PackageManagerService.java revision 50d946c13a5a47c6617530425479b0ad4f381700
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    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
846    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
847
848    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
849            = new SparseArray<IntentFilterVerificationState>();
850
851    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
852
853    // List of packages names to keep cached, even if they are uninstalled for all users
854    private List<String> mKeepUninstalledPackages;
855
856    private UserManagerInternal mUserManagerInternal;
857
858    private DeviceIdleController.LocalService mDeviceIdleController;
859
860    private File mCacheDir;
861
862    private ArraySet<String> mPrivappPermissionsViolations;
863
864    private Future<?> mPrepareAppDataFuture;
865
866    private static class IFVerificationParams {
867        PackageParser.Package pkg;
868        boolean replacing;
869        int userId;
870        int verifierUid;
871
872        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
873                int _userId, int _verifierUid) {
874            pkg = _pkg;
875            replacing = _replacing;
876            userId = _userId;
877            replacing = _replacing;
878            verifierUid = _verifierUid;
879        }
880    }
881
882    private interface IntentFilterVerifier<T extends IntentFilter> {
883        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
884                                               T filter, String packageName);
885        void startVerifications(int userId);
886        void receiveVerificationResponse(int verificationId);
887    }
888
889    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
890        private Context mContext;
891        private ComponentName mIntentFilterVerifierComponent;
892        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
893
894        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
895            mContext = context;
896            mIntentFilterVerifierComponent = verifierComponent;
897        }
898
899        private String getDefaultScheme() {
900            return IntentFilter.SCHEME_HTTPS;
901        }
902
903        @Override
904        public void startVerifications(int userId) {
905            // Launch verifications requests
906            int count = mCurrentIntentFilterVerifications.size();
907            for (int n=0; n<count; n++) {
908                int verificationId = mCurrentIntentFilterVerifications.get(n);
909                final IntentFilterVerificationState ivs =
910                        mIntentFilterVerificationStates.get(verificationId);
911
912                String packageName = ivs.getPackageName();
913
914                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
915                final int filterCount = filters.size();
916                ArraySet<String> domainsSet = new ArraySet<>();
917                for (int m=0; m<filterCount; m++) {
918                    PackageParser.ActivityIntentInfo filter = filters.get(m);
919                    domainsSet.addAll(filter.getHostsList());
920                }
921                synchronized (mPackages) {
922                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
923                            packageName, domainsSet) != null) {
924                        scheduleWriteSettingsLocked();
925                    }
926                }
927                sendVerificationRequest(userId, verificationId, ivs);
928            }
929            mCurrentIntentFilterVerifications.clear();
930        }
931
932        private void sendVerificationRequest(int userId, int verificationId,
933                IntentFilterVerificationState ivs) {
934
935            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
938                    verificationId);
939            verificationIntent.putExtra(
940                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
941                    getDefaultScheme());
942            verificationIntent.putExtra(
943                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
944                    ivs.getHostsString());
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
947                    ivs.getPackageName());
948            verificationIntent.setComponent(mIntentFilterVerifierComponent);
949            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
950
951            UserHandle user = new UserHandle(userId);
952            mContext.sendBroadcastAsUser(verificationIntent, user);
953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
954                    "Sending IntentFilter verification broadcast");
955        }
956
957        public void receiveVerificationResponse(int verificationId) {
958            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
959
960            final boolean verified = ivs.isVerified();
961
962            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
963            final int count = filters.size();
964            if (DEBUG_DOMAIN_VERIFICATION) {
965                Slog.i(TAG, "Received verification response " + verificationId
966                        + " for " + count + " filters, verified=" + verified);
967            }
968            for (int n=0; n<count; n++) {
969                PackageParser.ActivityIntentInfo filter = filters.get(n);
970                filter.setVerified(verified);
971
972                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
973                        + " verified with result:" + verified + " and hosts:"
974                        + ivs.getHostsString());
975            }
976
977            mIntentFilterVerificationStates.remove(verificationId);
978
979            final String packageName = ivs.getPackageName();
980            IntentFilterVerificationInfo ivi = null;
981
982            synchronized (mPackages) {
983                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
984            }
985            if (ivi == null) {
986                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
987                        + verificationId + " packageName:" + packageName);
988                return;
989            }
990            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
991                    "Updating IntentFilterVerificationInfo for package " + packageName
992                            +" verificationId:" + verificationId);
993
994            synchronized (mPackages) {
995                if (verified) {
996                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
997                } else {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
999                }
1000                scheduleWriteSettingsLocked();
1001
1002                final int userId = ivs.getUserId();
1003                if (userId != UserHandle.USER_ALL) {
1004                    final int userStatus =
1005                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1006
1007                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1008                    boolean needUpdate = false;
1009
1010                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1011                    // already been set by the User thru the Disambiguation dialog
1012                    switch (userStatus) {
1013                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1014                            if (verified) {
1015                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1016                            } else {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1018                            }
1019                            needUpdate = true;
1020                            break;
1021
1022                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1023                            if (verified) {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1025                                needUpdate = true;
1026                            }
1027                            break;
1028
1029                        default:
1030                            // Nothing to do
1031                    }
1032
1033                    if (needUpdate) {
1034                        mSettings.updateIntentFilterVerificationStatusLPw(
1035                                packageName, updatedStatus, userId);
1036                        scheduleWritePackageRestrictionsLocked(userId);
1037                    }
1038                }
1039            }
1040        }
1041
1042        @Override
1043        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1044                    ActivityIntentInfo filter, String packageName) {
1045            if (!hasValidDomains(filter)) {
1046                return false;
1047            }
1048            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1049            if (ivs == null) {
1050                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1051                        packageName);
1052            }
1053            if (DEBUG_DOMAIN_VERIFICATION) {
1054                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1055            }
1056            ivs.addFilter(filter);
1057            return true;
1058        }
1059
1060        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1061                int userId, int verificationId, String packageName) {
1062            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1063                    verifierUid, userId, packageName);
1064            ivs.setPendingState();
1065            synchronized (mPackages) {
1066                mIntentFilterVerificationStates.append(verificationId, ivs);
1067                mCurrentIntentFilterVerifications.add(verificationId);
1068            }
1069            return ivs;
1070        }
1071    }
1072
1073    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1074        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1075                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1076                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1077    }
1078
1079    // Set of pending broadcasts for aggregating enable/disable of components.
1080    static class PendingPackageBroadcasts {
1081        // for each user id, a map of <package name -> components within that package>
1082        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1083
1084        public PendingPackageBroadcasts() {
1085            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1086        }
1087
1088        public ArrayList<String> get(int userId, String packageName) {
1089            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1090            return packages.get(packageName);
1091        }
1092
1093        public void put(int userId, String packageName, ArrayList<String> components) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            packages.put(packageName, components);
1096        }
1097
1098        public void remove(int userId, String packageName) {
1099            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1100            if (packages != null) {
1101                packages.remove(packageName);
1102            }
1103        }
1104
1105        public void remove(int userId) {
1106            mUidMap.remove(userId);
1107        }
1108
1109        public int userIdCount() {
1110            return mUidMap.size();
1111        }
1112
1113        public int userIdAt(int n) {
1114            return mUidMap.keyAt(n);
1115        }
1116
1117        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1118            return mUidMap.get(userId);
1119        }
1120
1121        public int size() {
1122            // total number of pending broadcast entries across all userIds
1123            int num = 0;
1124            for (int i = 0; i< mUidMap.size(); i++) {
1125                num += mUidMap.valueAt(i).size();
1126            }
1127            return num;
1128        }
1129
1130        public void clear() {
1131            mUidMap.clear();
1132        }
1133
1134        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1135            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1136            if (map == null) {
1137                map = new ArrayMap<String, ArrayList<String>>();
1138                mUidMap.put(userId, map);
1139            }
1140            return map;
1141        }
1142    }
1143    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1144
1145    // Service Connection to remote media container service to copy
1146    // package uri's from external media onto secure containers
1147    // or internal storage.
1148    private IMediaContainerService mContainerService = null;
1149
1150    static final int SEND_PENDING_BROADCAST = 1;
1151    static final int MCS_BOUND = 3;
1152    static final int END_COPY = 4;
1153    static final int INIT_COPY = 5;
1154    static final int MCS_UNBIND = 6;
1155    static final int START_CLEANING_PACKAGE = 7;
1156    static final int FIND_INSTALL_LOC = 8;
1157    static final int POST_INSTALL = 9;
1158    static final int MCS_RECONNECT = 10;
1159    static final int MCS_GIVE_UP = 11;
1160    static final int UPDATED_MEDIA_STATUS = 12;
1161    static final int WRITE_SETTINGS = 13;
1162    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1163    static final int PACKAGE_VERIFIED = 15;
1164    static final int CHECK_PENDING_VERIFICATION = 16;
1165    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1166    static final int INTENT_FILTER_VERIFIED = 18;
1167    static final int WRITE_PACKAGE_LIST = 19;
1168    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1169
1170    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1171
1172    // Delay time in millisecs
1173    static final int BROADCAST_DELAY = 10 * 1000;
1174
1175    static UserManagerService sUserManager;
1176
1177    // Stores a list of users whose package restrictions file needs to be updated
1178    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1179
1180    final private DefaultContainerConnection mDefContainerConn =
1181            new DefaultContainerConnection();
1182    class DefaultContainerConnection implements ServiceConnection {
1183        public void onServiceConnected(ComponentName name, IBinder service) {
1184            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1185            final IMediaContainerService imcs = IMediaContainerService.Stub
1186                    .asInterface(Binder.allowBlocking(service));
1187            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1188        }
1189
1190        public void onServiceDisconnected(ComponentName name) {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1192        }
1193    }
1194
1195    // Recordkeeping of restore-after-install operations that are currently in flight
1196    // between the Package Manager and the Backup Manager
1197    static class PostInstallData {
1198        public InstallArgs args;
1199        public PackageInstalledInfo res;
1200
1201        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1202            args = _a;
1203            res = _r;
1204        }
1205    }
1206
1207    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1208    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1209
1210    // XML tags for backup/restore of various bits of state
1211    private static final String TAG_PREFERRED_BACKUP = "pa";
1212    private static final String TAG_DEFAULT_APPS = "da";
1213    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1214
1215    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1216    private static final String TAG_ALL_GRANTS = "rt-grants";
1217    private static final String TAG_GRANT = "grant";
1218    private static final String ATTR_PACKAGE_NAME = "pkg";
1219
1220    private static final String TAG_PERMISSION = "perm";
1221    private static final String ATTR_PERMISSION_NAME = "name";
1222    private static final String ATTR_IS_GRANTED = "g";
1223    private static final String ATTR_USER_SET = "set";
1224    private static final String ATTR_USER_FIXED = "fixed";
1225    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1226
1227    // System/policy permission grants are not backed up
1228    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1229            FLAG_PERMISSION_POLICY_FIXED
1230            | FLAG_PERMISSION_SYSTEM_FIXED
1231            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1232
1233    // And we back up these user-adjusted states
1234    private static final int USER_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_USER_SET
1236            | FLAG_PERMISSION_USER_FIXED
1237            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1238
1239    final @Nullable String mRequiredVerifierPackage;
1240    final @NonNull String mRequiredInstallerPackage;
1241    final @NonNull String mRequiredUninstallerPackage;
1242    final @Nullable String mSetupWizardPackage;
1243    final @Nullable String mStorageManagerPackage;
1244    final @NonNull String mServicesSystemSharedLibraryPackageName;
1245    final @NonNull String mSharedSystemSharedLibraryPackageName;
1246
1247    final boolean mPermissionReviewRequired;
1248
1249    private final PackageUsage mPackageUsage = new PackageUsage();
1250    private final CompilerStats mCompilerStats = new CompilerStats();
1251
1252    class PackageHandler extends Handler {
1253        private boolean mBound = false;
1254        final ArrayList<HandlerParams> mPendingInstalls =
1255            new ArrayList<HandlerParams>();
1256
1257        private boolean connectToService() {
1258            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1259                    " DefaultContainerService");
1260            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1261            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1263                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1264                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265                mBound = true;
1266                return true;
1267            }
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269            return false;
1270        }
1271
1272        private void disconnectService() {
1273            mContainerService = null;
1274            mBound = false;
1275            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276            mContext.unbindService(mDefContainerConn);
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1278        }
1279
1280        PackageHandler(Looper looper) {
1281            super(looper);
1282        }
1283
1284        public void handleMessage(Message msg) {
1285            try {
1286                doHandleMessage(msg);
1287            } finally {
1288                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289            }
1290        }
1291
1292        void doHandleMessage(Message msg) {
1293            switch (msg.what) {
1294                case INIT_COPY: {
1295                    HandlerParams params = (HandlerParams) msg.obj;
1296                    int idx = mPendingInstalls.size();
1297                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1298                    // If a bind was already initiated we dont really
1299                    // need to do anything. The pending install
1300                    // will be processed later on.
1301                    if (!mBound) {
1302                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1303                                System.identityHashCode(mHandler));
1304                        // If this is the only one pending we might
1305                        // have to bind to the service again.
1306                        if (!connectToService()) {
1307                            Slog.e(TAG, "Failed to bind to media container service");
1308                            params.serviceError();
1309                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                    System.identityHashCode(mHandler));
1311                            if (params.traceMethod != null) {
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1313                                        params.traceCookie);
1314                            }
1315                            return;
1316                        } else {
1317                            // Once we bind to the service, the first
1318                            // pending request will be processed.
1319                            mPendingInstalls.add(idx, params);
1320                        }
1321                    } else {
1322                        mPendingInstalls.add(idx, params);
1323                        // Already bound to the service. Just make
1324                        // sure we trigger off processing the first request.
1325                        if (idx == 0) {
1326                            mHandler.sendEmptyMessage(MCS_BOUND);
1327                        }
1328                    }
1329                    break;
1330                }
1331                case MCS_BOUND: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1333                    if (msg.obj != null) {
1334                        mContainerService = (IMediaContainerService) msg.obj;
1335                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1336                                System.identityHashCode(mHandler));
1337                    }
1338                    if (mContainerService == null) {
1339                        if (!mBound) {
1340                            // Something seriously wrong since we are not bound and we are not
1341                            // waiting for connection. Bail out.
1342                            Slog.e(TAG, "Cannot bind to media container service");
1343                            for (HandlerParams params : mPendingInstalls) {
1344                                // Indicate service bind error
1345                                params.serviceError();
1346                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                                        System.identityHashCode(params));
1348                                if (params.traceMethod != null) {
1349                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1350                                            params.traceMethod, params.traceCookie);
1351                                }
1352                                return;
1353                            }
1354                            mPendingInstalls.clear();
1355                        } else {
1356                            Slog.w(TAG, "Waiting to connect to media container service");
1357                        }
1358                    } else if (mPendingInstalls.size() > 0) {
1359                        HandlerParams params = mPendingInstalls.get(0);
1360                        if (params != null) {
1361                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1362                                    System.identityHashCode(params));
1363                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1364                            if (params.startCopy()) {
1365                                // We are done...  look for more work or to
1366                                // go idle.
1367                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1368                                        "Checking for more work or unbind...");
1369                                // Delete pending install
1370                                if (mPendingInstalls.size() > 0) {
1371                                    mPendingInstalls.remove(0);
1372                                }
1373                                if (mPendingInstalls.size() == 0) {
1374                                    if (mBound) {
1375                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1376                                                "Posting delayed MCS_UNBIND");
1377                                        removeMessages(MCS_UNBIND);
1378                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1379                                        // Unbind after a little delay, to avoid
1380                                        // continual thrashing.
1381                                        sendMessageDelayed(ubmsg, 10000);
1382                                    }
1383                                } else {
1384                                    // There are more pending requests in queue.
1385                                    // Just post MCS_BOUND message to trigger processing
1386                                    // of next pending install.
1387                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1388                                            "Posting MCS_BOUND for next work");
1389                                    mHandler.sendEmptyMessage(MCS_BOUND);
1390                                }
1391                            }
1392                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1393                        }
1394                    } else {
1395                        // Should never happen ideally.
1396                        Slog.w(TAG, "Empty queue");
1397                    }
1398                    break;
1399                }
1400                case MCS_RECONNECT: {
1401                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1402                    if (mPendingInstalls.size() > 0) {
1403                        if (mBound) {
1404                            disconnectService();
1405                        }
1406                        if (!connectToService()) {
1407                            Slog.e(TAG, "Failed to bind to media container service");
1408                            for (HandlerParams params : mPendingInstalls) {
1409                                // Indicate service bind error
1410                                params.serviceError();
1411                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1412                                        System.identityHashCode(params));
1413                            }
1414                            mPendingInstalls.clear();
1415                        }
1416                    }
1417                    break;
1418                }
1419                case MCS_UNBIND: {
1420                    // If there is no actual work left, then time to unbind.
1421                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1422
1423                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1424                        if (mBound) {
1425                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1426
1427                            disconnectService();
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        // There are more pending requests in queue.
1431                        // Just post MCS_BOUND message to trigger processing
1432                        // of next pending install.
1433                        mHandler.sendEmptyMessage(MCS_BOUND);
1434                    }
1435
1436                    break;
1437                }
1438                case MCS_GIVE_UP: {
1439                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1440                    HandlerParams params = mPendingInstalls.remove(0);
1441                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                            System.identityHashCode(params));
1443                    break;
1444                }
1445                case SEND_PENDING_BROADCAST: {
1446                    String packages[];
1447                    ArrayList<String> components[];
1448                    int size = 0;
1449                    int uids[];
1450                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1451                    synchronized (mPackages) {
1452                        if (mPendingBroadcasts == null) {
1453                            return;
1454                        }
1455                        size = mPendingBroadcasts.size();
1456                        if (size <= 0) {
1457                            // Nothing to be done. Just return
1458                            return;
1459                        }
1460                        packages = new String[size];
1461                        components = new ArrayList[size];
1462                        uids = new int[size];
1463                        int i = 0;  // filling out the above arrays
1464
1465                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1466                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1467                            Iterator<Map.Entry<String, ArrayList<String>>> it
1468                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1469                                            .entrySet().iterator();
1470                            while (it.hasNext() && i < size) {
1471                                Map.Entry<String, ArrayList<String>> ent = it.next();
1472                                packages[i] = ent.getKey();
1473                                components[i] = ent.getValue();
1474                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1475                                uids[i] = (ps != null)
1476                                        ? UserHandle.getUid(packageUserId, ps.appId)
1477                                        : -1;
1478                                i++;
1479                            }
1480                        }
1481                        size = i;
1482                        mPendingBroadcasts.clear();
1483                    }
1484                    // Send broadcasts
1485                    for (int i = 0; i < size; i++) {
1486                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                    break;
1490                }
1491                case START_CLEANING_PACKAGE: {
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1493                    final String packageName = (String)msg.obj;
1494                    final int userId = msg.arg1;
1495                    final boolean andCode = msg.arg2 != 0;
1496                    synchronized (mPackages) {
1497                        if (userId == UserHandle.USER_ALL) {
1498                            int[] users = sUserManager.getUserIds();
1499                            for (int user : users) {
1500                                mSettings.addPackageToCleanLPw(
1501                                        new PackageCleanItem(user, packageName, andCode));
1502                            }
1503                        } else {
1504                            mSettings.addPackageToCleanLPw(
1505                                    new PackageCleanItem(userId, packageName, andCode));
1506                        }
1507                    }
1508                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1509                    startCleaningPackages();
1510                } break;
1511                case POST_INSTALL: {
1512                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1513
1514                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1515                    final boolean didRestore = (msg.arg2 != 0);
1516                    mRunningInstalls.delete(msg.arg1);
1517
1518                    if (data != null) {
1519                        InstallArgs args = data.args;
1520                        PackageInstalledInfo parentRes = data.res;
1521
1522                        final boolean grantPermissions = (args.installFlags
1523                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1524                        final boolean killApp = (args.installFlags
1525                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1526                        final String[] grantedPermissions = args.installGrantPermissions;
1527
1528                        // Handle the parent package
1529                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1530                                grantedPermissions, didRestore, args.installerPackageName,
1531                                args.observer);
1532
1533                        // Handle the child packages
1534                        final int childCount = (parentRes.addedChildPackages != null)
1535                                ? parentRes.addedChildPackages.size() : 0;
1536                        for (int i = 0; i < childCount; i++) {
1537                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1538                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1539                                    grantedPermissions, false, args.installerPackageName,
1540                                    args.observer);
1541                        }
1542
1543                        // Log tracing if needed
1544                        if (args.traceMethod != null) {
1545                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1546                                    args.traceCookie);
1547                        }
1548                    } else {
1549                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1550                    }
1551
1552                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1553                } break;
1554                case UPDATED_MEDIA_STATUS: {
1555                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1556                    boolean reportStatus = msg.arg1 == 1;
1557                    boolean doGc = msg.arg2 == 1;
1558                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1559                    if (doGc) {
1560                        // Force a gc to clear up stale containers.
1561                        Runtime.getRuntime().gc();
1562                    }
1563                    if (msg.obj != null) {
1564                        @SuppressWarnings("unchecked")
1565                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1566                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1567                        // Unload containers
1568                        unloadAllContainers(args);
1569                    }
1570                    if (reportStatus) {
1571                        try {
1572                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1573                                    "Invoking StorageManagerService call back");
1574                            PackageHelper.getStorageManager().finishMediaUpdate();
1575                        } catch (RemoteException e) {
1576                            Log.e(TAG, "StorageManagerService not running?");
1577                        }
1578                    }
1579                } break;
1580                case WRITE_SETTINGS: {
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1582                    synchronized (mPackages) {
1583                        removeMessages(WRITE_SETTINGS);
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        mSettings.writeLPr();
1586                        mDirtyUsers.clear();
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                } break;
1590                case WRITE_PACKAGE_RESTRICTIONS: {
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1592                    synchronized (mPackages) {
1593                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1594                        for (int userId : mDirtyUsers) {
1595                            mSettings.writePackageRestrictionsLPr(userId);
1596                        }
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_LIST: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_LIST);
1605                        mSettings.writePackageListLPr(msg.arg1);
1606                    }
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1608                } break;
1609                case CHECK_PENDING_VERIFICATION: {
1610                    final int verificationId = msg.arg1;
1611                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1612
1613                    if ((state != null) && !state.timeoutExtended()) {
1614                        final InstallArgs args = state.getInstallArgs();
1615                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1616
1617                        Slog.i(TAG, "Verification timed out for " + originUri);
1618                        mPendingVerification.remove(verificationId);
1619
1620                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1621
1622                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1623                            Slog.i(TAG, "Continuing with installation of " + originUri);
1624                            state.setVerifierResponse(Binder.getCallingUid(),
1625                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1626                            broadcastPackageVerified(verificationId, originUri,
1627                                    PackageManager.VERIFICATION_ALLOW,
1628                                    state.getInstallArgs().getUser());
1629                            try {
1630                                ret = args.copyApk(mContainerService, true);
1631                            } catch (RemoteException e) {
1632                                Slog.e(TAG, "Could not contact the ContainerService");
1633                            }
1634                        } else {
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    PackageManager.VERIFICATION_REJECT,
1637                                    state.getInstallArgs().getUser());
1638                        }
1639
1640                        Trace.asyncTraceEnd(
1641                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1642
1643                        processPendingInstall(args, ret);
1644                        mHandler.sendEmptyMessage(MCS_UNBIND);
1645                    }
1646                    break;
1647                }
1648                case PACKAGE_VERIFIED: {
1649                    final int verificationId = msg.arg1;
1650
1651                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1652                    if (state == null) {
1653                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1654                        break;
1655                    }
1656
1657                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1658
1659                    state.setVerifierResponse(response.callerUid, response.code);
1660
1661                    if (state.isVerificationComplete()) {
1662                        mPendingVerification.remove(verificationId);
1663
1664                        final InstallArgs args = state.getInstallArgs();
1665                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1666
1667                        int ret;
1668                        if (state.isInstallAllowed()) {
1669                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1670                            broadcastPackageVerified(verificationId, originUri,
1671                                    response.code, state.getInstallArgs().getUser());
1672                            try {
1673                                ret = args.copyApk(mContainerService, true);
1674                            } catch (RemoteException e) {
1675                                Slog.e(TAG, "Could not contact the ContainerService");
1676                            }
1677                        } else {
1678                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1679                        }
1680
1681                        Trace.asyncTraceEnd(
1682                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1683
1684                        processPendingInstall(args, ret);
1685                        mHandler.sendEmptyMessage(MCS_UNBIND);
1686                    }
1687
1688                    break;
1689                }
1690                case START_INTENT_FILTER_VERIFICATIONS: {
1691                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1692                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1693                            params.replacing, params.pkg);
1694                    break;
1695                }
1696                case INTENT_FILTER_VERIFIED: {
1697                    final int verificationId = msg.arg1;
1698
1699                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1700                            verificationId);
1701                    if (state == null) {
1702                        Slog.w(TAG, "Invalid IntentFilter verification token "
1703                                + verificationId + " received");
1704                        break;
1705                    }
1706
1707                    final int userId = state.getUserId();
1708
1709                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1710                            "Processing IntentFilter verification with token:"
1711                            + verificationId + " and userId:" + userId);
1712
1713                    final IntentFilterVerificationResponse response =
1714                            (IntentFilterVerificationResponse) msg.obj;
1715
1716                    state.setVerifierResponse(response.callerUid, response.code);
1717
1718                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1719                            "IntentFilter verification with token:" + verificationId
1720                            + " and userId:" + userId
1721                            + " is settings verifier response with response code:"
1722                            + response.code);
1723
1724                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1725                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1726                                + response.getFailedDomainsString());
1727                    }
1728
1729                    if (state.isVerificationComplete()) {
1730                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1731                    } else {
1732                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1733                                "IntentFilter verification with token:" + verificationId
1734                                + " was not said to be complete");
1735                    }
1736
1737                    break;
1738                }
1739                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1740                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1741                            mInstantAppResolverConnection,
1742                            (InstantAppRequest) msg.obj,
1743                            mInstantAppInstallerActivity,
1744                            mHandler);
1745                }
1746            }
1747        }
1748    }
1749
1750    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1751            boolean killApp, String[] grantedPermissions,
1752            boolean launchedForRestore, String installerPackage,
1753            IPackageInstallObserver2 installObserver) {
1754        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1755            // Send the removed broadcasts
1756            if (res.removedInfo != null) {
1757                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1758            }
1759
1760            // Now that we successfully installed the package, grant runtime
1761            // permissions if requested before broadcasting the install. Also
1762            // for legacy apps in permission review mode we clear the permission
1763            // review flag which is used to emulate runtime permissions for
1764            // legacy apps.
1765            if (grantPermissions) {
1766                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1767            }
1768
1769            final boolean update = res.removedInfo != null
1770                    && res.removedInfo.removedPackage != null;
1771
1772            // If this is the first time we have child packages for a disabled privileged
1773            // app that had no children, we grant requested runtime permissions to the new
1774            // children if the parent on the system image had them already granted.
1775            if (res.pkg.parentPackage != null) {
1776                synchronized (mPackages) {
1777                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1778                }
1779            }
1780
1781            synchronized (mPackages) {
1782                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1783            }
1784
1785            final String packageName = res.pkg.applicationInfo.packageName;
1786
1787            // Determine the set of users who are adding this package for
1788            // the first time vs. those who are seeing an update.
1789            int[] firstUsers = EMPTY_INT_ARRAY;
1790            int[] updateUsers = EMPTY_INT_ARRAY;
1791            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1792            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1793            for (int newUser : res.newUsers) {
1794                if (ps.getInstantApp(newUser)) {
1795                    continue;
1796                }
1797                if (allNewUsers) {
1798                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1799                    continue;
1800                }
1801                boolean isNew = true;
1802                for (int origUser : res.origUsers) {
1803                    if (origUser == newUser) {
1804                        isNew = false;
1805                        break;
1806                    }
1807                }
1808                if (isNew) {
1809                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1810                } else {
1811                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1812                }
1813            }
1814
1815            // Send installed broadcasts if the package is not a static shared lib.
1816            if (res.pkg.staticSharedLibName == null) {
1817                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1818
1819                // Send added for users that see the package for the first time
1820                // sendPackageAddedForNewUsers also deals with system apps
1821                int appId = UserHandle.getAppId(res.uid);
1822                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1823                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1824
1825                // Send added for users that don't see the package for the first time
1826                Bundle extras = new Bundle(1);
1827                extras.putInt(Intent.EXTRA_UID, res.uid);
1828                if (update) {
1829                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1830                }
1831                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1832                        extras, 0 /*flags*/, null /*targetPackage*/,
1833                        null /*finishedReceiver*/, updateUsers);
1834
1835                // Send replaced for users that don't see the package for the first time
1836                if (update) {
1837                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1838                            packageName, extras, 0 /*flags*/,
1839                            null /*targetPackage*/, null /*finishedReceiver*/,
1840                            updateUsers);
1841                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1842                            null /*package*/, null /*extras*/, 0 /*flags*/,
1843                            packageName /*targetPackage*/,
1844                            null /*finishedReceiver*/, updateUsers);
1845                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1846                    // First-install and we did a restore, so we're responsible for the
1847                    // first-launch broadcast.
1848                    if (DEBUG_BACKUP) {
1849                        Slog.i(TAG, "Post-restore of " + packageName
1850                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1851                    }
1852                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1853                }
1854
1855                // Send broadcast package appeared if forward locked/external for all users
1856                // treat asec-hosted packages like removable media on upgrade
1857                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1858                    if (DEBUG_INSTALL) {
1859                        Slog.i(TAG, "upgrading pkg " + res.pkg
1860                                + " is ASEC-hosted -> AVAILABLE");
1861                    }
1862                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1863                    ArrayList<String> pkgList = new ArrayList<>(1);
1864                    pkgList.add(packageName);
1865                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1866                }
1867            }
1868
1869            // Work that needs to happen on first install within each user
1870            if (firstUsers != null && firstUsers.length > 0) {
1871                synchronized (mPackages) {
1872                    for (int userId : firstUsers) {
1873                        // If this app is a browser and it's newly-installed for some
1874                        // users, clear any default-browser state in those users. The
1875                        // app's nature doesn't depend on the user, so we can just check
1876                        // its browser nature in any user and generalize.
1877                        if (packageIsBrowser(packageName, userId)) {
1878                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1879                        }
1880
1881                        // We may also need to apply pending (restored) runtime
1882                        // permission grants within these users.
1883                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1884                    }
1885                }
1886            }
1887
1888            // Log current value of "unknown sources" setting
1889            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1890                    getUnknownSourcesSettings());
1891
1892            // Force a gc to clear up things
1893            Runtime.getRuntime().gc();
1894
1895            // Remove the replaced package's older resources safely now
1896            // We delete after a gc for applications  on sdcard.
1897            if (res.removedInfo != null && res.removedInfo.args != null) {
1898                synchronized (mInstallLock) {
1899                    res.removedInfo.args.doPostDeleteLI(true);
1900                }
1901            }
1902
1903            // Notify DexManager that the package was installed for new users.
1904            // The updated users should already be indexed and the package code paths
1905            // should not change.
1906            // Don't notify the manager for ephemeral apps as they are not expected to
1907            // survive long enough to benefit of background optimizations.
1908            for (int userId : firstUsers) {
1909                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1910                mDexManager.notifyPackageInstalled(info, userId);
1911            }
1912        }
1913
1914        // If someone is watching installs - notify them
1915        if (installObserver != null) {
1916            try {
1917                Bundle extras = extrasForInstallResult(res);
1918                installObserver.onPackageInstalled(res.name, res.returnCode,
1919                        res.returnMsg, extras);
1920            } catch (RemoteException e) {
1921                Slog.i(TAG, "Observer no longer exists.");
1922            }
1923        }
1924    }
1925
1926    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1927            PackageParser.Package pkg) {
1928        if (pkg.parentPackage == null) {
1929            return;
1930        }
1931        if (pkg.requestedPermissions == null) {
1932            return;
1933        }
1934        final PackageSetting disabledSysParentPs = mSettings
1935                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1936        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1937                || !disabledSysParentPs.isPrivileged()
1938                || (disabledSysParentPs.childPackageNames != null
1939                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1940            return;
1941        }
1942        final int[] allUserIds = sUserManager.getUserIds();
1943        final int permCount = pkg.requestedPermissions.size();
1944        for (int i = 0; i < permCount; i++) {
1945            String permission = pkg.requestedPermissions.get(i);
1946            BasePermission bp = mSettings.mPermissions.get(permission);
1947            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1948                continue;
1949            }
1950            for (int userId : allUserIds) {
1951                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1952                        permission, userId)) {
1953                    grantRuntimePermission(pkg.packageName, permission, userId);
1954                }
1955            }
1956        }
1957    }
1958
1959    private StorageEventListener mStorageListener = new StorageEventListener() {
1960        @Override
1961        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1962            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1963                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1964                    final String volumeUuid = vol.getFsUuid();
1965
1966                    // Clean up any users or apps that were removed or recreated
1967                    // while this volume was missing
1968                    sUserManager.reconcileUsers(volumeUuid);
1969                    reconcileApps(volumeUuid);
1970
1971                    // Clean up any install sessions that expired or were
1972                    // cancelled while this volume was missing
1973                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1974
1975                    loadPrivatePackages(vol);
1976
1977                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1978                    unloadPrivatePackages(vol);
1979                }
1980            }
1981
1982            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1983                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1984                    updateExternalMediaStatus(true, false);
1985                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1986                    updateExternalMediaStatus(false, false);
1987                }
1988            }
1989        }
1990
1991        @Override
1992        public void onVolumeForgotten(String fsUuid) {
1993            if (TextUtils.isEmpty(fsUuid)) {
1994                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1995                return;
1996            }
1997
1998            // Remove any apps installed on the forgotten volume
1999            synchronized (mPackages) {
2000                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2001                for (PackageSetting ps : packages) {
2002                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2003                    deletePackageVersioned(new VersionedPackage(ps.name,
2004                            PackageManager.VERSION_CODE_HIGHEST),
2005                            new LegacyPackageDeleteObserver(null).getBinder(),
2006                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2007                    // Try very hard to release any references to this package
2008                    // so we don't risk the system server being killed due to
2009                    // open FDs
2010                    AttributeCache.instance().removePackage(ps.name);
2011                }
2012
2013                mSettings.onVolumeForgotten(fsUuid);
2014                mSettings.writeLPr();
2015            }
2016        }
2017    };
2018
2019    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2020            String[] grantedPermissions) {
2021        for (int userId : userIds) {
2022            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2023        }
2024    }
2025
2026    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2027            String[] grantedPermissions) {
2028        SettingBase sb = (SettingBase) pkg.mExtras;
2029        if (sb == null) {
2030            return;
2031        }
2032
2033        PermissionsState permissionsState = sb.getPermissionsState();
2034
2035        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2036                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2037
2038        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2039                >= Build.VERSION_CODES.M;
2040
2041        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2042
2043        for (String permission : pkg.requestedPermissions) {
2044            final BasePermission bp;
2045            synchronized (mPackages) {
2046                bp = mSettings.mPermissions.get(permission);
2047            }
2048            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2049                    && (!instantApp || bp.isInstant())
2050                    && (grantedPermissions == null
2051                           || ArrayUtils.contains(grantedPermissions, permission))) {
2052                final int flags = permissionsState.getPermissionFlags(permission, userId);
2053                if (supportsRuntimePermissions) {
2054                    // Installer cannot change immutable permissions.
2055                    if ((flags & immutableFlags) == 0) {
2056                        grantRuntimePermission(pkg.packageName, permission, userId);
2057                    }
2058                } else if (mPermissionReviewRequired) {
2059                    // In permission review mode we clear the review flag when we
2060                    // are asked to install the app with all permissions granted.
2061                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2062                        updatePermissionFlags(permission, pkg.packageName,
2063                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2064                    }
2065                }
2066            }
2067        }
2068    }
2069
2070    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2071        Bundle extras = null;
2072        switch (res.returnCode) {
2073            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2074                extras = new Bundle();
2075                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2076                        res.origPermission);
2077                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2078                        res.origPackage);
2079                break;
2080            }
2081            case PackageManager.INSTALL_SUCCEEDED: {
2082                extras = new Bundle();
2083                extras.putBoolean(Intent.EXTRA_REPLACING,
2084                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2085                break;
2086            }
2087        }
2088        return extras;
2089    }
2090
2091    void scheduleWriteSettingsLocked() {
2092        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2093            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2094        }
2095    }
2096
2097    void scheduleWritePackageListLocked(int userId) {
2098        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2099            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2100            msg.arg1 = userId;
2101            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2102        }
2103    }
2104
2105    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2106        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2107        scheduleWritePackageRestrictionsLocked(userId);
2108    }
2109
2110    void scheduleWritePackageRestrictionsLocked(int userId) {
2111        final int[] userIds = (userId == UserHandle.USER_ALL)
2112                ? sUserManager.getUserIds() : new int[]{userId};
2113        for (int nextUserId : userIds) {
2114            if (!sUserManager.exists(nextUserId)) return;
2115            mDirtyUsers.add(nextUserId);
2116            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2117                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2118            }
2119        }
2120    }
2121
2122    public static PackageManagerService main(Context context, Installer installer,
2123            boolean factoryTest, boolean onlyCore) {
2124        // Self-check for initial settings.
2125        PackageManagerServiceCompilerMapping.checkProperties();
2126
2127        PackageManagerService m = new PackageManagerService(context, installer,
2128                factoryTest, onlyCore);
2129        m.enableSystemUserPackages();
2130        ServiceManager.addService("package", m);
2131        return m;
2132    }
2133
2134    private void enableSystemUserPackages() {
2135        if (!UserManager.isSplitSystemUser()) {
2136            return;
2137        }
2138        // For system user, enable apps based on the following conditions:
2139        // - app is whitelisted or belong to one of these groups:
2140        //   -- system app which has no launcher icons
2141        //   -- system app which has INTERACT_ACROSS_USERS permission
2142        //   -- system IME app
2143        // - app is not in the blacklist
2144        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2145        Set<String> enableApps = new ArraySet<>();
2146        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2147                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2148                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2149        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2150        enableApps.addAll(wlApps);
2151        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2152                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2153        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2154        enableApps.removeAll(blApps);
2155        Log.i(TAG, "Applications installed for system user: " + enableApps);
2156        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2157                UserHandle.SYSTEM);
2158        final int allAppsSize = allAps.size();
2159        synchronized (mPackages) {
2160            for (int i = 0; i < allAppsSize; i++) {
2161                String pName = allAps.get(i);
2162                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2163                // Should not happen, but we shouldn't be failing if it does
2164                if (pkgSetting == null) {
2165                    continue;
2166                }
2167                boolean install = enableApps.contains(pName);
2168                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2169                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2170                            + " for system user");
2171                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2172                }
2173            }
2174            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2175        }
2176    }
2177
2178    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2179        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2180                Context.DISPLAY_SERVICE);
2181        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2182    }
2183
2184    /**
2185     * Requests that files preopted on a secondary system partition be copied to the data partition
2186     * if possible.  Note that the actual copying of the files is accomplished by init for security
2187     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2188     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2189     */
2190    private static void requestCopyPreoptedFiles() {
2191        final int WAIT_TIME_MS = 100;
2192        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2193        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2194            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2195            // We will wait for up to 100 seconds.
2196            final long timeStart = SystemClock.uptimeMillis();
2197            final long timeEnd = timeStart + 100 * 1000;
2198            long timeNow = timeStart;
2199            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2200                try {
2201                    Thread.sleep(WAIT_TIME_MS);
2202                } catch (InterruptedException e) {
2203                    // Do nothing
2204                }
2205                timeNow = SystemClock.uptimeMillis();
2206                if (timeNow > timeEnd) {
2207                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2208                    Slog.wtf(TAG, "cppreopt did not finish!");
2209                    break;
2210                }
2211            }
2212
2213            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2214        }
2215    }
2216
2217    public PackageManagerService(Context context, Installer installer,
2218            boolean factoryTest, boolean onlyCore) {
2219        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2220        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2221        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2222                SystemClock.uptimeMillis());
2223
2224        if (mSdkVersion <= 0) {
2225            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2226        }
2227
2228        mContext = context;
2229
2230        mPermissionReviewRequired = context.getResources().getBoolean(
2231                R.bool.config_permissionReviewRequired);
2232
2233        mFactoryTest = factoryTest;
2234        mOnlyCore = onlyCore;
2235        mMetrics = new DisplayMetrics();
2236        mSettings = new Settings(mPackages);
2237        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249
2250        String separateProcesses = SystemProperties.get("debug.separate_processes");
2251        if (separateProcesses != null && separateProcesses.length() > 0) {
2252            if ("*".equals(separateProcesses)) {
2253                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2254                mSeparateProcesses = null;
2255                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2256            } else {
2257                mDefParseFlags = 0;
2258                mSeparateProcesses = separateProcesses.split(",");
2259                Slog.w(TAG, "Running with debug.separate_processes: "
2260                        + separateProcesses);
2261            }
2262        } else {
2263            mDefParseFlags = 0;
2264            mSeparateProcesses = null;
2265        }
2266
2267        mInstaller = installer;
2268        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2269                "*dexopt*");
2270        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2271        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2272
2273        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2274                FgThread.get().getLooper());
2275
2276        getDefaultDisplayMetrics(context, mMetrics);
2277
2278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2279        SystemConfig systemConfig = SystemConfig.getInstance();
2280        mGlobalGids = systemConfig.getGlobalGids();
2281        mSystemPermissions = systemConfig.getSystemPermissions();
2282        mAvailableFeatures = systemConfig.getAvailableFeatures();
2283        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2284
2285        mProtectedPackages = new ProtectedPackages(mContext);
2286
2287        synchronized (mInstallLock) {
2288        // writer
2289        synchronized (mPackages) {
2290            mHandlerThread = new ServiceThread(TAG,
2291                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2292            mHandlerThread.start();
2293            mHandler = new PackageHandler(mHandlerThread.getLooper());
2294            mProcessLoggingHandler = new ProcessLoggingHandler();
2295            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2296
2297            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2298            mInstantAppRegistry = new InstantAppRegistry(this);
2299
2300            File dataDir = Environment.getDataDirectory();
2301            mAppInstallDir = new File(dataDir, "app");
2302            mAppLib32InstallDir = new File(dataDir, "app-lib");
2303            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2304            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2305            sUserManager = new UserManagerService(context, this,
2306                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2307
2308            // Propagate permission configuration in to package manager.
2309            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2310                    = systemConfig.getPermissions();
2311            for (int i=0; i<permConfig.size(); i++) {
2312                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2313                BasePermission bp = mSettings.mPermissions.get(perm.name);
2314                if (bp == null) {
2315                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2316                    mSettings.mPermissions.put(perm.name, bp);
2317                }
2318                if (perm.gids != null) {
2319                    bp.setGids(perm.gids, perm.perUser);
2320                }
2321            }
2322
2323            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2324            final int builtInLibCount = libConfig.size();
2325            for (int i = 0; i < builtInLibCount; i++) {
2326                String name = libConfig.keyAt(i);
2327                String path = libConfig.valueAt(i);
2328                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2329                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2330            }
2331
2332            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2333
2334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2335            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2337
2338            // Clean up orphaned packages for which the code path doesn't exist
2339            // and they are an update to a system app - caused by bug/32321269
2340            final int packageSettingCount = mSettings.mPackages.size();
2341            for (int i = packageSettingCount - 1; i >= 0; i--) {
2342                PackageSetting ps = mSettings.mPackages.valueAt(i);
2343                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2344                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2345                    mSettings.mPackages.removeAt(i);
2346                    mSettings.enableSystemPackageLPw(ps.name);
2347                }
2348            }
2349
2350            if (mFirstBoot) {
2351                requestCopyPreoptedFiles();
2352            }
2353
2354            String customResolverActivity = Resources.getSystem().getString(
2355                    R.string.config_customResolverActivity);
2356            if (TextUtils.isEmpty(customResolverActivity)) {
2357                customResolverActivity = null;
2358            } else {
2359                mCustomResolverComponentName = ComponentName.unflattenFromString(
2360                        customResolverActivity);
2361            }
2362
2363            long startTime = SystemClock.uptimeMillis();
2364
2365            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2366                    startTime);
2367
2368            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2369            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2370
2371            if (bootClassPath == null) {
2372                Slog.w(TAG, "No BOOTCLASSPATH found!");
2373            }
2374
2375            if (systemServerClassPath == null) {
2376                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2377            }
2378
2379            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2380            final String[] dexCodeInstructionSets =
2381                    getDexCodeInstructionSets(
2382                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2383
2384            /**
2385             * Ensure all external libraries have had dexopt run on them.
2386             */
2387            if (mSharedLibraries.size() > 0) {
2388                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2389                // NOTE: For now, we're compiling these system "shared libraries"
2390                // (and framework jars) into all available architectures. It's possible
2391                // to compile them only when we come across an app that uses them (there's
2392                // already logic for that in scanPackageLI) but that adds some complexity.
2393                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2394                    final int libCount = mSharedLibraries.size();
2395                    for (int i = 0; i < libCount; i++) {
2396                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2397                        final int versionCount = versionedLib.size();
2398                        for (int j = 0; j < versionCount; j++) {
2399                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2400                            final String libPath = libEntry.path != null
2401                                    ? libEntry.path : libEntry.apk;
2402                            if (libPath == null) {
2403                                continue;
2404                            }
2405                            try {
2406                                // Shared libraries do not have profiles so we perform a full
2407                                // AOT compilation (if needed).
2408                                int dexoptNeeded = DexFile.getDexOptNeeded(
2409                                        libPath, dexCodeInstructionSet,
2410                                        getCompilerFilterForReason(REASON_SHARED_APK),
2411                                        false /* newProfile */);
2412                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2413                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2414                                            dexCodeInstructionSet, dexoptNeeded, null,
2415                                            DEXOPT_PUBLIC,
2416                                            getCompilerFilterForReason(REASON_SHARED_APK),
2417                                            StorageManager.UUID_PRIVATE_INTERNAL,
2418                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2419                                }
2420                            } catch (FileNotFoundException e) {
2421                                Slog.w(TAG, "Library not found: " + libPath);
2422                            } catch (IOException | InstallerException e) {
2423                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2424                                        + e.getMessage());
2425                            }
2426                        }
2427                    }
2428                }
2429                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2430            }
2431
2432            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2433
2434            final VersionInfo ver = mSettings.getInternalVersion();
2435            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2436
2437            // when upgrading from pre-M, promote system app permissions from install to runtime
2438            mPromoteSystemApps =
2439                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2440
2441            // When upgrading from pre-N, we need to handle package extraction like first boot,
2442            // as there is no profiling data available.
2443            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2444
2445            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2446
2447            // save off the names of pre-existing system packages prior to scanning; we don't
2448            // want to automatically grant runtime permissions for new system apps
2449            if (mPromoteSystemApps) {
2450                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2451                while (pkgSettingIter.hasNext()) {
2452                    PackageSetting ps = pkgSettingIter.next();
2453                    if (isSystemApp(ps)) {
2454                        mExistingSystemPackages.add(ps.name);
2455                    }
2456                }
2457            }
2458
2459            mCacheDir = preparePackageParserCache(mIsUpgrade);
2460
2461            // Set flag to monitor and not change apk file paths when
2462            // scanning install directories.
2463            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2464
2465            if (mIsUpgrade || mFirstBoot) {
2466                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2467            }
2468
2469            // Collect vendor overlay packages. (Do this before scanning any apps.)
2470            // For security and version matching reason, only consider
2471            // overlay packages if they reside in the right directory.
2472            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2476
2477            // Find base frameworks (resource packages without code).
2478            scanDirTracedLI(frameworkDir, mDefParseFlags
2479                    | PackageParser.PARSE_IS_SYSTEM
2480                    | PackageParser.PARSE_IS_SYSTEM_DIR
2481                    | PackageParser.PARSE_IS_PRIVILEGED,
2482                    scanFlags | SCAN_NO_DEX, 0);
2483
2484            // Collected privileged system packages.
2485            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2486            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2490
2491            // Collect ordinary system packages.
2492            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2493            scanDirTracedLI(systemAppDir, mDefParseFlags
2494                    | PackageParser.PARSE_IS_SYSTEM
2495                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2496
2497            // Collect all vendor packages.
2498            File vendorAppDir = new File("/vendor/app");
2499            try {
2500                vendorAppDir = vendorAppDir.getCanonicalFile();
2501            } catch (IOException e) {
2502                // failed to look up canonical path, continue with original one
2503            }
2504            scanDirTracedLI(vendorAppDir, mDefParseFlags
2505                    | PackageParser.PARSE_IS_SYSTEM
2506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2507
2508            // Collect all OEM packages.
2509            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2510            scanDirTracedLI(oemAppDir, mDefParseFlags
2511                    | PackageParser.PARSE_IS_SYSTEM
2512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2513
2514            // Prune any system packages that no longer exist.
2515            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2516            if (!mOnlyCore) {
2517                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2518                while (psit.hasNext()) {
2519                    PackageSetting ps = psit.next();
2520
2521                    /*
2522                     * If this is not a system app, it can't be a
2523                     * disable system app.
2524                     */
2525                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2526                        continue;
2527                    }
2528
2529                    /*
2530                     * If the package is scanned, it's not erased.
2531                     */
2532                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2533                    if (scannedPkg != null) {
2534                        /*
2535                         * If the system app is both scanned and in the
2536                         * disabled packages list, then it must have been
2537                         * added via OTA. Remove it from the currently
2538                         * scanned package so the previously user-installed
2539                         * application can be scanned.
2540                         */
2541                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2542                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2543                                    + ps.name + "; removing system app.  Last known codePath="
2544                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2545                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2546                                    + scannedPkg.mVersionCode);
2547                            removePackageLI(scannedPkg, true);
2548                            mExpectingBetter.put(ps.name, ps.codePath);
2549                        }
2550
2551                        continue;
2552                    }
2553
2554                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2555                        psit.remove();
2556                        logCriticalInfo(Log.WARN, "System package " + ps.name
2557                                + " no longer exists; it's data will be wiped");
2558                        // Actual deletion of code and data will be handled by later
2559                        // reconciliation step
2560                    } else {
2561                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2562                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2563                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2564                        }
2565                    }
2566                }
2567            }
2568
2569            //look for any incomplete package installations
2570            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2571            for (int i = 0; i < deletePkgsList.size(); i++) {
2572                // Actual deletion of code and data will be handled by later
2573                // reconciliation step
2574                final String packageName = deletePkgsList.get(i).name;
2575                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2576                synchronized (mPackages) {
2577                    mSettings.removePackageLPw(packageName);
2578                }
2579            }
2580
2581            //delete tmp files
2582            deleteTempPackageFiles();
2583
2584            // Remove any shared userIDs that have no associated packages
2585            mSettings.pruneSharedUsersLPw();
2586
2587            if (!mOnlyCore) {
2588                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2589                        SystemClock.uptimeMillis());
2590                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2591
2592                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2593                        | PackageParser.PARSE_FORWARD_LOCK,
2594                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2595
2596                /**
2597                 * Remove disable package settings for any updated system
2598                 * apps that were removed via an OTA. If they're not a
2599                 * previously-updated app, remove them completely.
2600                 * Otherwise, just revoke their system-level permissions.
2601                 */
2602                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2603                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2604                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2605
2606                    String msg;
2607                    if (deletedPkg == null) {
2608                        msg = "Updated system package " + deletedAppName
2609                                + " no longer exists; it's data will be wiped";
2610                        // Actual deletion of code and data will be handled by later
2611                        // reconciliation step
2612                    } else {
2613                        msg = "Updated system app + " + deletedAppName
2614                                + " no longer present; removing system privileges for "
2615                                + deletedAppName;
2616
2617                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2618
2619                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2620                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2621                    }
2622                    logCriticalInfo(Log.WARN, msg);
2623                }
2624
2625                /**
2626                 * Make sure all system apps that we expected to appear on
2627                 * the userdata partition actually showed up. If they never
2628                 * appeared, crawl back and revive the system version.
2629                 */
2630                for (int i = 0; i < mExpectingBetter.size(); i++) {
2631                    final String packageName = mExpectingBetter.keyAt(i);
2632                    if (!mPackages.containsKey(packageName)) {
2633                        final File scanFile = mExpectingBetter.valueAt(i);
2634
2635                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2636                                + " but never showed up; reverting to system");
2637
2638                        int reparseFlags = mDefParseFlags;
2639                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2640                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2641                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2642                                    | PackageParser.PARSE_IS_PRIVILEGED;
2643                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2650                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2651                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2652                        } else {
2653                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2654                            continue;
2655                        }
2656
2657                        mSettings.enableSystemPackageLPw(packageName);
2658
2659                        try {
2660                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2661                        } catch (PackageManagerException e) {
2662                            Slog.e(TAG, "Failed to parse original system package: "
2663                                    + e.getMessage());
2664                        }
2665                    }
2666                }
2667            }
2668            mExpectingBetter.clear();
2669
2670            // Resolve the storage manager.
2671            mStorageManagerPackage = getStorageManagerPackageName();
2672
2673            // Resolve protected action filters. Only the setup wizard is allowed to
2674            // have a high priority filter for these actions.
2675            mSetupWizardPackage = getSetupWizardPackageName();
2676            if (mProtectedFilters.size() > 0) {
2677                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2678                    Slog.i(TAG, "No setup wizard;"
2679                        + " All protected intents capped to priority 0");
2680                }
2681                for (ActivityIntentInfo filter : mProtectedFilters) {
2682                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2683                        if (DEBUG_FILTERS) {
2684                            Slog.i(TAG, "Found setup wizard;"
2685                                + " allow priority " + filter.getPriority() + ";"
2686                                + " package: " + filter.activity.info.packageName
2687                                + " activity: " + filter.activity.className
2688                                + " priority: " + filter.getPriority());
2689                        }
2690                        // skip setup wizard; allow it to keep the high priority filter
2691                        continue;
2692                    }
2693                    Slog.w(TAG, "Protected action; cap priority to 0;"
2694                            + " package: " + filter.activity.info.packageName
2695                            + " activity: " + filter.activity.className
2696                            + " origPrio: " + filter.getPriority());
2697                    filter.setPriority(0);
2698                }
2699            }
2700            mDeferProtectedFilters = false;
2701            mProtectedFilters.clear();
2702
2703            // Now that we know all of the shared libraries, update all clients to have
2704            // the correct library paths.
2705            updateAllSharedLibrariesLPw(null);
2706
2707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2708                // NOTE: We ignore potential failures here during a system scan (like
2709                // the rest of the commands above) because there's precious little we
2710                // can do about it. A settings error is reported, though.
2711                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2712            }
2713
2714            // Now that we know all the packages we are keeping,
2715            // read and update their last usage times.
2716            mPackageUsage.read(mPackages);
2717            mCompilerStats.read();
2718
2719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2720                    SystemClock.uptimeMillis());
2721            Slog.i(TAG, "Time to scan packages: "
2722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2723                    + " seconds");
2724
2725            // If the platform SDK has changed since the last time we booted,
2726            // we need to re-grant app permission to catch any new ones that
2727            // appear.  This is really a hack, and means that apps can in some
2728            // cases get permissions that the user didn't initially explicitly
2729            // allow...  it would be nice to have some better way to handle
2730            // this situation.
2731            int updateFlags = UPDATE_PERMISSIONS_ALL;
2732            if (ver.sdkVersion != mSdkVersion) {
2733                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2734                        + mSdkVersion + "; regranting permissions for internal storage");
2735                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2736            }
2737            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2738            ver.sdkVersion = mSdkVersion;
2739
2740            // If this is the first boot or an update from pre-M, and it is a normal
2741            // boot, then we need to initialize the default preferred apps across
2742            // all defined users.
2743            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2744                for (UserInfo user : sUserManager.getUsers(true)) {
2745                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2746                    applyFactoryDefaultBrowserLPw(user.id);
2747                    primeDomainVerificationsLPw(user.id);
2748                }
2749            }
2750
2751            // Prepare storage for system user really early during boot,
2752            // since core system apps like SettingsProvider and SystemUI
2753            // can't wait for user to start
2754            final int storageFlags;
2755            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2756                storageFlags = StorageManager.FLAG_STORAGE_DE;
2757            } else {
2758                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2759            }
2760            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2761                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2762                    true /* onlyCoreApps */);
2763            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2764                if (deferPackages == null || deferPackages.isEmpty()) {
2765                    return;
2766                }
2767                int count = 0;
2768                for (String pkgName : deferPackages) {
2769                    PackageParser.Package pkg = null;
2770                    synchronized (mPackages) {
2771                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2772                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2773                            pkg = ps.pkg;
2774                        }
2775                    }
2776                    if (pkg != null) {
2777                        synchronized (mInstallLock) {
2778                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2779                                    true /* maybeMigrateAppData */);
2780                        }
2781                        count++;
2782                    }
2783                }
2784                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2785            }, "prepareAppData");
2786
2787            // If this is first boot after an OTA, and a normal boot, then
2788            // we need to clear code cache directories.
2789            // Note that we do *not* clear the application profiles. These remain valid
2790            // across OTAs and are used to drive profile verification (post OTA) and
2791            // profile compilation (without waiting to collect a fresh set of profiles).
2792            if (mIsUpgrade && !onlyCore) {
2793                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2794                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2795                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2796                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2797                        // No apps are running this early, so no need to freeze
2798                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2799                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2800                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2801                    }
2802                }
2803                ver.fingerprint = Build.FINGERPRINT;
2804            }
2805
2806            checkDefaultBrowser();
2807
2808            // clear only after permissions and other defaults have been updated
2809            mExistingSystemPackages.clear();
2810            mPromoteSystemApps = false;
2811
2812            // All the changes are done during package scanning.
2813            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2814
2815            // can downgrade to reader
2816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2817            mSettings.writeLPr();
2818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2819
2820            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2821            // early on (before the package manager declares itself as early) because other
2822            // components in the system server might ask for package contexts for these apps.
2823            //
2824            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2825            // (i.e, that the data partition is unavailable).
2826            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2827                long start = System.nanoTime();
2828                List<PackageParser.Package> coreApps = new ArrayList<>();
2829                for (PackageParser.Package pkg : mPackages.values()) {
2830                    if (pkg.coreApp) {
2831                        coreApps.add(pkg);
2832                    }
2833                }
2834
2835                int[] stats = performDexOptUpgrade(coreApps, false,
2836                        getCompilerFilterForReason(REASON_CORE_APP));
2837
2838                final int elapsedTimeSeconds =
2839                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2840                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2841
2842                if (DEBUG_DEXOPT) {
2843                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2844                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2845                }
2846
2847
2848                // TODO: Should we log these stats to tron too ?
2849                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2850                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2851                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2852                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2853            }
2854
2855            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2856                    SystemClock.uptimeMillis());
2857
2858            if (!mOnlyCore) {
2859                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2860                mRequiredInstallerPackage = getRequiredInstallerLPr();
2861                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2862                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2863                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2864                        mIntentFilterVerifierComponent);
2865                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2866                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2867                        SharedLibraryInfo.VERSION_UNDEFINED);
2868                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2869                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2870                        SharedLibraryInfo.VERSION_UNDEFINED);
2871            } else {
2872                mRequiredVerifierPackage = null;
2873                mRequiredInstallerPackage = null;
2874                mRequiredUninstallerPackage = null;
2875                mIntentFilterVerifierComponent = null;
2876                mIntentFilterVerifier = null;
2877                mServicesSystemSharedLibraryPackageName = null;
2878                mSharedSystemSharedLibraryPackageName = null;
2879            }
2880
2881            mInstallerService = new PackageInstallerService(context, this);
2882
2883            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2884            if (ephemeralResolverComponent != null) {
2885                if (DEBUG_EPHEMERAL) {
2886                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2887                }
2888                mInstantAppResolverConnection =
2889                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2890            } else {
2891                mInstantAppResolverConnection = null;
2892            }
2893            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2894            if (mInstantAppInstallerComponent != null) {
2895                if (DEBUG_EPHEMERAL) {
2896                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2897                }
2898                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2899            }
2900
2901            // Read and update the usage of dex files.
2902            // Do this at the end of PM init so that all the packages have their
2903            // data directory reconciled.
2904            // At this point we know the code paths of the packages, so we can validate
2905            // the disk file and build the internal cache.
2906            // The usage file is expected to be small so loading and verifying it
2907            // should take a fairly small time compare to the other activities (e.g. package
2908            // scanning).
2909            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2910            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2911            for (int userId : currentUserIds) {
2912                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2913            }
2914            mDexManager.load(userPackages);
2915        } // synchronized (mPackages)
2916        } // synchronized (mInstallLock)
2917
2918        // Now after opening every single application zip, make sure they
2919        // are all flushed.  Not really needed, but keeps things nice and
2920        // tidy.
2921        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2922        Runtime.getRuntime().gc();
2923        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2924
2925        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2926        FallbackCategoryProvider.loadFallbacks();
2927        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2928
2929        // The initial scanning above does many calls into installd while
2930        // holding the mPackages lock, but we're mostly interested in yelling
2931        // once we have a booted system.
2932        mInstaller.setWarnIfHeld(mPackages);
2933
2934        // Expose private service for system components to use.
2935        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2936        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2937    }
2938
2939    private static File preparePackageParserCache(boolean isUpgrade) {
2940        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2941            return null;
2942        }
2943
2944        // Disable package parsing on eng builds to allow for faster incremental development.
2945        if ("eng".equals(Build.TYPE)) {
2946            return null;
2947        }
2948
2949        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2950            Slog.i(TAG, "Disabling package parser cache due to system property.");
2951            return null;
2952        }
2953
2954        // The base directory for the package parser cache lives under /data/system/.
2955        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2956                "package_cache");
2957        if (cacheBaseDir == null) {
2958            return null;
2959        }
2960
2961        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2962        // This also serves to "GC" unused entries when the package cache version changes (which
2963        // can only happen during upgrades).
2964        if (isUpgrade) {
2965            FileUtils.deleteContents(cacheBaseDir);
2966        }
2967
2968
2969        // Return the versioned package cache directory. This is something like
2970        // "/data/system/package_cache/1"
2971        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2972
2973        // The following is a workaround to aid development on non-numbered userdebug
2974        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2975        // the system partition is newer.
2976        //
2977        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2978        // that starts with "eng." to signify that this is an engineering build and not
2979        // destined for release.
2980        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2981            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2982
2983            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2984            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2985            // in general and should not be used for production changes. In this specific case,
2986            // we know that they will work.
2987            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2988            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2989                FileUtils.deleteContents(cacheBaseDir);
2990                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2991            }
2992        }
2993
2994        return cacheDir;
2995    }
2996
2997    @Override
2998    public boolean isFirstBoot() {
2999        return mFirstBoot;
3000    }
3001
3002    @Override
3003    public boolean isOnlyCoreApps() {
3004        return mOnlyCore;
3005    }
3006
3007    @Override
3008    public boolean isUpgrade() {
3009        return mIsUpgrade;
3010    }
3011
3012    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3013        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3014
3015        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3016                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3017                UserHandle.USER_SYSTEM);
3018        if (matches.size() == 1) {
3019            return matches.get(0).getComponentInfo().packageName;
3020        } else if (matches.size() == 0) {
3021            Log.e(TAG, "There should probably be a verifier, but, none were found");
3022            return null;
3023        }
3024        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3025    }
3026
3027    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3028        synchronized (mPackages) {
3029            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3030            if (libraryEntry == null) {
3031                throw new IllegalStateException("Missing required shared library:" + name);
3032            }
3033            return libraryEntry.apk;
3034        }
3035    }
3036
3037    private @NonNull String getRequiredInstallerLPr() {
3038        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3039        intent.addCategory(Intent.CATEGORY_DEFAULT);
3040        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3041
3042        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3043                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3044                UserHandle.USER_SYSTEM);
3045        if (matches.size() == 1) {
3046            ResolveInfo resolveInfo = matches.get(0);
3047            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3048                throw new RuntimeException("The installer must be a privileged app");
3049            }
3050            return matches.get(0).getComponentInfo().packageName;
3051        } else {
3052            throw new RuntimeException("There must be exactly one installer; found " + matches);
3053        }
3054    }
3055
3056    private @NonNull String getRequiredUninstallerLPr() {
3057        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3058        intent.addCategory(Intent.CATEGORY_DEFAULT);
3059        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3060
3061        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3062                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3063                UserHandle.USER_SYSTEM);
3064        if (resolveInfo == null ||
3065                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3066            throw new RuntimeException("There must be exactly one uninstaller; found "
3067                    + resolveInfo);
3068        }
3069        return resolveInfo.getComponentInfo().packageName;
3070    }
3071
3072    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3073        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3074
3075        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3076                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3077                UserHandle.USER_SYSTEM);
3078        ResolveInfo best = null;
3079        final int N = matches.size();
3080        for (int i = 0; i < N; i++) {
3081            final ResolveInfo cur = matches.get(i);
3082            final String packageName = cur.getComponentInfo().packageName;
3083            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3084                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3085                continue;
3086            }
3087
3088            if (best == null || cur.priority > best.priority) {
3089                best = cur;
3090            }
3091        }
3092
3093        if (best != null) {
3094            return best.getComponentInfo().getComponentName();
3095        } else {
3096            throw new RuntimeException("There must be at least one intent filter verifier");
3097        }
3098    }
3099
3100    private @Nullable ComponentName getEphemeralResolverLPr() {
3101        final String[] packageArray =
3102                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3103        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3104            if (DEBUG_EPHEMERAL) {
3105                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3106            }
3107            return null;
3108        }
3109
3110        final int resolveFlags =
3111                MATCH_DIRECT_BOOT_AWARE
3112                | MATCH_DIRECT_BOOT_UNAWARE
3113                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3114        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3115        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3116                resolveFlags, UserHandle.USER_SYSTEM);
3117
3118        final int N = resolvers.size();
3119        if (N == 0) {
3120            if (DEBUG_EPHEMERAL) {
3121                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3122            }
3123            return null;
3124        }
3125
3126        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3127        for (int i = 0; i < N; i++) {
3128            final ResolveInfo info = resolvers.get(i);
3129
3130            if (info.serviceInfo == null) {
3131                continue;
3132            }
3133
3134            final String packageName = info.serviceInfo.packageName;
3135            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3136                if (DEBUG_EPHEMERAL) {
3137                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3138                            + " pkg: " + packageName + ", info:" + info);
3139                }
3140                continue;
3141            }
3142
3143            if (DEBUG_EPHEMERAL) {
3144                Slog.v(TAG, "Ephemeral resolver found;"
3145                        + " pkg: " + packageName + ", info:" + info);
3146            }
3147            return new ComponentName(packageName, info.serviceInfo.name);
3148        }
3149        if (DEBUG_EPHEMERAL) {
3150            Slog.v(TAG, "Ephemeral resolver NOT found");
3151        }
3152        return null;
3153    }
3154
3155    private @Nullable ComponentName getEphemeralInstallerLPr() {
3156        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3157        intent.addCategory(Intent.CATEGORY_DEFAULT);
3158        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3159
3160        final int resolveFlags =
3161                MATCH_DIRECT_BOOT_AWARE
3162                | MATCH_DIRECT_BOOT_UNAWARE
3163                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3164        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3165                resolveFlags, UserHandle.USER_SYSTEM);
3166        Iterator<ResolveInfo> iter = matches.iterator();
3167        while (iter.hasNext()) {
3168            final ResolveInfo rInfo = iter.next();
3169            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3170            if (ps != null) {
3171                final PermissionsState permissionsState = ps.getPermissionsState();
3172                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3173                    continue;
3174                }
3175            }
3176            iter.remove();
3177        }
3178        if (matches.size() == 0) {
3179            return null;
3180        } else if (matches.size() == 1) {
3181            return matches.get(0).getComponentInfo().getComponentName();
3182        } else {
3183            throw new RuntimeException(
3184                    "There must be at most one ephemeral installer; found " + matches);
3185        }
3186    }
3187
3188    private void primeDomainVerificationsLPw(int userId) {
3189        if (DEBUG_DOMAIN_VERIFICATION) {
3190            Slog.d(TAG, "Priming domain verifications in user " + userId);
3191        }
3192
3193        SystemConfig systemConfig = SystemConfig.getInstance();
3194        ArraySet<String> packages = systemConfig.getLinkedApps();
3195
3196        for (String packageName : packages) {
3197            PackageParser.Package pkg = mPackages.get(packageName);
3198            if (pkg != null) {
3199                if (!pkg.isSystemApp()) {
3200                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3201                    continue;
3202                }
3203
3204                ArraySet<String> domains = null;
3205                for (PackageParser.Activity a : pkg.activities) {
3206                    for (ActivityIntentInfo filter : a.intents) {
3207                        if (hasValidDomains(filter)) {
3208                            if (domains == null) {
3209                                domains = new ArraySet<String>();
3210                            }
3211                            domains.addAll(filter.getHostsList());
3212                        }
3213                    }
3214                }
3215
3216                if (domains != null && domains.size() > 0) {
3217                    if (DEBUG_DOMAIN_VERIFICATION) {
3218                        Slog.v(TAG, "      + " + packageName);
3219                    }
3220                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3221                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3222                    // and then 'always' in the per-user state actually used for intent resolution.
3223                    final IntentFilterVerificationInfo ivi;
3224                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3225                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3226                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3227                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3228                } else {
3229                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3230                            + "' does not handle web links");
3231                }
3232            } else {
3233                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3234            }
3235        }
3236
3237        scheduleWritePackageRestrictionsLocked(userId);
3238        scheduleWriteSettingsLocked();
3239    }
3240
3241    private void applyFactoryDefaultBrowserLPw(int userId) {
3242        // The default browser app's package name is stored in a string resource,
3243        // with a product-specific overlay used for vendor customization.
3244        String browserPkg = mContext.getResources().getString(
3245                com.android.internal.R.string.default_browser);
3246        if (!TextUtils.isEmpty(browserPkg)) {
3247            // non-empty string => required to be a known package
3248            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3249            if (ps == null) {
3250                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3251                browserPkg = null;
3252            } else {
3253                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3254            }
3255        }
3256
3257        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3258        // default.  If there's more than one, just leave everything alone.
3259        if (browserPkg == null) {
3260            calculateDefaultBrowserLPw(userId);
3261        }
3262    }
3263
3264    private void calculateDefaultBrowserLPw(int userId) {
3265        List<String> allBrowsers = resolveAllBrowserApps(userId);
3266        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3267        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3268    }
3269
3270    private List<String> resolveAllBrowserApps(int userId) {
3271        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3272        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3273                PackageManager.MATCH_ALL, userId);
3274
3275        final int count = list.size();
3276        List<String> result = new ArrayList<String>(count);
3277        for (int i=0; i<count; i++) {
3278            ResolveInfo info = list.get(i);
3279            if (info.activityInfo == null
3280                    || !info.handleAllWebDataURI
3281                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3282                    || result.contains(info.activityInfo.packageName)) {
3283                continue;
3284            }
3285            result.add(info.activityInfo.packageName);
3286        }
3287
3288        return result;
3289    }
3290
3291    private boolean packageIsBrowser(String packageName, int userId) {
3292        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3293                PackageManager.MATCH_ALL, userId);
3294        final int N = list.size();
3295        for (int i = 0; i < N; i++) {
3296            ResolveInfo info = list.get(i);
3297            if (packageName.equals(info.activityInfo.packageName)) {
3298                return true;
3299            }
3300        }
3301        return false;
3302    }
3303
3304    private void checkDefaultBrowser() {
3305        final int myUserId = UserHandle.myUserId();
3306        final String packageName = getDefaultBrowserPackageName(myUserId);
3307        if (packageName != null) {
3308            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3309            if (info == null) {
3310                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3311                synchronized (mPackages) {
3312                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3313                }
3314            }
3315        }
3316    }
3317
3318    @Override
3319    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3320            throws RemoteException {
3321        try {
3322            return super.onTransact(code, data, reply, flags);
3323        } catch (RuntimeException e) {
3324            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3325                Slog.wtf(TAG, "Package Manager Crash", e);
3326            }
3327            throw e;
3328        }
3329    }
3330
3331    static int[] appendInts(int[] cur, int[] add) {
3332        if (add == null) return cur;
3333        if (cur == null) return add;
3334        final int N = add.length;
3335        for (int i=0; i<N; i++) {
3336            cur = appendInt(cur, add[i]);
3337        }
3338        return cur;
3339    }
3340
3341    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3342        if (!sUserManager.exists(userId)) return null;
3343        if (ps == null) {
3344            return null;
3345        }
3346        final PackageParser.Package p = ps.pkg;
3347        if (p == null) {
3348            return null;
3349        }
3350        // Filter out ephemeral app metadata:
3351        //   * The system/shell/root can see metadata for any app
3352        //   * An installed app can see metadata for 1) other installed apps
3353        //     and 2) ephemeral apps that have explicitly interacted with it
3354        //   * Ephemeral apps can only see their own data and exposed installed apps
3355        //   * Holding a signature permission allows seeing instant apps
3356        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3357        if (callingAppId != Process.SYSTEM_UID
3358                && callingAppId != Process.SHELL_UID
3359                && callingAppId != Process.ROOT_UID
3360                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3361                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3362            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3363            if (instantAppPackageName != null) {
3364                // ephemeral apps can only get information on themselves or
3365                // installed apps that are exposed.
3366                if (!instantAppPackageName.equals(p.packageName)
3367                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3368                    return null;
3369                }
3370            } else {
3371                if (ps.getInstantApp(userId)) {
3372                    // only get access to the ephemeral app if we've been granted access
3373                    if (!mInstantAppRegistry.isInstantAccessGranted(
3374                            userId, callingAppId, ps.appId)) {
3375                        return null;
3376                    }
3377                }
3378            }
3379        }
3380
3381        final PermissionsState permissionsState = ps.getPermissionsState();
3382
3383        // Compute GIDs only if requested
3384        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3385                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3386        // Compute granted permissions only if package has requested permissions
3387        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3388                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3389        final PackageUserState state = ps.readUserState(userId);
3390
3391        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3392                && ps.isSystem()) {
3393            flags |= MATCH_ANY_USER;
3394        }
3395
3396        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3397                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3398
3399        if (packageInfo == null) {
3400            return null;
3401        }
3402
3403        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3404
3405        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3406                resolveExternalPackageNameLPr(p);
3407
3408        return packageInfo;
3409    }
3410
3411    @Override
3412    public void checkPackageStartable(String packageName, int userId) {
3413        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3414
3415        synchronized (mPackages) {
3416            final PackageSetting ps = mSettings.mPackages.get(packageName);
3417            if (ps == null) {
3418                throw new SecurityException("Package " + packageName + " was not found!");
3419            }
3420
3421            if (!ps.getInstalled(userId)) {
3422                throw new SecurityException(
3423                        "Package " + packageName + " was not installed for user " + userId + "!");
3424            }
3425
3426            if (mSafeMode && !ps.isSystem()) {
3427                throw new SecurityException("Package " + packageName + " not a system app!");
3428            }
3429
3430            if (mFrozenPackages.contains(packageName)) {
3431                throw new SecurityException("Package " + packageName + " is currently frozen!");
3432            }
3433
3434            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3435                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3436                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3437            }
3438        }
3439    }
3440
3441    @Override
3442    public boolean isPackageAvailable(String packageName, int userId) {
3443        if (!sUserManager.exists(userId)) return false;
3444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3445                false /* requireFullPermission */, false /* checkShell */, "is package available");
3446        synchronized (mPackages) {
3447            PackageParser.Package p = mPackages.get(packageName);
3448            if (p != null) {
3449                final PackageSetting ps = (PackageSetting) p.mExtras;
3450                if (ps != null) {
3451                    final PackageUserState state = ps.readUserState(userId);
3452                    if (state != null) {
3453                        return PackageParser.isAvailable(state);
3454                    }
3455                }
3456            }
3457        }
3458        return false;
3459    }
3460
3461    @Override
3462    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3463        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3464                flags, userId);
3465    }
3466
3467    @Override
3468    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3469            int flags, int userId) {
3470        return getPackageInfoInternal(versionedPackage.getPackageName(),
3471                // TODO: We will change version code to long, so in the new API it is long
3472                (int) versionedPackage.getVersionCode(), flags, userId);
3473    }
3474
3475    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3476            int flags, int userId) {
3477        if (!sUserManager.exists(userId)) return null;
3478        flags = updateFlagsForPackage(flags, userId, packageName);
3479        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3480                false /* requireFullPermission */, false /* checkShell */, "get package info");
3481
3482        // reader
3483        synchronized (mPackages) {
3484            // Normalize package name to handle renamed packages and static libs
3485            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3486
3487            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3488            if (matchFactoryOnly) {
3489                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3490                if (ps != null) {
3491                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3492                        return null;
3493                    }
3494                    return generatePackageInfo(ps, flags, userId);
3495                }
3496            }
3497
3498            PackageParser.Package p = mPackages.get(packageName);
3499            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3500                return null;
3501            }
3502            if (DEBUG_PACKAGE_INFO)
3503                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3504            if (p != null) {
3505                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3506                        Binder.getCallingUid(), userId)) {
3507                    return null;
3508                }
3509                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3510            }
3511            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3512                final PackageSetting ps = mSettings.mPackages.get(packageName);
3513                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3514                    return null;
3515                }
3516                return generatePackageInfo(ps, flags, userId);
3517            }
3518        }
3519        return null;
3520    }
3521
3522
3523    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3524        // System/shell/root get to see all static libs
3525        final int appId = UserHandle.getAppId(uid);
3526        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3527                || appId == Process.ROOT_UID) {
3528            return false;
3529        }
3530
3531        // No package means no static lib as it is always on internal storage
3532        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3533            return false;
3534        }
3535
3536        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3537                ps.pkg.staticSharedLibVersion);
3538        if (libEntry == null) {
3539            return false;
3540        }
3541
3542        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3543        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3544        if (uidPackageNames == null) {
3545            return true;
3546        }
3547
3548        for (String uidPackageName : uidPackageNames) {
3549            if (ps.name.equals(uidPackageName)) {
3550                return false;
3551            }
3552            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3553            if (uidPs != null) {
3554                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3555                        libEntry.info.getName());
3556                if (index < 0) {
3557                    continue;
3558                }
3559                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3560                    return false;
3561                }
3562            }
3563        }
3564        return true;
3565    }
3566
3567    @Override
3568    public String[] currentToCanonicalPackageNames(String[] names) {
3569        String[] out = new String[names.length];
3570        // reader
3571        synchronized (mPackages) {
3572            for (int i=names.length-1; i>=0; i--) {
3573                PackageSetting ps = mSettings.mPackages.get(names[i]);
3574                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3575            }
3576        }
3577        return out;
3578    }
3579
3580    @Override
3581    public String[] canonicalToCurrentPackageNames(String[] names) {
3582        String[] out = new String[names.length];
3583        // reader
3584        synchronized (mPackages) {
3585            for (int i=names.length-1; i>=0; i--) {
3586                String cur = mSettings.getRenamedPackageLPr(names[i]);
3587                out[i] = cur != null ? cur : names[i];
3588            }
3589        }
3590        return out;
3591    }
3592
3593    @Override
3594    public int getPackageUid(String packageName, int flags, int userId) {
3595        if (!sUserManager.exists(userId)) return -1;
3596        flags = updateFlagsForPackage(flags, userId, packageName);
3597        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3598                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3599
3600        // reader
3601        synchronized (mPackages) {
3602            final PackageParser.Package p = mPackages.get(packageName);
3603            if (p != null && p.isMatch(flags)) {
3604                return UserHandle.getUid(userId, p.applicationInfo.uid);
3605            }
3606            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3607                final PackageSetting ps = mSettings.mPackages.get(packageName);
3608                if (ps != null && ps.isMatch(flags)) {
3609                    return UserHandle.getUid(userId, ps.appId);
3610                }
3611            }
3612        }
3613
3614        return -1;
3615    }
3616
3617    @Override
3618    public int[] getPackageGids(String packageName, int flags, int userId) {
3619        if (!sUserManager.exists(userId)) return null;
3620        flags = updateFlagsForPackage(flags, userId, packageName);
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3622                false /* requireFullPermission */, false /* checkShell */,
3623                "getPackageGids");
3624
3625        // reader
3626        synchronized (mPackages) {
3627            final PackageParser.Package p = mPackages.get(packageName);
3628            if (p != null && p.isMatch(flags)) {
3629                PackageSetting ps = (PackageSetting) p.mExtras;
3630                // TODO: Shouldn't this be checking for package installed state for userId and
3631                // return null?
3632                return ps.getPermissionsState().computeGids(userId);
3633            }
3634            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3635                final PackageSetting ps = mSettings.mPackages.get(packageName);
3636                if (ps != null && ps.isMatch(flags)) {
3637                    return ps.getPermissionsState().computeGids(userId);
3638                }
3639            }
3640        }
3641
3642        return null;
3643    }
3644
3645    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3646        if (bp.perm != null) {
3647            return PackageParser.generatePermissionInfo(bp.perm, flags);
3648        }
3649        PermissionInfo pi = new PermissionInfo();
3650        pi.name = bp.name;
3651        pi.packageName = bp.sourcePackage;
3652        pi.nonLocalizedLabel = bp.name;
3653        pi.protectionLevel = bp.protectionLevel;
3654        return pi;
3655    }
3656
3657    @Override
3658    public PermissionInfo getPermissionInfo(String name, int flags) {
3659        // reader
3660        synchronized (mPackages) {
3661            final BasePermission p = mSettings.mPermissions.get(name);
3662            if (p != null) {
3663                return generatePermissionInfo(p, flags);
3664            }
3665            return null;
3666        }
3667    }
3668
3669    @Override
3670    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3671            int flags) {
3672        // reader
3673        synchronized (mPackages) {
3674            if (group != null && !mPermissionGroups.containsKey(group)) {
3675                // This is thrown as NameNotFoundException
3676                return null;
3677            }
3678
3679            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3680            for (BasePermission p : mSettings.mPermissions.values()) {
3681                if (group == null) {
3682                    if (p.perm == null || p.perm.info.group == null) {
3683                        out.add(generatePermissionInfo(p, flags));
3684                    }
3685                } else {
3686                    if (p.perm != null && group.equals(p.perm.info.group)) {
3687                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3688                    }
3689                }
3690            }
3691            return new ParceledListSlice<>(out);
3692        }
3693    }
3694
3695    @Override
3696    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3697        // reader
3698        synchronized (mPackages) {
3699            return PackageParser.generatePermissionGroupInfo(
3700                    mPermissionGroups.get(name), flags);
3701        }
3702    }
3703
3704    @Override
3705    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3706        // reader
3707        synchronized (mPackages) {
3708            final int N = mPermissionGroups.size();
3709            ArrayList<PermissionGroupInfo> out
3710                    = new ArrayList<PermissionGroupInfo>(N);
3711            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3712                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3713            }
3714            return new ParceledListSlice<>(out);
3715        }
3716    }
3717
3718    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3719            int uid, int userId) {
3720        if (!sUserManager.exists(userId)) return null;
3721        PackageSetting ps = mSettings.mPackages.get(packageName);
3722        if (ps != null) {
3723            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3724                return null;
3725            }
3726            if (ps.pkg == null) {
3727                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3728                if (pInfo != null) {
3729                    return pInfo.applicationInfo;
3730                }
3731                return null;
3732            }
3733            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3734                    ps.readUserState(userId), userId);
3735            if (ai != null) {
3736                rebaseEnabledOverlays(ai, userId);
3737                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3738            }
3739            return ai;
3740        }
3741        return null;
3742    }
3743
3744    @Override
3745    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3746        if (!sUserManager.exists(userId)) return null;
3747        flags = updateFlagsForApplication(flags, userId, packageName);
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3749                false /* requireFullPermission */, false /* checkShell */, "get application info");
3750
3751        // writer
3752        synchronized (mPackages) {
3753            // Normalize package name to handle renamed packages and static libs
3754            packageName = resolveInternalPackageNameLPr(packageName,
3755                    PackageManager.VERSION_CODE_HIGHEST);
3756
3757            PackageParser.Package p = mPackages.get(packageName);
3758            if (DEBUG_PACKAGE_INFO) Log.v(
3759                    TAG, "getApplicationInfo " + packageName
3760                    + ": " + p);
3761            if (p != null) {
3762                PackageSetting ps = mSettings.mPackages.get(packageName);
3763                if (ps == null) return null;
3764                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3765                    return null;
3766                }
3767                // Note: isEnabledLP() does not apply here - always return info
3768                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3769                        p, flags, ps.readUserState(userId), userId);
3770                if (ai != null) {
3771                    rebaseEnabledOverlays(ai, userId);
3772                    ai.packageName = resolveExternalPackageNameLPr(p);
3773                }
3774                return ai;
3775            }
3776            if ("android".equals(packageName)||"system".equals(packageName)) {
3777                return mAndroidApplication;
3778            }
3779            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3780                // Already generates the external package name
3781                return generateApplicationInfoFromSettingsLPw(packageName,
3782                        Binder.getCallingUid(), flags, userId);
3783            }
3784        }
3785        return null;
3786    }
3787
3788    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3789        List<String> paths = new ArrayList<>();
3790        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3791            mEnabledOverlayPaths.get(userId);
3792        if (userSpecificOverlays != null) {
3793            if (!"android".equals(ai.packageName)) {
3794                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3795                if (frameworkOverlays != null) {
3796                    paths.addAll(frameworkOverlays);
3797                }
3798            }
3799
3800            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3801            if (appOverlays != null) {
3802                paths.addAll(appOverlays);
3803            }
3804        }
3805        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3806    }
3807
3808    private String normalizePackageNameLPr(String packageName) {
3809        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3810        return normalizedPackageName != null ? normalizedPackageName : packageName;
3811    }
3812
3813    @Override
3814    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3815            final IPackageDataObserver observer) {
3816        mContext.enforceCallingOrSelfPermission(
3817                android.Manifest.permission.CLEAR_APP_CACHE, null);
3818        mHandler.post(() -> {
3819            boolean success = false;
3820            try {
3821                freeStorage(volumeUuid, freeStorageSize, 0);
3822                success = true;
3823            } catch (IOException e) {
3824                Slog.w(TAG, e);
3825            }
3826            if (observer != null) {
3827                try {
3828                    observer.onRemoveCompleted(null, success);
3829                } catch (RemoteException e) {
3830                    Slog.w(TAG, e);
3831                }
3832            }
3833        });
3834    }
3835
3836    @Override
3837    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3838            final IntentSender pi) {
3839        mContext.enforceCallingOrSelfPermission(
3840                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3841        mHandler.post(() -> {
3842            boolean success = false;
3843            try {
3844                freeStorage(volumeUuid, freeStorageSize, 0);
3845                success = true;
3846            } catch (IOException e) {
3847                Slog.w(TAG, e);
3848            }
3849            if (pi != null) {
3850                try {
3851                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3852                } catch (SendIntentException e) {
3853                    Slog.w(TAG, e);
3854                }
3855            }
3856        });
3857    }
3858
3859    /**
3860     * Blocking call to clear various types of cached data across the system
3861     * until the requested bytes are available.
3862     */
3863    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3864        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3865        final File file = storage.findPathForUuid(volumeUuid);
3866
3867        if (ENABLE_FREE_CACHE_V2) {
3868            final boolean aggressive = (storageFlags
3869                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3870
3871            // 1. Pre-flight to determine if we have any chance to succeed
3872            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3873
3874            // 3. Consider parsed APK data (aggressive only)
3875            if (aggressive) {
3876                FileUtils.deleteContents(mCacheDir);
3877            }
3878            if (file.getUsableSpace() >= bytes) return;
3879
3880            // 4. Consider cached app data (above quotas)
3881            try {
3882                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3883            } catch (InstallerException ignored) {
3884            }
3885            if (file.getUsableSpace() >= bytes) return;
3886
3887            // 5. Consider shared libraries with refcount=0 and age>2h
3888            // 6. Consider dexopt output (aggressive only)
3889            // 7. Consider ephemeral apps not used in last week
3890
3891            // 8. Consider cached app data (below quotas)
3892            try {
3893                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3894                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3895            } catch (InstallerException ignored) {
3896            }
3897            if (file.getUsableSpace() >= bytes) return;
3898
3899            // 9. Consider DropBox entries
3900            // 10. Consider ephemeral cookies
3901
3902        } else {
3903            try {
3904                mInstaller.freeCache(volumeUuid, bytes, 0);
3905            } catch (InstallerException ignored) {
3906            }
3907            if (file.getUsableSpace() >= bytes) return;
3908        }
3909
3910        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3911    }
3912
3913    /**
3914     * Update given flags based on encryption status of current user.
3915     */
3916    private int updateFlags(int flags, int userId) {
3917        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3918                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3919            // Caller expressed an explicit opinion about what encryption
3920            // aware/unaware components they want to see, so fall through and
3921            // give them what they want
3922        } else {
3923            // Caller expressed no opinion, so match based on user state
3924            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3925                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3926            } else {
3927                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3928            }
3929        }
3930        return flags;
3931    }
3932
3933    private UserManagerInternal getUserManagerInternal() {
3934        if (mUserManagerInternal == null) {
3935            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3936        }
3937        return mUserManagerInternal;
3938    }
3939
3940    private DeviceIdleController.LocalService getDeviceIdleController() {
3941        if (mDeviceIdleController == null) {
3942            mDeviceIdleController =
3943                    LocalServices.getService(DeviceIdleController.LocalService.class);
3944        }
3945        return mDeviceIdleController;
3946    }
3947
3948    /**
3949     * Update given flags when being used to request {@link PackageInfo}.
3950     */
3951    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3952        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3953        boolean triaged = true;
3954        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3955                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3956            // Caller is asking for component details, so they'd better be
3957            // asking for specific encryption matching behavior, or be triaged
3958            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3959                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3960                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3961                triaged = false;
3962            }
3963        }
3964        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3965                | PackageManager.MATCH_SYSTEM_ONLY
3966                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3967            triaged = false;
3968        }
3969        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3970            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3971                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3972                    + Debug.getCallers(5));
3973        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3974                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3975            // If the caller wants all packages and has a restricted profile associated with it,
3976            // then match all users. This is to make sure that launchers that need to access work
3977            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3978            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3979            flags |= PackageManager.MATCH_ANY_USER;
3980        }
3981        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3982            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3983                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3984        }
3985        return updateFlags(flags, userId);
3986    }
3987
3988    /**
3989     * Update given flags when being used to request {@link ApplicationInfo}.
3990     */
3991    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3992        return updateFlagsForPackage(flags, userId, cookie);
3993    }
3994
3995    /**
3996     * Update given flags when being used to request {@link ComponentInfo}.
3997     */
3998    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3999        if (cookie instanceof Intent) {
4000            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4001                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4002            }
4003        }
4004
4005        boolean triaged = true;
4006        // Caller is asking for component details, so they'd better be
4007        // asking for specific encryption matching behavior, or be triaged
4008        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4009                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4010                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4011            triaged = false;
4012        }
4013        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4014            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4015                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4016        }
4017
4018        return updateFlags(flags, userId);
4019    }
4020
4021    /**
4022     * Update given intent when being used to request {@link ResolveInfo}.
4023     */
4024    private Intent updateIntentForResolve(Intent intent) {
4025        if (intent.getSelector() != null) {
4026            intent = intent.getSelector();
4027        }
4028        if (DEBUG_PREFERRED) {
4029            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4030        }
4031        return intent;
4032    }
4033
4034    /**
4035     * Update given flags when being used to request {@link ResolveInfo}.
4036     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4037     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4038     * flag set. However, this flag is only honoured in three circumstances:
4039     * <ul>
4040     * <li>when called from a system process</li>
4041     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4042     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4043     * action and a {@code android.intent.category.BROWSABLE} category</li>
4044     * </ul>
4045     */
4046    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4047        // Safe mode means we shouldn't match any third-party components
4048        if (mSafeMode) {
4049            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4050        }
4051        final int callingUid = Binder.getCallingUid();
4052        if (getInstantAppPackageName(callingUid) != null) {
4053            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4054            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4055            flags |= PackageManager.MATCH_INSTANT;
4056        } else {
4057            // Otherwise, prevent leaking ephemeral components
4058            final boolean isSpecialProcess =
4059                    callingUid == Process.SYSTEM_UID
4060                    || callingUid == Process.SHELL_UID
4061                    || callingUid == 0;
4062            final boolean allowMatchInstant =
4063                    (includeInstantApp
4064                            && Intent.ACTION_VIEW.equals(intent.getAction())
4065                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4066                            && hasWebURI(intent))
4067                    || isSpecialProcess
4068                    || mContext.checkCallingOrSelfPermission(
4069                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4070            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4071            if (!allowMatchInstant) {
4072                flags &= ~PackageManager.MATCH_INSTANT;
4073            }
4074        }
4075        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4076    }
4077
4078    @Override
4079    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4080        if (!sUserManager.exists(userId)) return null;
4081        flags = updateFlagsForComponent(flags, userId, component);
4082        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4083                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4084        synchronized (mPackages) {
4085            PackageParser.Activity a = mActivities.mActivities.get(component);
4086
4087            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4088            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4089                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4090                if (ps == null) return null;
4091                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4092                        userId);
4093            }
4094            if (mResolveComponentName.equals(component)) {
4095                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4096                        new PackageUserState(), userId);
4097            }
4098        }
4099        return null;
4100    }
4101
4102    @Override
4103    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4104            String resolvedType) {
4105        synchronized (mPackages) {
4106            if (component.equals(mResolveComponentName)) {
4107                // The resolver supports EVERYTHING!
4108                return true;
4109            }
4110            PackageParser.Activity a = mActivities.mActivities.get(component);
4111            if (a == null) {
4112                return false;
4113            }
4114            for (int i=0; i<a.intents.size(); i++) {
4115                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4116                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4117                    return true;
4118                }
4119            }
4120            return false;
4121        }
4122    }
4123
4124    @Override
4125    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4126        if (!sUserManager.exists(userId)) return null;
4127        flags = updateFlagsForComponent(flags, userId, component);
4128        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4129                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4130        synchronized (mPackages) {
4131            PackageParser.Activity a = mReceivers.mActivities.get(component);
4132            if (DEBUG_PACKAGE_INFO) Log.v(
4133                TAG, "getReceiverInfo " + component + ": " + a);
4134            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4135                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4136                if (ps == null) return null;
4137                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4138                        ps.readUserState(userId), userId);
4139                if (ri != null) {
4140                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4141                }
4142                return ri;
4143            }
4144        }
4145        return null;
4146    }
4147
4148    @Override
4149    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4150        if (!sUserManager.exists(userId)) return null;
4151        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4152
4153        flags = updateFlagsForPackage(flags, userId, null);
4154
4155        final boolean canSeeStaticLibraries =
4156                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4157                        == PERMISSION_GRANTED
4158                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4159                        == PERMISSION_GRANTED
4160                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4161                        == PERMISSION_GRANTED
4162                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4163                        == PERMISSION_GRANTED;
4164
4165        synchronized (mPackages) {
4166            List<SharedLibraryInfo> result = null;
4167
4168            final int libCount = mSharedLibraries.size();
4169            for (int i = 0; i < libCount; i++) {
4170                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4171                if (versionedLib == null) {
4172                    continue;
4173                }
4174
4175                final int versionCount = versionedLib.size();
4176                for (int j = 0; j < versionCount; j++) {
4177                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4178                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4179                        break;
4180                    }
4181                    final long identity = Binder.clearCallingIdentity();
4182                    try {
4183                        // TODO: We will change version code to long, so in the new API it is long
4184                        PackageInfo packageInfo = getPackageInfoVersioned(
4185                                libInfo.getDeclaringPackage(), flags, userId);
4186                        if (packageInfo == null) {
4187                            continue;
4188                        }
4189                    } finally {
4190                        Binder.restoreCallingIdentity(identity);
4191                    }
4192
4193                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4194                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4195                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4196
4197                    if (result == null) {
4198                        result = new ArrayList<>();
4199                    }
4200                    result.add(resLibInfo);
4201                }
4202            }
4203
4204            return result != null ? new ParceledListSlice<>(result) : null;
4205        }
4206    }
4207
4208    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4209            SharedLibraryInfo libInfo, int flags, int userId) {
4210        List<VersionedPackage> versionedPackages = null;
4211        final int packageCount = mSettings.mPackages.size();
4212        for (int i = 0; i < packageCount; i++) {
4213            PackageSetting ps = mSettings.mPackages.valueAt(i);
4214
4215            if (ps == null) {
4216                continue;
4217            }
4218
4219            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4220                continue;
4221            }
4222
4223            final String libName = libInfo.getName();
4224            if (libInfo.isStatic()) {
4225                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4226                if (libIdx < 0) {
4227                    continue;
4228                }
4229                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4230                    continue;
4231                }
4232                if (versionedPackages == null) {
4233                    versionedPackages = new ArrayList<>();
4234                }
4235                // If the dependent is a static shared lib, use the public package name
4236                String dependentPackageName = ps.name;
4237                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4238                    dependentPackageName = ps.pkg.manifestPackageName;
4239                }
4240                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4241            } else if (ps.pkg != null) {
4242                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4243                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4244                    if (versionedPackages == null) {
4245                        versionedPackages = new ArrayList<>();
4246                    }
4247                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4248                }
4249            }
4250        }
4251
4252        return versionedPackages;
4253    }
4254
4255    @Override
4256    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4257        if (!sUserManager.exists(userId)) return null;
4258        flags = updateFlagsForComponent(flags, userId, component);
4259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4260                false /* requireFullPermission */, false /* checkShell */, "get service info");
4261        synchronized (mPackages) {
4262            PackageParser.Service s = mServices.mServices.get(component);
4263            if (DEBUG_PACKAGE_INFO) Log.v(
4264                TAG, "getServiceInfo " + component + ": " + s);
4265            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4266                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4267                if (ps == null) return null;
4268                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4269                        ps.readUserState(userId), userId);
4270                if (si != null) {
4271                    rebaseEnabledOverlays(si.applicationInfo, userId);
4272                }
4273                return si;
4274            }
4275        }
4276        return null;
4277    }
4278
4279    @Override
4280    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4281        if (!sUserManager.exists(userId)) return null;
4282        flags = updateFlagsForComponent(flags, userId, component);
4283        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4284                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4285        synchronized (mPackages) {
4286            PackageParser.Provider p = mProviders.mProviders.get(component);
4287            if (DEBUG_PACKAGE_INFO) Log.v(
4288                TAG, "getProviderInfo " + component + ": " + p);
4289            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4290                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4291                if (ps == null) return null;
4292                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4293                        ps.readUserState(userId), userId);
4294                if (pi != null) {
4295                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4296                }
4297                return pi;
4298            }
4299        }
4300        return null;
4301    }
4302
4303    @Override
4304    public String[] getSystemSharedLibraryNames() {
4305        synchronized (mPackages) {
4306            Set<String> libs = null;
4307            final int libCount = mSharedLibraries.size();
4308            for (int i = 0; i < libCount; i++) {
4309                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4310                if (versionedLib == null) {
4311                    continue;
4312                }
4313                final int versionCount = versionedLib.size();
4314                for (int j = 0; j < versionCount; j++) {
4315                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4316                    if (!libEntry.info.isStatic()) {
4317                        if (libs == null) {
4318                            libs = new ArraySet<>();
4319                        }
4320                        libs.add(libEntry.info.getName());
4321                        break;
4322                    }
4323                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4324                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4325                            UserHandle.getUserId(Binder.getCallingUid()))) {
4326                        if (libs == null) {
4327                            libs = new ArraySet<>();
4328                        }
4329                        libs.add(libEntry.info.getName());
4330                        break;
4331                    }
4332                }
4333            }
4334
4335            if (libs != null) {
4336                String[] libsArray = new String[libs.size()];
4337                libs.toArray(libsArray);
4338                return libsArray;
4339            }
4340
4341            return null;
4342        }
4343    }
4344
4345    @Override
4346    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4347        synchronized (mPackages) {
4348            return mServicesSystemSharedLibraryPackageName;
4349        }
4350    }
4351
4352    @Override
4353    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4354        synchronized (mPackages) {
4355            return mSharedSystemSharedLibraryPackageName;
4356        }
4357    }
4358
4359    private void updateSequenceNumberLP(String packageName, int[] userList) {
4360        for (int i = userList.length - 1; i >= 0; --i) {
4361            final int userId = userList[i];
4362            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4363            if (changedPackages == null) {
4364                changedPackages = new SparseArray<>();
4365                mChangedPackages.put(userId, changedPackages);
4366            }
4367            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4368            if (sequenceNumbers == null) {
4369                sequenceNumbers = new HashMap<>();
4370                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4371            }
4372            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4373            if (sequenceNumber != null) {
4374                changedPackages.remove(sequenceNumber);
4375            }
4376            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4377            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4378        }
4379        mChangedPackagesSequenceNumber++;
4380    }
4381
4382    @Override
4383    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4384        synchronized (mPackages) {
4385            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4386                return null;
4387            }
4388            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4389            if (changedPackages == null) {
4390                return null;
4391            }
4392            final List<String> packageNames =
4393                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4394            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4395                final String packageName = changedPackages.get(i);
4396                if (packageName != null) {
4397                    packageNames.add(packageName);
4398                }
4399            }
4400            return packageNames.isEmpty()
4401                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4402        }
4403    }
4404
4405    @Override
4406    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4407        ArrayList<FeatureInfo> res;
4408        synchronized (mAvailableFeatures) {
4409            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4410            res.addAll(mAvailableFeatures.values());
4411        }
4412        final FeatureInfo fi = new FeatureInfo();
4413        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4414                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4415        res.add(fi);
4416
4417        return new ParceledListSlice<>(res);
4418    }
4419
4420    @Override
4421    public boolean hasSystemFeature(String name, int version) {
4422        synchronized (mAvailableFeatures) {
4423            final FeatureInfo feat = mAvailableFeatures.get(name);
4424            if (feat == null) {
4425                return false;
4426            } else {
4427                return feat.version >= version;
4428            }
4429        }
4430    }
4431
4432    @Override
4433    public int checkPermission(String permName, String pkgName, int userId) {
4434        if (!sUserManager.exists(userId)) {
4435            return PackageManager.PERMISSION_DENIED;
4436        }
4437
4438        synchronized (mPackages) {
4439            final PackageParser.Package p = mPackages.get(pkgName);
4440            if (p != null && p.mExtras != null) {
4441                final PackageSetting ps = (PackageSetting) p.mExtras;
4442                final PermissionsState permissionsState = ps.getPermissionsState();
4443                if (permissionsState.hasPermission(permName, userId)) {
4444                    return PackageManager.PERMISSION_GRANTED;
4445                }
4446                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4447                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4448                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4449                    return PackageManager.PERMISSION_GRANTED;
4450                }
4451            }
4452        }
4453
4454        return PackageManager.PERMISSION_DENIED;
4455    }
4456
4457    @Override
4458    public int checkUidPermission(String permName, int uid) {
4459        final int userId = UserHandle.getUserId(uid);
4460
4461        if (!sUserManager.exists(userId)) {
4462            return PackageManager.PERMISSION_DENIED;
4463        }
4464
4465        synchronized (mPackages) {
4466            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4467            if (obj != null) {
4468                final SettingBase ps = (SettingBase) obj;
4469                final PermissionsState permissionsState = ps.getPermissionsState();
4470                if (permissionsState.hasPermission(permName, userId)) {
4471                    return PackageManager.PERMISSION_GRANTED;
4472                }
4473                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4474                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4475                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4476                    return PackageManager.PERMISSION_GRANTED;
4477                }
4478            } else {
4479                ArraySet<String> perms = mSystemPermissions.get(uid);
4480                if (perms != null) {
4481                    if (perms.contains(permName)) {
4482                        return PackageManager.PERMISSION_GRANTED;
4483                    }
4484                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4485                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4486                        return PackageManager.PERMISSION_GRANTED;
4487                    }
4488                }
4489            }
4490        }
4491
4492        return PackageManager.PERMISSION_DENIED;
4493    }
4494
4495    @Override
4496    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4497        if (UserHandle.getCallingUserId() != userId) {
4498            mContext.enforceCallingPermission(
4499                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4500                    "isPermissionRevokedByPolicy for user " + userId);
4501        }
4502
4503        if (checkPermission(permission, packageName, userId)
4504                == PackageManager.PERMISSION_GRANTED) {
4505            return false;
4506        }
4507
4508        final long identity = Binder.clearCallingIdentity();
4509        try {
4510            final int flags = getPermissionFlags(permission, packageName, userId);
4511            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4512        } finally {
4513            Binder.restoreCallingIdentity(identity);
4514        }
4515    }
4516
4517    @Override
4518    public String getPermissionControllerPackageName() {
4519        synchronized (mPackages) {
4520            return mRequiredInstallerPackage;
4521        }
4522    }
4523
4524    /**
4525     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4526     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4527     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4528     * @param message the message to log on security exception
4529     */
4530    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4531            boolean checkShell, String message) {
4532        if (userId < 0) {
4533            throw new IllegalArgumentException("Invalid userId " + userId);
4534        }
4535        if (checkShell) {
4536            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4537        }
4538        if (userId == UserHandle.getUserId(callingUid)) return;
4539        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4540            if (requireFullPermission) {
4541                mContext.enforceCallingOrSelfPermission(
4542                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4543            } else {
4544                try {
4545                    mContext.enforceCallingOrSelfPermission(
4546                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4547                } catch (SecurityException se) {
4548                    mContext.enforceCallingOrSelfPermission(
4549                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4550                }
4551            }
4552        }
4553    }
4554
4555    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4556        if (callingUid == Process.SHELL_UID) {
4557            if (userHandle >= 0
4558                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4559                throw new SecurityException("Shell does not have permission to access user "
4560                        + userHandle);
4561            } else if (userHandle < 0) {
4562                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4563                        + Debug.getCallers(3));
4564            }
4565        }
4566    }
4567
4568    private BasePermission findPermissionTreeLP(String permName) {
4569        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4570            if (permName.startsWith(bp.name) &&
4571                    permName.length() > bp.name.length() &&
4572                    permName.charAt(bp.name.length()) == '.') {
4573                return bp;
4574            }
4575        }
4576        return null;
4577    }
4578
4579    private BasePermission checkPermissionTreeLP(String permName) {
4580        if (permName != null) {
4581            BasePermission bp = findPermissionTreeLP(permName);
4582            if (bp != null) {
4583                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4584                    return bp;
4585                }
4586                throw new SecurityException("Calling uid "
4587                        + Binder.getCallingUid()
4588                        + " is not allowed to add to permission tree "
4589                        + bp.name + " owned by uid " + bp.uid);
4590            }
4591        }
4592        throw new SecurityException("No permission tree found for " + permName);
4593    }
4594
4595    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4596        if (s1 == null) {
4597            return s2 == null;
4598        }
4599        if (s2 == null) {
4600            return false;
4601        }
4602        if (s1.getClass() != s2.getClass()) {
4603            return false;
4604        }
4605        return s1.equals(s2);
4606    }
4607
4608    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4609        if (pi1.icon != pi2.icon) return false;
4610        if (pi1.logo != pi2.logo) return false;
4611        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4612        if (!compareStrings(pi1.name, pi2.name)) return false;
4613        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4614        // We'll take care of setting this one.
4615        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4616        // These are not currently stored in settings.
4617        //if (!compareStrings(pi1.group, pi2.group)) return false;
4618        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4619        //if (pi1.labelRes != pi2.labelRes) return false;
4620        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4621        return true;
4622    }
4623
4624    int permissionInfoFootprint(PermissionInfo info) {
4625        int size = info.name.length();
4626        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4627        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4628        return size;
4629    }
4630
4631    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4632        int size = 0;
4633        for (BasePermission perm : mSettings.mPermissions.values()) {
4634            if (perm.uid == tree.uid) {
4635                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4636            }
4637        }
4638        return size;
4639    }
4640
4641    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4642        // We calculate the max size of permissions defined by this uid and throw
4643        // if that plus the size of 'info' would exceed our stated maximum.
4644        if (tree.uid != Process.SYSTEM_UID) {
4645            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4646            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4647                throw new SecurityException("Permission tree size cap exceeded");
4648            }
4649        }
4650    }
4651
4652    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4653        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4654            throw new SecurityException("Label must be specified in permission");
4655        }
4656        BasePermission tree = checkPermissionTreeLP(info.name);
4657        BasePermission bp = mSettings.mPermissions.get(info.name);
4658        boolean added = bp == null;
4659        boolean changed = true;
4660        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4661        if (added) {
4662            enforcePermissionCapLocked(info, tree);
4663            bp = new BasePermission(info.name, tree.sourcePackage,
4664                    BasePermission.TYPE_DYNAMIC);
4665        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4666            throw new SecurityException(
4667                    "Not allowed to modify non-dynamic permission "
4668                    + info.name);
4669        } else {
4670            if (bp.protectionLevel == fixedLevel
4671                    && bp.perm.owner.equals(tree.perm.owner)
4672                    && bp.uid == tree.uid
4673                    && comparePermissionInfos(bp.perm.info, info)) {
4674                changed = false;
4675            }
4676        }
4677        bp.protectionLevel = fixedLevel;
4678        info = new PermissionInfo(info);
4679        info.protectionLevel = fixedLevel;
4680        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4681        bp.perm.info.packageName = tree.perm.info.packageName;
4682        bp.uid = tree.uid;
4683        if (added) {
4684            mSettings.mPermissions.put(info.name, bp);
4685        }
4686        if (changed) {
4687            if (!async) {
4688                mSettings.writeLPr();
4689            } else {
4690                scheduleWriteSettingsLocked();
4691            }
4692        }
4693        return added;
4694    }
4695
4696    @Override
4697    public boolean addPermission(PermissionInfo info) {
4698        synchronized (mPackages) {
4699            return addPermissionLocked(info, false);
4700        }
4701    }
4702
4703    @Override
4704    public boolean addPermissionAsync(PermissionInfo info) {
4705        synchronized (mPackages) {
4706            return addPermissionLocked(info, true);
4707        }
4708    }
4709
4710    @Override
4711    public void removePermission(String name) {
4712        synchronized (mPackages) {
4713            checkPermissionTreeLP(name);
4714            BasePermission bp = mSettings.mPermissions.get(name);
4715            if (bp != null) {
4716                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4717                    throw new SecurityException(
4718                            "Not allowed to modify non-dynamic permission "
4719                            + name);
4720                }
4721                mSettings.mPermissions.remove(name);
4722                mSettings.writeLPr();
4723            }
4724        }
4725    }
4726
4727    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4728            BasePermission bp) {
4729        int index = pkg.requestedPermissions.indexOf(bp.name);
4730        if (index == -1) {
4731            throw new SecurityException("Package " + pkg.packageName
4732                    + " has not requested permission " + bp.name);
4733        }
4734        if (!bp.isRuntime() && !bp.isDevelopment()) {
4735            throw new SecurityException("Permission " + bp.name
4736                    + " is not a changeable permission type");
4737        }
4738    }
4739
4740    @Override
4741    public void grantRuntimePermission(String packageName, String name, final int userId) {
4742        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4743    }
4744
4745    private void grantRuntimePermission(String packageName, String name, final int userId,
4746            boolean overridePolicy) {
4747        if (!sUserManager.exists(userId)) {
4748            Log.e(TAG, "No such user:" + userId);
4749            return;
4750        }
4751
4752        mContext.enforceCallingOrSelfPermission(
4753                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4754                "grantRuntimePermission");
4755
4756        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4757                true /* requireFullPermission */, true /* checkShell */,
4758                "grantRuntimePermission");
4759
4760        final int uid;
4761        final SettingBase sb;
4762
4763        synchronized (mPackages) {
4764            final PackageParser.Package pkg = mPackages.get(packageName);
4765            if (pkg == null) {
4766                throw new IllegalArgumentException("Unknown package: " + packageName);
4767            }
4768
4769            final BasePermission bp = mSettings.mPermissions.get(name);
4770            if (bp == null) {
4771                throw new IllegalArgumentException("Unknown permission: " + name);
4772            }
4773
4774            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4775
4776            // If a permission review is required for legacy apps we represent
4777            // their permissions as always granted runtime ones since we need
4778            // to keep the review required permission flag per user while an
4779            // install permission's state is shared across all users.
4780            if (mPermissionReviewRequired
4781                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4782                    && bp.isRuntime()) {
4783                return;
4784            }
4785
4786            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4787            sb = (SettingBase) pkg.mExtras;
4788            if (sb == null) {
4789                throw new IllegalArgumentException("Unknown package: " + packageName);
4790            }
4791
4792            final PermissionsState permissionsState = sb.getPermissionsState();
4793
4794            final int flags = permissionsState.getPermissionFlags(name, userId);
4795            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4796                throw new SecurityException("Cannot grant system fixed permission "
4797                        + name + " for package " + packageName);
4798            }
4799            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4800                throw new SecurityException("Cannot grant policy fixed permission "
4801                        + name + " for package " + packageName);
4802            }
4803
4804            if (bp.isDevelopment()) {
4805                // Development permissions must be handled specially, since they are not
4806                // normal runtime permissions.  For now they apply to all users.
4807                if (permissionsState.grantInstallPermission(bp) !=
4808                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4809                    scheduleWriteSettingsLocked();
4810                }
4811                return;
4812            }
4813
4814            final PackageSetting ps = mSettings.mPackages.get(packageName);
4815            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4816                throw new SecurityException("Cannot grant non-ephemeral permission"
4817                        + name + " for package " + packageName);
4818            }
4819
4820            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4821                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4822                return;
4823            }
4824
4825            final int result = permissionsState.grantRuntimePermission(bp, userId);
4826            switch (result) {
4827                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4828                    return;
4829                }
4830
4831                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4832                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4833                    mHandler.post(new Runnable() {
4834                        @Override
4835                        public void run() {
4836                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4837                        }
4838                    });
4839                }
4840                break;
4841            }
4842
4843            if (bp.isRuntime()) {
4844                logPermissionGranted(mContext, name, packageName);
4845            }
4846
4847            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4848
4849            // Not critical if that is lost - app has to request again.
4850            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4851        }
4852
4853        // Only need to do this if user is initialized. Otherwise it's a new user
4854        // and there are no processes running as the user yet and there's no need
4855        // to make an expensive call to remount processes for the changed permissions.
4856        if (READ_EXTERNAL_STORAGE.equals(name)
4857                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4858            final long token = Binder.clearCallingIdentity();
4859            try {
4860                if (sUserManager.isInitialized(userId)) {
4861                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4862                            StorageManagerInternal.class);
4863                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4864                }
4865            } finally {
4866                Binder.restoreCallingIdentity(token);
4867            }
4868        }
4869    }
4870
4871    @Override
4872    public void revokeRuntimePermission(String packageName, String name, int userId) {
4873        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4874    }
4875
4876    private void revokeRuntimePermission(String packageName, String name, int userId,
4877            boolean overridePolicy) {
4878        if (!sUserManager.exists(userId)) {
4879            Log.e(TAG, "No such user:" + userId);
4880            return;
4881        }
4882
4883        mContext.enforceCallingOrSelfPermission(
4884                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4885                "revokeRuntimePermission");
4886
4887        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4888                true /* requireFullPermission */, true /* checkShell */,
4889                "revokeRuntimePermission");
4890
4891        final int appId;
4892
4893        synchronized (mPackages) {
4894            final PackageParser.Package pkg = mPackages.get(packageName);
4895            if (pkg == null) {
4896                throw new IllegalArgumentException("Unknown package: " + packageName);
4897            }
4898
4899            final BasePermission bp = mSettings.mPermissions.get(name);
4900            if (bp == null) {
4901                throw new IllegalArgumentException("Unknown permission: " + name);
4902            }
4903
4904            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4905
4906            // If a permission review is required for legacy apps we represent
4907            // their permissions as always granted runtime ones since we need
4908            // to keep the review required permission flag per user while an
4909            // install permission's state is shared across all users.
4910            if (mPermissionReviewRequired
4911                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4912                    && bp.isRuntime()) {
4913                return;
4914            }
4915
4916            SettingBase sb = (SettingBase) pkg.mExtras;
4917            if (sb == null) {
4918                throw new IllegalArgumentException("Unknown package: " + packageName);
4919            }
4920
4921            final PermissionsState permissionsState = sb.getPermissionsState();
4922
4923            final int flags = permissionsState.getPermissionFlags(name, userId);
4924            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4925                throw new SecurityException("Cannot revoke system fixed permission "
4926                        + name + " for package " + packageName);
4927            }
4928            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4929                throw new SecurityException("Cannot revoke policy fixed permission "
4930                        + name + " for package " + packageName);
4931            }
4932
4933            if (bp.isDevelopment()) {
4934                // Development permissions must be handled specially, since they are not
4935                // normal runtime permissions.  For now they apply to all users.
4936                if (permissionsState.revokeInstallPermission(bp) !=
4937                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4938                    scheduleWriteSettingsLocked();
4939                }
4940                return;
4941            }
4942
4943            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4944                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4945                return;
4946            }
4947
4948            if (bp.isRuntime()) {
4949                logPermissionRevoked(mContext, name, packageName);
4950            }
4951
4952            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4953
4954            // Critical, after this call app should never have the permission.
4955            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4956
4957            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4958        }
4959
4960        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4961    }
4962
4963    /**
4964     * Get the first event id for the permission.
4965     *
4966     * <p>There are four events for each permission: <ul>
4967     *     <li>Request permission: first id + 0</li>
4968     *     <li>Grant permission: first id + 1</li>
4969     *     <li>Request for permission denied: first id + 2</li>
4970     *     <li>Revoke permission: first id + 3</li>
4971     * </ul></p>
4972     *
4973     * @param name name of the permission
4974     *
4975     * @return The first event id for the permission
4976     */
4977    private static int getBaseEventId(@NonNull String name) {
4978        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4979
4980        if (eventIdIndex == -1) {
4981            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4982                    || "user".equals(Build.TYPE)) {
4983                Log.i(TAG, "Unknown permission " + name);
4984
4985                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4986            } else {
4987                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4988                //
4989                // Also update
4990                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4991                // - metrics_constants.proto
4992                throw new IllegalStateException("Unknown permission " + name);
4993            }
4994        }
4995
4996        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4997    }
4998
4999    /**
5000     * Log that a permission was revoked.
5001     *
5002     * @param context Context of the caller
5003     * @param name name of the permission
5004     * @param packageName package permission if for
5005     */
5006    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5007            @NonNull String packageName) {
5008        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5009    }
5010
5011    /**
5012     * Log that a permission request was granted.
5013     *
5014     * @param context Context of the caller
5015     * @param name name of the permission
5016     * @param packageName package permission if for
5017     */
5018    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5019            @NonNull String packageName) {
5020        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5021    }
5022
5023    @Override
5024    public void resetRuntimePermissions() {
5025        mContext.enforceCallingOrSelfPermission(
5026                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5027                "revokeRuntimePermission");
5028
5029        int callingUid = Binder.getCallingUid();
5030        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5031            mContext.enforceCallingOrSelfPermission(
5032                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5033                    "resetRuntimePermissions");
5034        }
5035
5036        synchronized (mPackages) {
5037            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5038            for (int userId : UserManagerService.getInstance().getUserIds()) {
5039                final int packageCount = mPackages.size();
5040                for (int i = 0; i < packageCount; i++) {
5041                    PackageParser.Package pkg = mPackages.valueAt(i);
5042                    if (!(pkg.mExtras instanceof PackageSetting)) {
5043                        continue;
5044                    }
5045                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5046                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5047                }
5048            }
5049        }
5050    }
5051
5052    @Override
5053    public int getPermissionFlags(String name, String packageName, int userId) {
5054        if (!sUserManager.exists(userId)) {
5055            return 0;
5056        }
5057
5058        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5059
5060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5061                true /* requireFullPermission */, false /* checkShell */,
5062                "getPermissionFlags");
5063
5064        synchronized (mPackages) {
5065            final PackageParser.Package pkg = mPackages.get(packageName);
5066            if (pkg == null) {
5067                return 0;
5068            }
5069
5070            final BasePermission bp = mSettings.mPermissions.get(name);
5071            if (bp == null) {
5072                return 0;
5073            }
5074
5075            SettingBase sb = (SettingBase) pkg.mExtras;
5076            if (sb == null) {
5077                return 0;
5078            }
5079
5080            PermissionsState permissionsState = sb.getPermissionsState();
5081            return permissionsState.getPermissionFlags(name, userId);
5082        }
5083    }
5084
5085    @Override
5086    public void updatePermissionFlags(String name, String packageName, int flagMask,
5087            int flagValues, int userId) {
5088        if (!sUserManager.exists(userId)) {
5089            return;
5090        }
5091
5092        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5093
5094        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5095                true /* requireFullPermission */, true /* checkShell */,
5096                "updatePermissionFlags");
5097
5098        // Only the system can change these flags and nothing else.
5099        if (getCallingUid() != Process.SYSTEM_UID) {
5100            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5101            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5102            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5103            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5104            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5105        }
5106
5107        synchronized (mPackages) {
5108            final PackageParser.Package pkg = mPackages.get(packageName);
5109            if (pkg == null) {
5110                throw new IllegalArgumentException("Unknown package: " + packageName);
5111            }
5112
5113            final BasePermission bp = mSettings.mPermissions.get(name);
5114            if (bp == null) {
5115                throw new IllegalArgumentException("Unknown permission: " + name);
5116            }
5117
5118            SettingBase sb = (SettingBase) pkg.mExtras;
5119            if (sb == null) {
5120                throw new IllegalArgumentException("Unknown package: " + packageName);
5121            }
5122
5123            PermissionsState permissionsState = sb.getPermissionsState();
5124
5125            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5126
5127            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5128                // Install and runtime permissions are stored in different places,
5129                // so figure out what permission changed and persist the change.
5130                if (permissionsState.getInstallPermissionState(name) != null) {
5131                    scheduleWriteSettingsLocked();
5132                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5133                        || hadState) {
5134                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5135                }
5136            }
5137        }
5138    }
5139
5140    /**
5141     * Update the permission flags for all packages and runtime permissions of a user in order
5142     * to allow device or profile owner to remove POLICY_FIXED.
5143     */
5144    @Override
5145    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5146        if (!sUserManager.exists(userId)) {
5147            return;
5148        }
5149
5150        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5151
5152        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5153                true /* requireFullPermission */, true /* checkShell */,
5154                "updatePermissionFlagsForAllApps");
5155
5156        // Only the system can change system fixed flags.
5157        if (getCallingUid() != Process.SYSTEM_UID) {
5158            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5159            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5160        }
5161
5162        synchronized (mPackages) {
5163            boolean changed = false;
5164            final int packageCount = mPackages.size();
5165            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5166                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5167                SettingBase sb = (SettingBase) pkg.mExtras;
5168                if (sb == null) {
5169                    continue;
5170                }
5171                PermissionsState permissionsState = sb.getPermissionsState();
5172                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5173                        userId, flagMask, flagValues);
5174            }
5175            if (changed) {
5176                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5177            }
5178        }
5179    }
5180
5181    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5182        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5183                != PackageManager.PERMISSION_GRANTED
5184            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5185                != PackageManager.PERMISSION_GRANTED) {
5186            throw new SecurityException(message + " requires "
5187                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5188                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5189        }
5190    }
5191
5192    @Override
5193    public boolean shouldShowRequestPermissionRationale(String permissionName,
5194            String packageName, int userId) {
5195        if (UserHandle.getCallingUserId() != userId) {
5196            mContext.enforceCallingPermission(
5197                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5198                    "canShowRequestPermissionRationale for user " + userId);
5199        }
5200
5201        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5202        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5203            return false;
5204        }
5205
5206        if (checkPermission(permissionName, packageName, userId)
5207                == PackageManager.PERMISSION_GRANTED) {
5208            return false;
5209        }
5210
5211        final int flags;
5212
5213        final long identity = Binder.clearCallingIdentity();
5214        try {
5215            flags = getPermissionFlags(permissionName,
5216                    packageName, userId);
5217        } finally {
5218            Binder.restoreCallingIdentity(identity);
5219        }
5220
5221        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5222                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5223                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5224
5225        if ((flags & fixedFlags) != 0) {
5226            return false;
5227        }
5228
5229        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5230    }
5231
5232    @Override
5233    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5234        mContext.enforceCallingOrSelfPermission(
5235                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5236                "addOnPermissionsChangeListener");
5237
5238        synchronized (mPackages) {
5239            mOnPermissionChangeListeners.addListenerLocked(listener);
5240        }
5241    }
5242
5243    @Override
5244    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5245        synchronized (mPackages) {
5246            mOnPermissionChangeListeners.removeListenerLocked(listener);
5247        }
5248    }
5249
5250    @Override
5251    public boolean isProtectedBroadcast(String actionName) {
5252        synchronized (mPackages) {
5253            if (mProtectedBroadcasts.contains(actionName)) {
5254                return true;
5255            } else if (actionName != null) {
5256                // TODO: remove these terrible hacks
5257                if (actionName.startsWith("android.net.netmon.lingerExpired")
5258                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5259                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5260                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5261                    return true;
5262                }
5263            }
5264        }
5265        return false;
5266    }
5267
5268    @Override
5269    public int checkSignatures(String pkg1, String pkg2) {
5270        synchronized (mPackages) {
5271            final PackageParser.Package p1 = mPackages.get(pkg1);
5272            final PackageParser.Package p2 = mPackages.get(pkg2);
5273            if (p1 == null || p1.mExtras == null
5274                    || p2 == null || p2.mExtras == null) {
5275                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5276            }
5277            return compareSignatures(p1.mSignatures, p2.mSignatures);
5278        }
5279    }
5280
5281    @Override
5282    public int checkUidSignatures(int uid1, int uid2) {
5283        // Map to base uids.
5284        uid1 = UserHandle.getAppId(uid1);
5285        uid2 = UserHandle.getAppId(uid2);
5286        // reader
5287        synchronized (mPackages) {
5288            Signature[] s1;
5289            Signature[] s2;
5290            Object obj = mSettings.getUserIdLPr(uid1);
5291            if (obj != null) {
5292                if (obj instanceof SharedUserSetting) {
5293                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5294                } else if (obj instanceof PackageSetting) {
5295                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5296                } else {
5297                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5298                }
5299            } else {
5300                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5301            }
5302            obj = mSettings.getUserIdLPr(uid2);
5303            if (obj != null) {
5304                if (obj instanceof SharedUserSetting) {
5305                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5306                } else if (obj instanceof PackageSetting) {
5307                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5308                } else {
5309                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5310                }
5311            } else {
5312                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5313            }
5314            return compareSignatures(s1, s2);
5315        }
5316    }
5317
5318    /**
5319     * This method should typically only be used when granting or revoking
5320     * permissions, since the app may immediately restart after this call.
5321     * <p>
5322     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5323     * guard your work against the app being relaunched.
5324     */
5325    private void killUid(int appId, int userId, String reason) {
5326        final long identity = Binder.clearCallingIdentity();
5327        try {
5328            IActivityManager am = ActivityManager.getService();
5329            if (am != null) {
5330                try {
5331                    am.killUid(appId, userId, reason);
5332                } catch (RemoteException e) {
5333                    /* ignore - same process */
5334                }
5335            }
5336        } finally {
5337            Binder.restoreCallingIdentity(identity);
5338        }
5339    }
5340
5341    /**
5342     * Compares two sets of signatures. Returns:
5343     * <br />
5344     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5345     * <br />
5346     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5347     * <br />
5348     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5349     * <br />
5350     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5351     * <br />
5352     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5353     */
5354    static int compareSignatures(Signature[] s1, Signature[] s2) {
5355        if (s1 == null) {
5356            return s2 == null
5357                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5358                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5359        }
5360
5361        if (s2 == null) {
5362            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5363        }
5364
5365        if (s1.length != s2.length) {
5366            return PackageManager.SIGNATURE_NO_MATCH;
5367        }
5368
5369        // Since both signature sets are of size 1, we can compare without HashSets.
5370        if (s1.length == 1) {
5371            return s1[0].equals(s2[0]) ?
5372                    PackageManager.SIGNATURE_MATCH :
5373                    PackageManager.SIGNATURE_NO_MATCH;
5374        }
5375
5376        ArraySet<Signature> set1 = new ArraySet<Signature>();
5377        for (Signature sig : s1) {
5378            set1.add(sig);
5379        }
5380        ArraySet<Signature> set2 = new ArraySet<Signature>();
5381        for (Signature sig : s2) {
5382            set2.add(sig);
5383        }
5384        // Make sure s2 contains all signatures in s1.
5385        if (set1.equals(set2)) {
5386            return PackageManager.SIGNATURE_MATCH;
5387        }
5388        return PackageManager.SIGNATURE_NO_MATCH;
5389    }
5390
5391    /**
5392     * If the database version for this type of package (internal storage or
5393     * external storage) is less than the version where package signatures
5394     * were updated, return true.
5395     */
5396    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5397        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5398        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5399    }
5400
5401    /**
5402     * Used for backward compatibility to make sure any packages with
5403     * certificate chains get upgraded to the new style. {@code existingSigs}
5404     * will be in the old format (since they were stored on disk from before the
5405     * system upgrade) and {@code scannedSigs} will be in the newer format.
5406     */
5407    private int compareSignaturesCompat(PackageSignatures existingSigs,
5408            PackageParser.Package scannedPkg) {
5409        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5410            return PackageManager.SIGNATURE_NO_MATCH;
5411        }
5412
5413        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5414        for (Signature sig : existingSigs.mSignatures) {
5415            existingSet.add(sig);
5416        }
5417        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5418        for (Signature sig : scannedPkg.mSignatures) {
5419            try {
5420                Signature[] chainSignatures = sig.getChainSignatures();
5421                for (Signature chainSig : chainSignatures) {
5422                    scannedCompatSet.add(chainSig);
5423                }
5424            } catch (CertificateEncodingException e) {
5425                scannedCompatSet.add(sig);
5426            }
5427        }
5428        /*
5429         * Make sure the expanded scanned set contains all signatures in the
5430         * existing one.
5431         */
5432        if (scannedCompatSet.equals(existingSet)) {
5433            // Migrate the old signatures to the new scheme.
5434            existingSigs.assignSignatures(scannedPkg.mSignatures);
5435            // The new KeySets will be re-added later in the scanning process.
5436            synchronized (mPackages) {
5437                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5438            }
5439            return PackageManager.SIGNATURE_MATCH;
5440        }
5441        return PackageManager.SIGNATURE_NO_MATCH;
5442    }
5443
5444    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5445        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5446        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5447    }
5448
5449    private int compareSignaturesRecover(PackageSignatures existingSigs,
5450            PackageParser.Package scannedPkg) {
5451        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5452            return PackageManager.SIGNATURE_NO_MATCH;
5453        }
5454
5455        String msg = null;
5456        try {
5457            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5458                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5459                        + scannedPkg.packageName);
5460                return PackageManager.SIGNATURE_MATCH;
5461            }
5462        } catch (CertificateException e) {
5463            msg = e.getMessage();
5464        }
5465
5466        logCriticalInfo(Log.INFO,
5467                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5468        return PackageManager.SIGNATURE_NO_MATCH;
5469    }
5470
5471    @Override
5472    public List<String> getAllPackages() {
5473        synchronized (mPackages) {
5474            return new ArrayList<String>(mPackages.keySet());
5475        }
5476    }
5477
5478    @Override
5479    public String[] getPackagesForUid(int uid) {
5480        final int userId = UserHandle.getUserId(uid);
5481        uid = UserHandle.getAppId(uid);
5482        // reader
5483        synchronized (mPackages) {
5484            Object obj = mSettings.getUserIdLPr(uid);
5485            if (obj instanceof SharedUserSetting) {
5486                final SharedUserSetting sus = (SharedUserSetting) obj;
5487                final int N = sus.packages.size();
5488                String[] res = new String[N];
5489                final Iterator<PackageSetting> it = sus.packages.iterator();
5490                int i = 0;
5491                while (it.hasNext()) {
5492                    PackageSetting ps = it.next();
5493                    if (ps.getInstalled(userId)) {
5494                        res[i++] = ps.name;
5495                    } else {
5496                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5497                    }
5498                }
5499                return res;
5500            } else if (obj instanceof PackageSetting) {
5501                final PackageSetting ps = (PackageSetting) obj;
5502                if (ps.getInstalled(userId)) {
5503                    return new String[]{ps.name};
5504                }
5505            }
5506        }
5507        return null;
5508    }
5509
5510    @Override
5511    public String getNameForUid(int uid) {
5512        // reader
5513        synchronized (mPackages) {
5514            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5515            if (obj instanceof SharedUserSetting) {
5516                final SharedUserSetting sus = (SharedUserSetting) obj;
5517                return sus.name + ":" + sus.userId;
5518            } else if (obj instanceof PackageSetting) {
5519                final PackageSetting ps = (PackageSetting) obj;
5520                return ps.name;
5521            }
5522        }
5523        return null;
5524    }
5525
5526    @Override
5527    public int getUidForSharedUser(String sharedUserName) {
5528        if(sharedUserName == null) {
5529            return -1;
5530        }
5531        // reader
5532        synchronized (mPackages) {
5533            SharedUserSetting suid;
5534            try {
5535                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5536                if (suid != null) {
5537                    return suid.userId;
5538                }
5539            } catch (PackageManagerException ignore) {
5540                // can't happen, but, still need to catch it
5541            }
5542            return -1;
5543        }
5544    }
5545
5546    @Override
5547    public int getFlagsForUid(int uid) {
5548        synchronized (mPackages) {
5549            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5550            if (obj instanceof SharedUserSetting) {
5551                final SharedUserSetting sus = (SharedUserSetting) obj;
5552                return sus.pkgFlags;
5553            } else if (obj instanceof PackageSetting) {
5554                final PackageSetting ps = (PackageSetting) obj;
5555                return ps.pkgFlags;
5556            }
5557        }
5558        return 0;
5559    }
5560
5561    @Override
5562    public int getPrivateFlagsForUid(int uid) {
5563        synchronized (mPackages) {
5564            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5565            if (obj instanceof SharedUserSetting) {
5566                final SharedUserSetting sus = (SharedUserSetting) obj;
5567                return sus.pkgPrivateFlags;
5568            } else if (obj instanceof PackageSetting) {
5569                final PackageSetting ps = (PackageSetting) obj;
5570                return ps.pkgPrivateFlags;
5571            }
5572        }
5573        return 0;
5574    }
5575
5576    @Override
5577    public boolean isUidPrivileged(int uid) {
5578        uid = UserHandle.getAppId(uid);
5579        // reader
5580        synchronized (mPackages) {
5581            Object obj = mSettings.getUserIdLPr(uid);
5582            if (obj instanceof SharedUserSetting) {
5583                final SharedUserSetting sus = (SharedUserSetting) obj;
5584                final Iterator<PackageSetting> it = sus.packages.iterator();
5585                while (it.hasNext()) {
5586                    if (it.next().isPrivileged()) {
5587                        return true;
5588                    }
5589                }
5590            } else if (obj instanceof PackageSetting) {
5591                final PackageSetting ps = (PackageSetting) obj;
5592                return ps.isPrivileged();
5593            }
5594        }
5595        return false;
5596    }
5597
5598    @Override
5599    public String[] getAppOpPermissionPackages(String permissionName) {
5600        synchronized (mPackages) {
5601            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5602            if (pkgs == null) {
5603                return null;
5604            }
5605            return pkgs.toArray(new String[pkgs.size()]);
5606        }
5607    }
5608
5609    @Override
5610    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5611            int flags, int userId) {
5612        return resolveIntentInternal(
5613                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5614    }
5615
5616    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5617            int flags, int userId, boolean includeInstantApp) {
5618        try {
5619            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5620
5621            if (!sUserManager.exists(userId)) return null;
5622            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5623            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5624                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5625
5626            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5627            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5628                    flags, userId, includeInstantApp);
5629            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5630
5631            final ResolveInfo bestChoice =
5632                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5633            return bestChoice;
5634        } finally {
5635            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5636        }
5637    }
5638
5639    @Override
5640    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5641        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5642            throw new SecurityException(
5643                    "findPersistentPreferredActivity can only be run by the system");
5644        }
5645        if (!sUserManager.exists(userId)) {
5646            return null;
5647        }
5648        intent = updateIntentForResolve(intent);
5649        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5650        final int flags = updateFlagsForResolve(0, userId, intent, false);
5651        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5652                userId);
5653        synchronized (mPackages) {
5654            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5655                    userId);
5656        }
5657    }
5658
5659    @Override
5660    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5661            IntentFilter filter, int match, ComponentName activity) {
5662        final int userId = UserHandle.getCallingUserId();
5663        if (DEBUG_PREFERRED) {
5664            Log.v(TAG, "setLastChosenActivity intent=" + intent
5665                + " resolvedType=" + resolvedType
5666                + " flags=" + flags
5667                + " filter=" + filter
5668                + " match=" + match
5669                + " activity=" + activity);
5670            filter.dump(new PrintStreamPrinter(System.out), "    ");
5671        }
5672        intent.setComponent(null);
5673        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5674                userId);
5675        // Find any earlier preferred or last chosen entries and nuke them
5676        findPreferredActivity(intent, resolvedType,
5677                flags, query, 0, false, true, false, userId);
5678        // Add the new activity as the last chosen for this filter
5679        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5680                "Setting last chosen");
5681    }
5682
5683    @Override
5684    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5685        final int userId = UserHandle.getCallingUserId();
5686        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5687        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5688                userId);
5689        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5690                false, false, false, userId);
5691    }
5692
5693    /**
5694     * Returns whether or not instant apps have been disabled remotely.
5695     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5696     * held. Otherwise we run the risk of deadlock.
5697     */
5698    private boolean isEphemeralDisabled() {
5699        // ephemeral apps have been disabled across the board
5700        if (DISABLE_EPHEMERAL_APPS) {
5701            return true;
5702        }
5703        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5704        if (!mSystemReady) {
5705            return true;
5706        }
5707        // we can't get a content resolver until the system is ready; these checks must happen last
5708        final ContentResolver resolver = mContext.getContentResolver();
5709        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5710            return true;
5711        }
5712        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5713    }
5714
5715    private boolean isEphemeralAllowed(
5716            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5717            boolean skipPackageCheck) {
5718        final int callingUser = UserHandle.getCallingUserId();
5719        if (callingUser != UserHandle.USER_SYSTEM) {
5720            return false;
5721        }
5722        if (mInstantAppResolverConnection == null) {
5723            return false;
5724        }
5725        if (mInstantAppInstallerComponent == null) {
5726            return false;
5727        }
5728        if (intent.getComponent() != null) {
5729            return false;
5730        }
5731        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5732            return false;
5733        }
5734        if (!skipPackageCheck && intent.getPackage() != null) {
5735            return false;
5736        }
5737        final boolean isWebUri = hasWebURI(intent);
5738        if (!isWebUri || intent.getData().getHost() == null) {
5739            return false;
5740        }
5741        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5742        // Or if there's already an ephemeral app installed that handles the action
5743        synchronized (mPackages) {
5744            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5745            for (int n = 0; n < count; n++) {
5746                ResolveInfo info = resolvedActivities.get(n);
5747                String packageName = info.activityInfo.packageName;
5748                PackageSetting ps = mSettings.mPackages.get(packageName);
5749                if (ps != null) {
5750                    // Try to get the status from User settings first
5751                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5752                    int status = (int) (packedStatus >> 32);
5753                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5754                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5755                        if (DEBUG_EPHEMERAL) {
5756                            Slog.v(TAG, "DENY ephemeral apps;"
5757                                + " pkg: " + packageName + ", status: " + status);
5758                        }
5759                        return false;
5760                    }
5761                    if (ps.getInstantApp(userId)) {
5762                        return false;
5763                    }
5764                }
5765            }
5766        }
5767        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5768        return true;
5769    }
5770
5771    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5772            Intent origIntent, String resolvedType, String callingPackage,
5773            int userId) {
5774        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5775                new InstantAppRequest(responseObj, origIntent, resolvedType,
5776                        callingPackage, userId));
5777        mHandler.sendMessage(msg);
5778    }
5779
5780    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5781            int flags, List<ResolveInfo> query, int userId) {
5782        if (query != null) {
5783            final int N = query.size();
5784            if (N == 1) {
5785                return query.get(0);
5786            } else if (N > 1) {
5787                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5788                // If there is more than one activity with the same priority,
5789                // then let the user decide between them.
5790                ResolveInfo r0 = query.get(0);
5791                ResolveInfo r1 = query.get(1);
5792                if (DEBUG_INTENT_MATCHING || debug) {
5793                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5794                            + r1.activityInfo.name + "=" + r1.priority);
5795                }
5796                // If the first activity has a higher priority, or a different
5797                // default, then it is always desirable to pick it.
5798                if (r0.priority != r1.priority
5799                        || r0.preferredOrder != r1.preferredOrder
5800                        || r0.isDefault != r1.isDefault) {
5801                    return query.get(0);
5802                }
5803                // If we have saved a preference for a preferred activity for
5804                // this Intent, use that.
5805                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5806                        flags, query, r0.priority, true, false, debug, userId);
5807                if (ri != null) {
5808                    return ri;
5809                }
5810                // If we have an ephemeral app, use it
5811                for (int i = 0; i < N; i++) {
5812                    ri = query.get(i);
5813                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5814                        return ri;
5815                    }
5816                }
5817                ri = new ResolveInfo(mResolveInfo);
5818                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5819                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5820                // If all of the options come from the same package, show the application's
5821                // label and icon instead of the generic resolver's.
5822                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5823                // and then throw away the ResolveInfo itself, meaning that the caller loses
5824                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5825                // a fallback for this case; we only set the target package's resources on
5826                // the ResolveInfo, not the ActivityInfo.
5827                final String intentPackage = intent.getPackage();
5828                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5829                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5830                    ri.resolvePackageName = intentPackage;
5831                    if (userNeedsBadging(userId)) {
5832                        ri.noResourceId = true;
5833                    } else {
5834                        ri.icon = appi.icon;
5835                    }
5836                    ri.iconResourceId = appi.icon;
5837                    ri.labelRes = appi.labelRes;
5838                }
5839                ri.activityInfo.applicationInfo = new ApplicationInfo(
5840                        ri.activityInfo.applicationInfo);
5841                if (userId != 0) {
5842                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5843                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5844                }
5845                // Make sure that the resolver is displayable in car mode
5846                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5847                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5848                return ri;
5849            }
5850        }
5851        return null;
5852    }
5853
5854    /**
5855     * Return true if the given list is not empty and all of its contents have
5856     * an activityInfo with the given package name.
5857     */
5858    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5859        if (ArrayUtils.isEmpty(list)) {
5860            return false;
5861        }
5862        for (int i = 0, N = list.size(); i < N; i++) {
5863            final ResolveInfo ri = list.get(i);
5864            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5865            if (ai == null || !packageName.equals(ai.packageName)) {
5866                return false;
5867            }
5868        }
5869        return true;
5870    }
5871
5872    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5873            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5874        final int N = query.size();
5875        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5876                .get(userId);
5877        // Get the list of persistent preferred activities that handle the intent
5878        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5879        List<PersistentPreferredActivity> pprefs = ppir != null
5880                ? ppir.queryIntent(intent, resolvedType,
5881                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5882                        userId)
5883                : null;
5884        if (pprefs != null && pprefs.size() > 0) {
5885            final int M = pprefs.size();
5886            for (int i=0; i<M; i++) {
5887                final PersistentPreferredActivity ppa = pprefs.get(i);
5888                if (DEBUG_PREFERRED || debug) {
5889                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5890                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5891                            + "\n  component=" + ppa.mComponent);
5892                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5893                }
5894                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5895                        flags | MATCH_DISABLED_COMPONENTS, userId);
5896                if (DEBUG_PREFERRED || debug) {
5897                    Slog.v(TAG, "Found persistent preferred activity:");
5898                    if (ai != null) {
5899                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5900                    } else {
5901                        Slog.v(TAG, "  null");
5902                    }
5903                }
5904                if (ai == null) {
5905                    // This previously registered persistent preferred activity
5906                    // component is no longer known. Ignore it and do NOT remove it.
5907                    continue;
5908                }
5909                for (int j=0; j<N; j++) {
5910                    final ResolveInfo ri = query.get(j);
5911                    if (!ri.activityInfo.applicationInfo.packageName
5912                            .equals(ai.applicationInfo.packageName)) {
5913                        continue;
5914                    }
5915                    if (!ri.activityInfo.name.equals(ai.name)) {
5916                        continue;
5917                    }
5918                    //  Found a persistent preference that can handle the intent.
5919                    if (DEBUG_PREFERRED || debug) {
5920                        Slog.v(TAG, "Returning persistent preferred activity: " +
5921                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5922                    }
5923                    return ri;
5924                }
5925            }
5926        }
5927        return null;
5928    }
5929
5930    // TODO: handle preferred activities missing while user has amnesia
5931    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5932            List<ResolveInfo> query, int priority, boolean always,
5933            boolean removeMatches, boolean debug, int userId) {
5934        if (!sUserManager.exists(userId)) return null;
5935        flags = updateFlagsForResolve(flags, userId, intent, false);
5936        intent = updateIntentForResolve(intent);
5937        // writer
5938        synchronized (mPackages) {
5939            // Try to find a matching persistent preferred activity.
5940            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5941                    debug, userId);
5942
5943            // If a persistent preferred activity matched, use it.
5944            if (pri != null) {
5945                return pri;
5946            }
5947
5948            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5949            // Get the list of preferred activities that handle the intent
5950            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5951            List<PreferredActivity> prefs = pir != null
5952                    ? pir.queryIntent(intent, resolvedType,
5953                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5954                            userId)
5955                    : null;
5956            if (prefs != null && prefs.size() > 0) {
5957                boolean changed = false;
5958                try {
5959                    // First figure out how good the original match set is.
5960                    // We will only allow preferred activities that came
5961                    // from the same match quality.
5962                    int match = 0;
5963
5964                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5965
5966                    final int N = query.size();
5967                    for (int j=0; j<N; j++) {
5968                        final ResolveInfo ri = query.get(j);
5969                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5970                                + ": 0x" + Integer.toHexString(match));
5971                        if (ri.match > match) {
5972                            match = ri.match;
5973                        }
5974                    }
5975
5976                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5977                            + Integer.toHexString(match));
5978
5979                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5980                    final int M = prefs.size();
5981                    for (int i=0; i<M; i++) {
5982                        final PreferredActivity pa = prefs.get(i);
5983                        if (DEBUG_PREFERRED || debug) {
5984                            Slog.v(TAG, "Checking PreferredActivity ds="
5985                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5986                                    + "\n  component=" + pa.mPref.mComponent);
5987                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5988                        }
5989                        if (pa.mPref.mMatch != match) {
5990                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5991                                    + Integer.toHexString(pa.mPref.mMatch));
5992                            continue;
5993                        }
5994                        // If it's not an "always" type preferred activity and that's what we're
5995                        // looking for, skip it.
5996                        if (always && !pa.mPref.mAlways) {
5997                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5998                            continue;
5999                        }
6000                        final ActivityInfo ai = getActivityInfo(
6001                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6002                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6003                                userId);
6004                        if (DEBUG_PREFERRED || debug) {
6005                            Slog.v(TAG, "Found preferred activity:");
6006                            if (ai != null) {
6007                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6008                            } else {
6009                                Slog.v(TAG, "  null");
6010                            }
6011                        }
6012                        if (ai == null) {
6013                            // This previously registered preferred activity
6014                            // component is no longer known.  Most likely an update
6015                            // to the app was installed and in the new version this
6016                            // component no longer exists.  Clean it up by removing
6017                            // it from the preferred activities list, and skip it.
6018                            Slog.w(TAG, "Removing dangling preferred activity: "
6019                                    + pa.mPref.mComponent);
6020                            pir.removeFilter(pa);
6021                            changed = true;
6022                            continue;
6023                        }
6024                        for (int j=0; j<N; j++) {
6025                            final ResolveInfo ri = query.get(j);
6026                            if (!ri.activityInfo.applicationInfo.packageName
6027                                    .equals(ai.applicationInfo.packageName)) {
6028                                continue;
6029                            }
6030                            if (!ri.activityInfo.name.equals(ai.name)) {
6031                                continue;
6032                            }
6033
6034                            if (removeMatches) {
6035                                pir.removeFilter(pa);
6036                                changed = true;
6037                                if (DEBUG_PREFERRED) {
6038                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6039                                }
6040                                break;
6041                            }
6042
6043                            // Okay we found a previously set preferred or last chosen app.
6044                            // If the result set is different from when this
6045                            // was created, we need to clear it and re-ask the
6046                            // user their preference, if we're looking for an "always" type entry.
6047                            if (always && !pa.mPref.sameSet(query)) {
6048                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6049                                        + intent + " type " + resolvedType);
6050                                if (DEBUG_PREFERRED) {
6051                                    Slog.v(TAG, "Removing preferred activity since set changed "
6052                                            + pa.mPref.mComponent);
6053                                }
6054                                pir.removeFilter(pa);
6055                                // Re-add the filter as a "last chosen" entry (!always)
6056                                PreferredActivity lastChosen = new PreferredActivity(
6057                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6058                                pir.addFilter(lastChosen);
6059                                changed = true;
6060                                return null;
6061                            }
6062
6063                            // Yay! Either the set matched or we're looking for the last chosen
6064                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6065                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6066                            return ri;
6067                        }
6068                    }
6069                } finally {
6070                    if (changed) {
6071                        if (DEBUG_PREFERRED) {
6072                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6073                        }
6074                        scheduleWritePackageRestrictionsLocked(userId);
6075                    }
6076                }
6077            }
6078        }
6079        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6080        return null;
6081    }
6082
6083    /*
6084     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6085     */
6086    @Override
6087    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6088            int targetUserId) {
6089        mContext.enforceCallingOrSelfPermission(
6090                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6091        List<CrossProfileIntentFilter> matches =
6092                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6093        if (matches != null) {
6094            int size = matches.size();
6095            for (int i = 0; i < size; i++) {
6096                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6097            }
6098        }
6099        if (hasWebURI(intent)) {
6100            // cross-profile app linking works only towards the parent.
6101            final UserInfo parent = getProfileParent(sourceUserId);
6102            synchronized(mPackages) {
6103                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6104                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6105                        intent, resolvedType, flags, sourceUserId, parent.id);
6106                return xpDomainInfo != null;
6107            }
6108        }
6109        return false;
6110    }
6111
6112    private UserInfo getProfileParent(int userId) {
6113        final long identity = Binder.clearCallingIdentity();
6114        try {
6115            return sUserManager.getProfileParent(userId);
6116        } finally {
6117            Binder.restoreCallingIdentity(identity);
6118        }
6119    }
6120
6121    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6122            String resolvedType, int userId) {
6123        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6124        if (resolver != null) {
6125            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6126        }
6127        return null;
6128    }
6129
6130    @Override
6131    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6132            String resolvedType, int flags, int userId) {
6133        try {
6134            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6135
6136            return new ParceledListSlice<>(
6137                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6138        } finally {
6139            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6140        }
6141    }
6142
6143    /**
6144     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6145     * instant, returns {@code null}.
6146     */
6147    private String getInstantAppPackageName(int callingUid) {
6148        final int appId = UserHandle.getAppId(callingUid);
6149        synchronized (mPackages) {
6150            final Object obj = mSettings.getUserIdLPr(appId);
6151            if (obj instanceof PackageSetting) {
6152                final PackageSetting ps = (PackageSetting) obj;
6153                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6154                return isInstantApp ? ps.pkg.packageName : null;
6155            }
6156        }
6157        return null;
6158    }
6159
6160    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6161            String resolvedType, int flags, int userId) {
6162        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6163    }
6164
6165    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6166            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6167        if (!sUserManager.exists(userId)) return Collections.emptyList();
6168        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6169        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6170        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6171                false /* requireFullPermission */, false /* checkShell */,
6172                "query intent activities");
6173        ComponentName comp = intent.getComponent();
6174        if (comp == null) {
6175            if (intent.getSelector() != null) {
6176                intent = intent.getSelector();
6177                comp = intent.getComponent();
6178            }
6179        }
6180
6181        if (comp != null) {
6182            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6183            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6184            if (ai != null) {
6185                // When specifying an explicit component, we prevent the activity from being
6186                // used when either 1) the calling package is normal and the activity is within
6187                // an ephemeral application or 2) the calling package is ephemeral and the
6188                // activity is not visible to ephemeral applications.
6189                final boolean matchInstantApp =
6190                        (flags & PackageManager.MATCH_INSTANT) != 0;
6191                final boolean matchVisibleToInstantAppOnly =
6192                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6193                final boolean isCallerInstantApp =
6194                        instantAppPkgName != null;
6195                final boolean isTargetSameInstantApp =
6196                        comp.getPackageName().equals(instantAppPkgName);
6197                final boolean isTargetInstantApp =
6198                        (ai.applicationInfo.privateFlags
6199                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6200                final boolean isTargetHiddenFromInstantApp =
6201                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6202                final boolean blockResolution =
6203                        !isTargetSameInstantApp
6204                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6205                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6206                                        && isTargetHiddenFromInstantApp));
6207                if (!blockResolution) {
6208                    final ResolveInfo ri = new ResolveInfo();
6209                    ri.activityInfo = ai;
6210                    list.add(ri);
6211                }
6212            }
6213            return applyPostResolutionFilter(list, instantAppPkgName);
6214        }
6215
6216        // reader
6217        boolean sortResult = false;
6218        boolean addEphemeral = false;
6219        List<ResolveInfo> result;
6220        final String pkgName = intent.getPackage();
6221        final boolean ephemeralDisabled = isEphemeralDisabled();
6222        synchronized (mPackages) {
6223            if (pkgName == null) {
6224                List<CrossProfileIntentFilter> matchingFilters =
6225                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6226                // Check for results that need to skip the current profile.
6227                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6228                        resolvedType, flags, userId);
6229                if (xpResolveInfo != null) {
6230                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6231                    xpResult.add(xpResolveInfo);
6232                    return applyPostResolutionFilter(
6233                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6234                }
6235
6236                // Check for results in the current profile.
6237                result = filterIfNotSystemUser(mActivities.queryIntent(
6238                        intent, resolvedType, flags, userId), userId);
6239                addEphemeral = !ephemeralDisabled
6240                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6241
6242                // Check for cross profile results.
6243                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6244                xpResolveInfo = queryCrossProfileIntents(
6245                        matchingFilters, intent, resolvedType, flags, userId,
6246                        hasNonNegativePriorityResult);
6247                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6248                    boolean isVisibleToUser = filterIfNotSystemUser(
6249                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6250                    if (isVisibleToUser) {
6251                        result.add(xpResolveInfo);
6252                        sortResult = true;
6253                    }
6254                }
6255                if (hasWebURI(intent)) {
6256                    CrossProfileDomainInfo xpDomainInfo = null;
6257                    final UserInfo parent = getProfileParent(userId);
6258                    if (parent != null) {
6259                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6260                                flags, userId, parent.id);
6261                    }
6262                    if (xpDomainInfo != null) {
6263                        if (xpResolveInfo != null) {
6264                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6265                            // in the result.
6266                            result.remove(xpResolveInfo);
6267                        }
6268                        if (result.size() == 0 && !addEphemeral) {
6269                            // No result in current profile, but found candidate in parent user.
6270                            // And we are not going to add emphemeral app, so we can return the
6271                            // result straight away.
6272                            result.add(xpDomainInfo.resolveInfo);
6273                            return applyPostResolutionFilter(result, instantAppPkgName);
6274                        }
6275                    } else if (result.size() <= 1 && !addEphemeral) {
6276                        // No result in parent user and <= 1 result in current profile, and we
6277                        // are not going to add emphemeral app, so we can return the result without
6278                        // further processing.
6279                        return applyPostResolutionFilter(result, instantAppPkgName);
6280                    }
6281                    // We have more than one candidate (combining results from current and parent
6282                    // profile), so we need filtering and sorting.
6283                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6284                            intent, flags, result, xpDomainInfo, userId);
6285                    sortResult = true;
6286                }
6287            } else {
6288                final PackageParser.Package pkg = mPackages.get(pkgName);
6289                if (pkg != null) {
6290                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6291                            mActivities.queryIntentForPackage(
6292                                    intent, resolvedType, flags, pkg.activities, userId),
6293                            userId), instantAppPkgName);
6294                } else {
6295                    // the caller wants to resolve for a particular package; however, there
6296                    // were no installed results, so, try to find an ephemeral result
6297                    addEphemeral =  !ephemeralDisabled
6298                            && isEphemeralAllowed(
6299                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6300                    result = new ArrayList<ResolveInfo>();
6301                }
6302            }
6303        }
6304        if (addEphemeral) {
6305            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6306            final InstantAppRequest requestObject = new InstantAppRequest(
6307                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6308                    null /*callingPackage*/, userId);
6309            final AuxiliaryResolveInfo auxiliaryResponse =
6310                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6311                            mContext, mInstantAppResolverConnection, requestObject);
6312            if (auxiliaryResponse != null) {
6313                if (DEBUG_EPHEMERAL) {
6314                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6315                }
6316                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6317                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6318                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6319                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6320                // make sure this resolver is the default
6321                ephemeralInstaller.isDefault = true;
6322                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6323                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6324                // add a non-generic filter
6325                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6326                ephemeralInstaller.filter.addDataPath(
6327                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6328                ephemeralInstaller.instantAppAvailable = true;
6329                result.add(ephemeralInstaller);
6330            }
6331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6332        }
6333        if (sortResult) {
6334            Collections.sort(result, mResolvePrioritySorter);
6335        }
6336        return applyPostResolutionFilter(result, instantAppPkgName);
6337    }
6338
6339    private static class CrossProfileDomainInfo {
6340        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6341        ResolveInfo resolveInfo;
6342        /* Best domain verification status of the activities found in the other profile */
6343        int bestDomainVerificationStatus;
6344    }
6345
6346    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6347            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6348        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6349                sourceUserId)) {
6350            return null;
6351        }
6352        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6353                resolvedType, flags, parentUserId);
6354
6355        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6356            return null;
6357        }
6358        CrossProfileDomainInfo result = null;
6359        int size = resultTargetUser.size();
6360        for (int i = 0; i < size; i++) {
6361            ResolveInfo riTargetUser = resultTargetUser.get(i);
6362            // Intent filter verification is only for filters that specify a host. So don't return
6363            // those that handle all web uris.
6364            if (riTargetUser.handleAllWebDataURI) {
6365                continue;
6366            }
6367            String packageName = riTargetUser.activityInfo.packageName;
6368            PackageSetting ps = mSettings.mPackages.get(packageName);
6369            if (ps == null) {
6370                continue;
6371            }
6372            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6373            int status = (int)(verificationState >> 32);
6374            if (result == null) {
6375                result = new CrossProfileDomainInfo();
6376                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6377                        sourceUserId, parentUserId);
6378                result.bestDomainVerificationStatus = status;
6379            } else {
6380                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6381                        result.bestDomainVerificationStatus);
6382            }
6383        }
6384        // Don't consider matches with status NEVER across profiles.
6385        if (result != null && result.bestDomainVerificationStatus
6386                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6387            return null;
6388        }
6389        return result;
6390    }
6391
6392    /**
6393     * Verification statuses are ordered from the worse to the best, except for
6394     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6395     */
6396    private int bestDomainVerificationStatus(int status1, int status2) {
6397        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6398            return status2;
6399        }
6400        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6401            return status1;
6402        }
6403        return (int) MathUtils.max(status1, status2);
6404    }
6405
6406    private boolean isUserEnabled(int userId) {
6407        long callingId = Binder.clearCallingIdentity();
6408        try {
6409            UserInfo userInfo = sUserManager.getUserInfo(userId);
6410            return userInfo != null && userInfo.isEnabled();
6411        } finally {
6412            Binder.restoreCallingIdentity(callingId);
6413        }
6414    }
6415
6416    /**
6417     * Filter out activities with systemUserOnly flag set, when current user is not System.
6418     *
6419     * @return filtered list
6420     */
6421    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6422        if (userId == UserHandle.USER_SYSTEM) {
6423            return resolveInfos;
6424        }
6425        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6426            ResolveInfo info = resolveInfos.get(i);
6427            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6428                resolveInfos.remove(i);
6429            }
6430        }
6431        return resolveInfos;
6432    }
6433
6434    /**
6435     * Filters out ephemeral activities.
6436     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6437     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6438     *
6439     * @param resolveInfos The pre-filtered list of resolved activities
6440     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6441     *          is performed.
6442     * @return A filtered list of resolved activities.
6443     */
6444    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6445            String ephemeralPkgName) {
6446        // TODO: When adding on-demand split support for non-instant apps, remove this check
6447        // and always apply post filtering
6448        if (ephemeralPkgName == null) {
6449            return resolveInfos;
6450        }
6451        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6452            final ResolveInfo info = resolveInfos.get(i);
6453            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6454            // allow activities that are defined in the provided package
6455            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6456                if (info.activityInfo.splitName != null
6457                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6458                                info.activityInfo.splitName)) {
6459                    // requested activity is defined in a split that hasn't been installed yet.
6460                    // add the installer to the resolve list
6461                    if (DEBUG_EPHEMERAL) {
6462                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6463                    }
6464                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6465                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6466                            info.activityInfo.packageName, info.activityInfo.splitName,
6467                            info.activityInfo.applicationInfo.versionCode);
6468                    // make sure this resolver is the default
6469                    installerInfo.isDefault = true;
6470                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6471                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6472                    // add a non-generic filter
6473                    installerInfo.filter = new IntentFilter();
6474                    // load resources from the correct package
6475                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6476                    resolveInfos.set(i, installerInfo);
6477                }
6478                continue;
6479            }
6480            // allow activities that have been explicitly exposed to ephemeral apps
6481            if (!isEphemeralApp
6482                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6483                continue;
6484            }
6485            resolveInfos.remove(i);
6486        }
6487        return resolveInfos;
6488    }
6489
6490    /**
6491     * @param resolveInfos list of resolve infos in descending priority order
6492     * @return if the list contains a resolve info with non-negative priority
6493     */
6494    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6495        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6496    }
6497
6498    private static boolean hasWebURI(Intent intent) {
6499        if (intent.getData() == null) {
6500            return false;
6501        }
6502        final String scheme = intent.getScheme();
6503        if (TextUtils.isEmpty(scheme)) {
6504            return false;
6505        }
6506        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6507    }
6508
6509    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6510            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6511            int userId) {
6512        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6513
6514        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6515            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6516                    candidates.size());
6517        }
6518
6519        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6520        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6521        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6522        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6523        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6524        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6525
6526        synchronized (mPackages) {
6527            final int count = candidates.size();
6528            // First, try to use linked apps. Partition the candidates into four lists:
6529            // one for the final results, one for the "do not use ever", one for "undefined status"
6530            // and finally one for "browser app type".
6531            for (int n=0; n<count; n++) {
6532                ResolveInfo info = candidates.get(n);
6533                String packageName = info.activityInfo.packageName;
6534                PackageSetting ps = mSettings.mPackages.get(packageName);
6535                if (ps != null) {
6536                    // Add to the special match all list (Browser use case)
6537                    if (info.handleAllWebDataURI) {
6538                        matchAllList.add(info);
6539                        continue;
6540                    }
6541                    // Try to get the status from User settings first
6542                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6543                    int status = (int)(packedStatus >> 32);
6544                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6545                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6546                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6547                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6548                                    + " : linkgen=" + linkGeneration);
6549                        }
6550                        // Use link-enabled generation as preferredOrder, i.e.
6551                        // prefer newly-enabled over earlier-enabled.
6552                        info.preferredOrder = linkGeneration;
6553                        alwaysList.add(info);
6554                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6555                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6556                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6557                        }
6558                        neverList.add(info);
6559                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6560                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6561                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6562                        }
6563                        alwaysAskList.add(info);
6564                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6565                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6566                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6567                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6568                        }
6569                        undefinedList.add(info);
6570                    }
6571                }
6572            }
6573
6574            // We'll want to include browser possibilities in a few cases
6575            boolean includeBrowser = false;
6576
6577            // First try to add the "always" resolution(s) for the current user, if any
6578            if (alwaysList.size() > 0) {
6579                result.addAll(alwaysList);
6580            } else {
6581                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6582                result.addAll(undefinedList);
6583                // Maybe add one for the other profile.
6584                if (xpDomainInfo != null && (
6585                        xpDomainInfo.bestDomainVerificationStatus
6586                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6587                    result.add(xpDomainInfo.resolveInfo);
6588                }
6589                includeBrowser = true;
6590            }
6591
6592            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6593            // If there were 'always' entries their preferred order has been set, so we also
6594            // back that off to make the alternatives equivalent
6595            if (alwaysAskList.size() > 0) {
6596                for (ResolveInfo i : result) {
6597                    i.preferredOrder = 0;
6598                }
6599                result.addAll(alwaysAskList);
6600                includeBrowser = true;
6601            }
6602
6603            if (includeBrowser) {
6604                // Also add browsers (all of them or only the default one)
6605                if (DEBUG_DOMAIN_VERIFICATION) {
6606                    Slog.v(TAG, "   ...including browsers in candidate set");
6607                }
6608                if ((matchFlags & MATCH_ALL) != 0) {
6609                    result.addAll(matchAllList);
6610                } else {
6611                    // Browser/generic handling case.  If there's a default browser, go straight
6612                    // to that (but only if there is no other higher-priority match).
6613                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6614                    int maxMatchPrio = 0;
6615                    ResolveInfo defaultBrowserMatch = null;
6616                    final int numCandidates = matchAllList.size();
6617                    for (int n = 0; n < numCandidates; n++) {
6618                        ResolveInfo info = matchAllList.get(n);
6619                        // track the highest overall match priority...
6620                        if (info.priority > maxMatchPrio) {
6621                            maxMatchPrio = info.priority;
6622                        }
6623                        // ...and the highest-priority default browser match
6624                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6625                            if (defaultBrowserMatch == null
6626                                    || (defaultBrowserMatch.priority < info.priority)) {
6627                                if (debug) {
6628                                    Slog.v(TAG, "Considering default browser match " + info);
6629                                }
6630                                defaultBrowserMatch = info;
6631                            }
6632                        }
6633                    }
6634                    if (defaultBrowserMatch != null
6635                            && defaultBrowserMatch.priority >= maxMatchPrio
6636                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6637                    {
6638                        if (debug) {
6639                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6640                        }
6641                        result.add(defaultBrowserMatch);
6642                    } else {
6643                        result.addAll(matchAllList);
6644                    }
6645                }
6646
6647                // If there is nothing selected, add all candidates and remove the ones that the user
6648                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6649                if (result.size() == 0) {
6650                    result.addAll(candidates);
6651                    result.removeAll(neverList);
6652                }
6653            }
6654        }
6655        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6656            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6657                    result.size());
6658            for (ResolveInfo info : result) {
6659                Slog.v(TAG, "  + " + info.activityInfo);
6660            }
6661        }
6662        return result;
6663    }
6664
6665    // Returns a packed value as a long:
6666    //
6667    // high 'int'-sized word: link status: undefined/ask/never/always.
6668    // low 'int'-sized word: relative priority among 'always' results.
6669    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6670        long result = ps.getDomainVerificationStatusForUser(userId);
6671        // if none available, get the master status
6672        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6673            if (ps.getIntentFilterVerificationInfo() != null) {
6674                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6675            }
6676        }
6677        return result;
6678    }
6679
6680    private ResolveInfo querySkipCurrentProfileIntents(
6681            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6682            int flags, int sourceUserId) {
6683        if (matchingFilters != null) {
6684            int size = matchingFilters.size();
6685            for (int i = 0; i < size; i ++) {
6686                CrossProfileIntentFilter filter = matchingFilters.get(i);
6687                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6688                    // Checking if there are activities in the target user that can handle the
6689                    // intent.
6690                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6691                            resolvedType, flags, sourceUserId);
6692                    if (resolveInfo != null) {
6693                        return resolveInfo;
6694                    }
6695                }
6696            }
6697        }
6698        return null;
6699    }
6700
6701    // Return matching ResolveInfo in target user if any.
6702    private ResolveInfo queryCrossProfileIntents(
6703            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6704            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6705        if (matchingFilters != null) {
6706            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6707            // match the same intent. For performance reasons, it is better not to
6708            // run queryIntent twice for the same userId
6709            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6710            int size = matchingFilters.size();
6711            for (int i = 0; i < size; i++) {
6712                CrossProfileIntentFilter filter = matchingFilters.get(i);
6713                int targetUserId = filter.getTargetUserId();
6714                boolean skipCurrentProfile =
6715                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6716                boolean skipCurrentProfileIfNoMatchFound =
6717                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6718                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6719                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6720                    // Checking if there are activities in the target user that can handle the
6721                    // intent.
6722                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6723                            resolvedType, flags, sourceUserId);
6724                    if (resolveInfo != null) return resolveInfo;
6725                    alreadyTriedUserIds.put(targetUserId, true);
6726                }
6727            }
6728        }
6729        return null;
6730    }
6731
6732    /**
6733     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6734     * will forward the intent to the filter's target user.
6735     * Otherwise, returns null.
6736     */
6737    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6738            String resolvedType, int flags, int sourceUserId) {
6739        int targetUserId = filter.getTargetUserId();
6740        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6741                resolvedType, flags, targetUserId);
6742        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6743            // If all the matches in the target profile are suspended, return null.
6744            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6745                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6746                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6747                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6748                            targetUserId);
6749                }
6750            }
6751        }
6752        return null;
6753    }
6754
6755    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6756            int sourceUserId, int targetUserId) {
6757        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6758        long ident = Binder.clearCallingIdentity();
6759        boolean targetIsProfile;
6760        try {
6761            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6762        } finally {
6763            Binder.restoreCallingIdentity(ident);
6764        }
6765        String className;
6766        if (targetIsProfile) {
6767            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6768        } else {
6769            className = FORWARD_INTENT_TO_PARENT;
6770        }
6771        ComponentName forwardingActivityComponentName = new ComponentName(
6772                mAndroidApplication.packageName, className);
6773        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6774                sourceUserId);
6775        if (!targetIsProfile) {
6776            forwardingActivityInfo.showUserIcon = targetUserId;
6777            forwardingResolveInfo.noResourceId = true;
6778        }
6779        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6780        forwardingResolveInfo.priority = 0;
6781        forwardingResolveInfo.preferredOrder = 0;
6782        forwardingResolveInfo.match = 0;
6783        forwardingResolveInfo.isDefault = true;
6784        forwardingResolveInfo.filter = filter;
6785        forwardingResolveInfo.targetUserId = targetUserId;
6786        return forwardingResolveInfo;
6787    }
6788
6789    @Override
6790    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6791            Intent[] specifics, String[] specificTypes, Intent intent,
6792            String resolvedType, int flags, int userId) {
6793        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6794                specificTypes, intent, resolvedType, flags, userId));
6795    }
6796
6797    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6798            Intent[] specifics, String[] specificTypes, Intent intent,
6799            String resolvedType, int flags, int userId) {
6800        if (!sUserManager.exists(userId)) return Collections.emptyList();
6801        flags = updateFlagsForResolve(flags, userId, intent, false);
6802        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6803                false /* requireFullPermission */, false /* checkShell */,
6804                "query intent activity options");
6805        final String resultsAction = intent.getAction();
6806
6807        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6808                | PackageManager.GET_RESOLVED_FILTER, userId);
6809
6810        if (DEBUG_INTENT_MATCHING) {
6811            Log.v(TAG, "Query " + intent + ": " + results);
6812        }
6813
6814        int specificsPos = 0;
6815        int N;
6816
6817        // todo: note that the algorithm used here is O(N^2).  This
6818        // isn't a problem in our current environment, but if we start running
6819        // into situations where we have more than 5 or 10 matches then this
6820        // should probably be changed to something smarter...
6821
6822        // First we go through and resolve each of the specific items
6823        // that were supplied, taking care of removing any corresponding
6824        // duplicate items in the generic resolve list.
6825        if (specifics != null) {
6826            for (int i=0; i<specifics.length; i++) {
6827                final Intent sintent = specifics[i];
6828                if (sintent == null) {
6829                    continue;
6830                }
6831
6832                if (DEBUG_INTENT_MATCHING) {
6833                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6834                }
6835
6836                String action = sintent.getAction();
6837                if (resultsAction != null && resultsAction.equals(action)) {
6838                    // If this action was explicitly requested, then don't
6839                    // remove things that have it.
6840                    action = null;
6841                }
6842
6843                ResolveInfo ri = null;
6844                ActivityInfo ai = null;
6845
6846                ComponentName comp = sintent.getComponent();
6847                if (comp == null) {
6848                    ri = resolveIntent(
6849                        sintent,
6850                        specificTypes != null ? specificTypes[i] : null,
6851                            flags, userId);
6852                    if (ri == null) {
6853                        continue;
6854                    }
6855                    if (ri == mResolveInfo) {
6856                        // ACK!  Must do something better with this.
6857                    }
6858                    ai = ri.activityInfo;
6859                    comp = new ComponentName(ai.applicationInfo.packageName,
6860                            ai.name);
6861                } else {
6862                    ai = getActivityInfo(comp, flags, userId);
6863                    if (ai == null) {
6864                        continue;
6865                    }
6866                }
6867
6868                // Look for any generic query activities that are duplicates
6869                // of this specific one, and remove them from the results.
6870                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6871                N = results.size();
6872                int j;
6873                for (j=specificsPos; j<N; j++) {
6874                    ResolveInfo sri = results.get(j);
6875                    if ((sri.activityInfo.name.equals(comp.getClassName())
6876                            && sri.activityInfo.applicationInfo.packageName.equals(
6877                                    comp.getPackageName()))
6878                        || (action != null && sri.filter.matchAction(action))) {
6879                        results.remove(j);
6880                        if (DEBUG_INTENT_MATCHING) Log.v(
6881                            TAG, "Removing duplicate item from " + j
6882                            + " due to specific " + specificsPos);
6883                        if (ri == null) {
6884                            ri = sri;
6885                        }
6886                        j--;
6887                        N--;
6888                    }
6889                }
6890
6891                // Add this specific item to its proper place.
6892                if (ri == null) {
6893                    ri = new ResolveInfo();
6894                    ri.activityInfo = ai;
6895                }
6896                results.add(specificsPos, ri);
6897                ri.specificIndex = i;
6898                specificsPos++;
6899            }
6900        }
6901
6902        // Now we go through the remaining generic results and remove any
6903        // duplicate actions that are found here.
6904        N = results.size();
6905        for (int i=specificsPos; i<N-1; i++) {
6906            final ResolveInfo rii = results.get(i);
6907            if (rii.filter == null) {
6908                continue;
6909            }
6910
6911            // Iterate over all of the actions of this result's intent
6912            // filter...  typically this should be just one.
6913            final Iterator<String> it = rii.filter.actionsIterator();
6914            if (it == null) {
6915                continue;
6916            }
6917            while (it.hasNext()) {
6918                final String action = it.next();
6919                if (resultsAction != null && resultsAction.equals(action)) {
6920                    // If this action was explicitly requested, then don't
6921                    // remove things that have it.
6922                    continue;
6923                }
6924                for (int j=i+1; j<N; j++) {
6925                    final ResolveInfo rij = results.get(j);
6926                    if (rij.filter != null && rij.filter.hasAction(action)) {
6927                        results.remove(j);
6928                        if (DEBUG_INTENT_MATCHING) Log.v(
6929                            TAG, "Removing duplicate item from " + j
6930                            + " due to action " + action + " at " + i);
6931                        j--;
6932                        N--;
6933                    }
6934                }
6935            }
6936
6937            // If the caller didn't request filter information, drop it now
6938            // so we don't have to marshall/unmarshall it.
6939            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6940                rii.filter = null;
6941            }
6942        }
6943
6944        // Filter out the caller activity if so requested.
6945        if (caller != null) {
6946            N = results.size();
6947            for (int i=0; i<N; i++) {
6948                ActivityInfo ainfo = results.get(i).activityInfo;
6949                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6950                        && caller.getClassName().equals(ainfo.name)) {
6951                    results.remove(i);
6952                    break;
6953                }
6954            }
6955        }
6956
6957        // If the caller didn't request filter information,
6958        // drop them now so we don't have to
6959        // marshall/unmarshall it.
6960        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6961            N = results.size();
6962            for (int i=0; i<N; i++) {
6963                results.get(i).filter = null;
6964            }
6965        }
6966
6967        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6968        return results;
6969    }
6970
6971    @Override
6972    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6973            String resolvedType, int flags, int userId) {
6974        return new ParceledListSlice<>(
6975                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6976    }
6977
6978    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6979            String resolvedType, int flags, int userId) {
6980        if (!sUserManager.exists(userId)) return Collections.emptyList();
6981        flags = updateFlagsForResolve(flags, userId, intent, false);
6982        ComponentName comp = intent.getComponent();
6983        if (comp == null) {
6984            if (intent.getSelector() != null) {
6985                intent = intent.getSelector();
6986                comp = intent.getComponent();
6987            }
6988        }
6989        if (comp != null) {
6990            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6991            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6992            if (ai != null) {
6993                ResolveInfo ri = new ResolveInfo();
6994                ri.activityInfo = ai;
6995                list.add(ri);
6996            }
6997            return list;
6998        }
6999
7000        // reader
7001        synchronized (mPackages) {
7002            String pkgName = intent.getPackage();
7003            if (pkgName == null) {
7004                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7005            }
7006            final PackageParser.Package pkg = mPackages.get(pkgName);
7007            if (pkg != null) {
7008                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7009                        userId);
7010            }
7011            return Collections.emptyList();
7012        }
7013    }
7014
7015    @Override
7016    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7017        if (!sUserManager.exists(userId)) return null;
7018        flags = updateFlagsForResolve(flags, userId, intent, false);
7019        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7020        if (query != null) {
7021            if (query.size() >= 1) {
7022                // If there is more than one service with the same priority,
7023                // just arbitrarily pick the first one.
7024                return query.get(0);
7025            }
7026        }
7027        return null;
7028    }
7029
7030    @Override
7031    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7032            String resolvedType, int flags, int userId) {
7033        return new ParceledListSlice<>(
7034                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7035    }
7036
7037    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7038            String resolvedType, int flags, int userId) {
7039        if (!sUserManager.exists(userId)) return Collections.emptyList();
7040        flags = updateFlagsForResolve(flags, userId, intent, false);
7041        ComponentName comp = intent.getComponent();
7042        if (comp == null) {
7043            if (intent.getSelector() != null) {
7044                intent = intent.getSelector();
7045                comp = intent.getComponent();
7046            }
7047        }
7048        if (comp != null) {
7049            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7050            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7051            if (si != null) {
7052                final ResolveInfo ri = new ResolveInfo();
7053                ri.serviceInfo = si;
7054                list.add(ri);
7055            }
7056            return list;
7057        }
7058
7059        // reader
7060        synchronized (mPackages) {
7061            String pkgName = intent.getPackage();
7062            if (pkgName == null) {
7063                return mServices.queryIntent(intent, resolvedType, flags, userId);
7064            }
7065            final PackageParser.Package pkg = mPackages.get(pkgName);
7066            if (pkg != null) {
7067                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7068                        userId);
7069            }
7070            return Collections.emptyList();
7071        }
7072    }
7073
7074    @Override
7075    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7076            String resolvedType, int flags, int userId) {
7077        return new ParceledListSlice<>(
7078                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7079    }
7080
7081    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7082            Intent intent, String resolvedType, int flags, int userId) {
7083        if (!sUserManager.exists(userId)) return Collections.emptyList();
7084        flags = updateFlagsForResolve(flags, userId, intent, false);
7085        ComponentName comp = intent.getComponent();
7086        if (comp == null) {
7087            if (intent.getSelector() != null) {
7088                intent = intent.getSelector();
7089                comp = intent.getComponent();
7090            }
7091        }
7092        if (comp != null) {
7093            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7094            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7095            if (pi != null) {
7096                final ResolveInfo ri = new ResolveInfo();
7097                ri.providerInfo = pi;
7098                list.add(ri);
7099            }
7100            return list;
7101        }
7102
7103        // reader
7104        synchronized (mPackages) {
7105            String pkgName = intent.getPackage();
7106            if (pkgName == null) {
7107                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7108            }
7109            final PackageParser.Package pkg = mPackages.get(pkgName);
7110            if (pkg != null) {
7111                return mProviders.queryIntentForPackage(
7112                        intent, resolvedType, flags, pkg.providers, userId);
7113            }
7114            return Collections.emptyList();
7115        }
7116    }
7117
7118    @Override
7119    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7120        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7121        flags = updateFlagsForPackage(flags, userId, null);
7122        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7124                true /* requireFullPermission */, false /* checkShell */,
7125                "get installed packages");
7126
7127        // writer
7128        synchronized (mPackages) {
7129            ArrayList<PackageInfo> list;
7130            if (listUninstalled) {
7131                list = new ArrayList<>(mSettings.mPackages.size());
7132                for (PackageSetting ps : mSettings.mPackages.values()) {
7133                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7134                        continue;
7135                    }
7136                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7137                    if (pi != null) {
7138                        list.add(pi);
7139                    }
7140                }
7141            } else {
7142                list = new ArrayList<>(mPackages.size());
7143                for (PackageParser.Package p : mPackages.values()) {
7144                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7145                            Binder.getCallingUid(), userId)) {
7146                        continue;
7147                    }
7148                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7149                            p.mExtras, flags, userId);
7150                    if (pi != null) {
7151                        list.add(pi);
7152                    }
7153                }
7154            }
7155
7156            return new ParceledListSlice<>(list);
7157        }
7158    }
7159
7160    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7161            String[] permissions, boolean[] tmp, int flags, int userId) {
7162        int numMatch = 0;
7163        final PermissionsState permissionsState = ps.getPermissionsState();
7164        for (int i=0; i<permissions.length; i++) {
7165            final String permission = permissions[i];
7166            if (permissionsState.hasPermission(permission, userId)) {
7167                tmp[i] = true;
7168                numMatch++;
7169            } else {
7170                tmp[i] = false;
7171            }
7172        }
7173        if (numMatch == 0) {
7174            return;
7175        }
7176        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7177
7178        // The above might return null in cases of uninstalled apps or install-state
7179        // skew across users/profiles.
7180        if (pi != null) {
7181            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7182                if (numMatch == permissions.length) {
7183                    pi.requestedPermissions = permissions;
7184                } else {
7185                    pi.requestedPermissions = new String[numMatch];
7186                    numMatch = 0;
7187                    for (int i=0; i<permissions.length; i++) {
7188                        if (tmp[i]) {
7189                            pi.requestedPermissions[numMatch] = permissions[i];
7190                            numMatch++;
7191                        }
7192                    }
7193                }
7194            }
7195            list.add(pi);
7196        }
7197    }
7198
7199    @Override
7200    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7201            String[] permissions, int flags, int userId) {
7202        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7203        flags = updateFlagsForPackage(flags, userId, permissions);
7204        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7205                true /* requireFullPermission */, false /* checkShell */,
7206                "get packages holding permissions");
7207        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7208
7209        // writer
7210        synchronized (mPackages) {
7211            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7212            boolean[] tmpBools = new boolean[permissions.length];
7213            if (listUninstalled) {
7214                for (PackageSetting ps : mSettings.mPackages.values()) {
7215                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7216                            userId);
7217                }
7218            } else {
7219                for (PackageParser.Package pkg : mPackages.values()) {
7220                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7221                    if (ps != null) {
7222                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7223                                userId);
7224                    }
7225                }
7226            }
7227
7228            return new ParceledListSlice<PackageInfo>(list);
7229        }
7230    }
7231
7232    @Override
7233    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7234        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7235        flags = updateFlagsForApplication(flags, userId, null);
7236        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7237
7238        // writer
7239        synchronized (mPackages) {
7240            ArrayList<ApplicationInfo> list;
7241            if (listUninstalled) {
7242                list = new ArrayList<>(mSettings.mPackages.size());
7243                for (PackageSetting ps : mSettings.mPackages.values()) {
7244                    ApplicationInfo ai;
7245                    int effectiveFlags = flags;
7246                    if (ps.isSystem()) {
7247                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7248                    }
7249                    if (ps.pkg != null) {
7250                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7251                            continue;
7252                        }
7253                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7254                                ps.readUserState(userId), userId);
7255                        if (ai != null) {
7256                            rebaseEnabledOverlays(ai, userId);
7257                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7258                        }
7259                    } else {
7260                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7261                        // and already converts to externally visible package name
7262                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7263                                Binder.getCallingUid(), effectiveFlags, userId);
7264                    }
7265                    if (ai != null) {
7266                        list.add(ai);
7267                    }
7268                }
7269            } else {
7270                list = new ArrayList<>(mPackages.size());
7271                for (PackageParser.Package p : mPackages.values()) {
7272                    if (p.mExtras != null) {
7273                        PackageSetting ps = (PackageSetting) p.mExtras;
7274                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7275                            continue;
7276                        }
7277                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7278                                ps.readUserState(userId), userId);
7279                        if (ai != null) {
7280                            rebaseEnabledOverlays(ai, userId);
7281                            ai.packageName = resolveExternalPackageNameLPr(p);
7282                            list.add(ai);
7283                        }
7284                    }
7285                }
7286            }
7287
7288            return new ParceledListSlice<>(list);
7289        }
7290    }
7291
7292    @Override
7293    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7294        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7295            return null;
7296        }
7297
7298        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7299                "getEphemeralApplications");
7300        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7301                true /* requireFullPermission */, false /* checkShell */,
7302                "getEphemeralApplications");
7303        synchronized (mPackages) {
7304            List<InstantAppInfo> instantApps = mInstantAppRegistry
7305                    .getInstantAppsLPr(userId);
7306            if (instantApps != null) {
7307                return new ParceledListSlice<>(instantApps);
7308            }
7309        }
7310        return null;
7311    }
7312
7313    @Override
7314    public boolean isInstantApp(String packageName, int userId) {
7315        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7316                true /* requireFullPermission */, false /* checkShell */,
7317                "isInstantApp");
7318        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7319            return false;
7320        }
7321
7322        synchronized (mPackages) {
7323            final PackageSetting ps = mSettings.mPackages.get(packageName);
7324            final boolean returnAllowed =
7325                    ps != null
7326                    && (isCallerSameApp(packageName)
7327                            || mContext.checkCallingOrSelfPermission(
7328                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7329                                            == PERMISSION_GRANTED
7330                            || mInstantAppRegistry.isInstantAccessGranted(
7331                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7332            if (returnAllowed) {
7333                return ps.getInstantApp(userId);
7334            }
7335        }
7336        return false;
7337    }
7338
7339    @Override
7340    public byte[] getInstantAppCookie(String packageName, int userId) {
7341        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7342            return null;
7343        }
7344
7345        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7346                true /* requireFullPermission */, false /* checkShell */,
7347                "getInstantAppCookie");
7348        if (!isCallerSameApp(packageName)) {
7349            return null;
7350        }
7351        synchronized (mPackages) {
7352            return mInstantAppRegistry.getInstantAppCookieLPw(
7353                    packageName, userId);
7354        }
7355    }
7356
7357    @Override
7358    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7359        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7360            return true;
7361        }
7362
7363        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7364                true /* requireFullPermission */, true /* checkShell */,
7365                "setInstantAppCookie");
7366        if (!isCallerSameApp(packageName)) {
7367            return false;
7368        }
7369        synchronized (mPackages) {
7370            return mInstantAppRegistry.setInstantAppCookieLPw(
7371                    packageName, cookie, userId);
7372        }
7373    }
7374
7375    @Override
7376    public Bitmap getInstantAppIcon(String packageName, int userId) {
7377        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7378            return null;
7379        }
7380
7381        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7382                "getInstantAppIcon");
7383
7384        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7385                true /* requireFullPermission */, false /* checkShell */,
7386                "getInstantAppIcon");
7387
7388        synchronized (mPackages) {
7389            return mInstantAppRegistry.getInstantAppIconLPw(
7390                    packageName, userId);
7391        }
7392    }
7393
7394    private boolean isCallerSameApp(String packageName) {
7395        PackageParser.Package pkg = mPackages.get(packageName);
7396        return pkg != null
7397                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7398    }
7399
7400    @Override
7401    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7402        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7403    }
7404
7405    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7406        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7407
7408        // reader
7409        synchronized (mPackages) {
7410            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7411            final int userId = UserHandle.getCallingUserId();
7412            while (i.hasNext()) {
7413                final PackageParser.Package p = i.next();
7414                if (p.applicationInfo == null) continue;
7415
7416                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7417                        && !p.applicationInfo.isDirectBootAware();
7418                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7419                        && p.applicationInfo.isDirectBootAware();
7420
7421                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7422                        && (!mSafeMode || isSystemApp(p))
7423                        && (matchesUnaware || matchesAware)) {
7424                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7425                    if (ps != null) {
7426                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7427                                ps.readUserState(userId), userId);
7428                        if (ai != null) {
7429                            rebaseEnabledOverlays(ai, userId);
7430                            finalList.add(ai);
7431                        }
7432                    }
7433                }
7434            }
7435        }
7436
7437        return finalList;
7438    }
7439
7440    @Override
7441    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7442        if (!sUserManager.exists(userId)) return null;
7443        flags = updateFlagsForComponent(flags, userId, name);
7444        // reader
7445        synchronized (mPackages) {
7446            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7447            PackageSetting ps = provider != null
7448                    ? mSettings.mPackages.get(provider.owner.packageName)
7449                    : null;
7450            return ps != null
7451                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7452                    ? PackageParser.generateProviderInfo(provider, flags,
7453                            ps.readUserState(userId), userId)
7454                    : null;
7455        }
7456    }
7457
7458    /**
7459     * @deprecated
7460     */
7461    @Deprecated
7462    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7463        // reader
7464        synchronized (mPackages) {
7465            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7466                    .entrySet().iterator();
7467            final int userId = UserHandle.getCallingUserId();
7468            while (i.hasNext()) {
7469                Map.Entry<String, PackageParser.Provider> entry = i.next();
7470                PackageParser.Provider p = entry.getValue();
7471                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7472
7473                if (ps != null && p.syncable
7474                        && (!mSafeMode || (p.info.applicationInfo.flags
7475                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7476                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7477                            ps.readUserState(userId), userId);
7478                    if (info != null) {
7479                        outNames.add(entry.getKey());
7480                        outInfo.add(info);
7481                    }
7482                }
7483            }
7484        }
7485    }
7486
7487    @Override
7488    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7489            int uid, int flags, String metaDataKey) {
7490        final int userId = processName != null ? UserHandle.getUserId(uid)
7491                : UserHandle.getCallingUserId();
7492        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7493        flags = updateFlagsForComponent(flags, userId, processName);
7494
7495        ArrayList<ProviderInfo> finalList = null;
7496        // reader
7497        synchronized (mPackages) {
7498            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7499            while (i.hasNext()) {
7500                final PackageParser.Provider p = i.next();
7501                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7502                if (ps != null && p.info.authority != null
7503                        && (processName == null
7504                                || (p.info.processName.equals(processName)
7505                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7506                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7507
7508                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7509                    // parameter.
7510                    if (metaDataKey != null
7511                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7512                        continue;
7513                    }
7514
7515                    if (finalList == null) {
7516                        finalList = new ArrayList<ProviderInfo>(3);
7517                    }
7518                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7519                            ps.readUserState(userId), userId);
7520                    if (info != null) {
7521                        finalList.add(info);
7522                    }
7523                }
7524            }
7525        }
7526
7527        if (finalList != null) {
7528            Collections.sort(finalList, mProviderInitOrderSorter);
7529            return new ParceledListSlice<ProviderInfo>(finalList);
7530        }
7531
7532        return ParceledListSlice.emptyList();
7533    }
7534
7535    @Override
7536    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7537        // reader
7538        synchronized (mPackages) {
7539            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7540            return PackageParser.generateInstrumentationInfo(i, flags);
7541        }
7542    }
7543
7544    @Override
7545    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7546            String targetPackage, int flags) {
7547        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7548    }
7549
7550    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7551            int flags) {
7552        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7553
7554        // reader
7555        synchronized (mPackages) {
7556            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7557            while (i.hasNext()) {
7558                final PackageParser.Instrumentation p = i.next();
7559                if (targetPackage == null
7560                        || targetPackage.equals(p.info.targetPackage)) {
7561                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7562                            flags);
7563                    if (ii != null) {
7564                        finalList.add(ii);
7565                    }
7566                }
7567            }
7568        }
7569
7570        return finalList;
7571    }
7572
7573    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7574        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7575        try {
7576            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7577        } finally {
7578            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7579        }
7580    }
7581
7582    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7583        final File[] files = dir.listFiles();
7584        if (ArrayUtils.isEmpty(files)) {
7585            Log.d(TAG, "No files in app dir " + dir);
7586            return;
7587        }
7588
7589        if (DEBUG_PACKAGE_SCANNING) {
7590            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7591                    + " flags=0x" + Integer.toHexString(parseFlags));
7592        }
7593        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7594                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7595
7596        // Submit files for parsing in parallel
7597        int fileCount = 0;
7598        for (File file : files) {
7599            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7600                    && !PackageInstallerService.isStageName(file.getName());
7601            if (!isPackage) {
7602                // Ignore entries which are not packages
7603                continue;
7604            }
7605            parallelPackageParser.submit(file, parseFlags);
7606            fileCount++;
7607        }
7608
7609        // Process results one by one
7610        for (; fileCount > 0; fileCount--) {
7611            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7612            Throwable throwable = parseResult.throwable;
7613            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7614
7615            if (throwable == null) {
7616                // Static shared libraries have synthetic package names
7617                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7618                    renameStaticSharedLibraryPackage(parseResult.pkg);
7619                }
7620                try {
7621                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7622                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7623                                currentTime, null);
7624                    }
7625                } catch (PackageManagerException e) {
7626                    errorCode = e.error;
7627                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7628                }
7629            } else if (throwable instanceof PackageParser.PackageParserException) {
7630                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7631                        throwable;
7632                errorCode = e.error;
7633                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7634            } else {
7635                throw new IllegalStateException("Unexpected exception occurred while parsing "
7636                        + parseResult.scanFile, throwable);
7637            }
7638
7639            // Delete invalid userdata apps
7640            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7641                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7642                logCriticalInfo(Log.WARN,
7643                        "Deleting invalid package at " + parseResult.scanFile);
7644                removeCodePathLI(parseResult.scanFile);
7645            }
7646        }
7647        parallelPackageParser.close();
7648    }
7649
7650    private static File getSettingsProblemFile() {
7651        File dataDir = Environment.getDataDirectory();
7652        File systemDir = new File(dataDir, "system");
7653        File fname = new File(systemDir, "uiderrors.txt");
7654        return fname;
7655    }
7656
7657    static void reportSettingsProblem(int priority, String msg) {
7658        logCriticalInfo(priority, msg);
7659    }
7660
7661    public static void logCriticalInfo(int priority, String msg) {
7662        Slog.println(priority, TAG, msg);
7663        EventLogTags.writePmCriticalInfo(msg);
7664        try {
7665            File fname = getSettingsProblemFile();
7666            FileOutputStream out = new FileOutputStream(fname, true);
7667            PrintWriter pw = new FastPrintWriter(out);
7668            SimpleDateFormat formatter = new SimpleDateFormat();
7669            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7670            pw.println(dateString + ": " + msg);
7671            pw.close();
7672            FileUtils.setPermissions(
7673                    fname.toString(),
7674                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7675                    -1, -1);
7676        } catch (java.io.IOException e) {
7677        }
7678    }
7679
7680    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7681        if (srcFile.isDirectory()) {
7682            final File baseFile = new File(pkg.baseCodePath);
7683            long maxModifiedTime = baseFile.lastModified();
7684            if (pkg.splitCodePaths != null) {
7685                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7686                    final File splitFile = new File(pkg.splitCodePaths[i]);
7687                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7688                }
7689            }
7690            return maxModifiedTime;
7691        }
7692        return srcFile.lastModified();
7693    }
7694
7695    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7696            final int policyFlags) throws PackageManagerException {
7697        // When upgrading from pre-N MR1, verify the package time stamp using the package
7698        // directory and not the APK file.
7699        final long lastModifiedTime = mIsPreNMR1Upgrade
7700                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7701        if (ps != null
7702                && ps.codePath.equals(srcFile)
7703                && ps.timeStamp == lastModifiedTime
7704                && !isCompatSignatureUpdateNeeded(pkg)
7705                && !isRecoverSignatureUpdateNeeded(pkg)) {
7706            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7707            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7708            ArraySet<PublicKey> signingKs;
7709            synchronized (mPackages) {
7710                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7711            }
7712            if (ps.signatures.mSignatures != null
7713                    && ps.signatures.mSignatures.length != 0
7714                    && signingKs != null) {
7715                // Optimization: reuse the existing cached certificates
7716                // if the package appears to be unchanged.
7717                pkg.mSignatures = ps.signatures.mSignatures;
7718                pkg.mSigningKeys = signingKs;
7719                return;
7720            }
7721
7722            Slog.w(TAG, "PackageSetting for " + ps.name
7723                    + " is missing signatures.  Collecting certs again to recover them.");
7724        } else {
7725            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7726        }
7727
7728        try {
7729            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7730            PackageParser.collectCertificates(pkg, policyFlags);
7731        } catch (PackageParserException e) {
7732            throw PackageManagerException.from(e);
7733        } finally {
7734            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7735        }
7736    }
7737
7738    /**
7739     *  Traces a package scan.
7740     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7741     */
7742    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7743            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7744        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7745        try {
7746            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7747        } finally {
7748            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7749        }
7750    }
7751
7752    /**
7753     *  Scans a package and returns the newly parsed package.
7754     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7755     */
7756    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7757            long currentTime, UserHandle user) throws PackageManagerException {
7758        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7759        PackageParser pp = new PackageParser();
7760        pp.setSeparateProcesses(mSeparateProcesses);
7761        pp.setOnlyCoreApps(mOnlyCore);
7762        pp.setDisplayMetrics(mMetrics);
7763        pp.setCallback(mPackageParserCallback);
7764
7765        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7766            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7767        }
7768
7769        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7770        final PackageParser.Package pkg;
7771        try {
7772            pkg = pp.parsePackage(scanFile, parseFlags);
7773        } catch (PackageParserException e) {
7774            throw PackageManagerException.from(e);
7775        } finally {
7776            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7777        }
7778
7779        // Static shared libraries have synthetic package names
7780        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7781            renameStaticSharedLibraryPackage(pkg);
7782        }
7783
7784        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7785    }
7786
7787    /**
7788     *  Scans a package and returns the newly parsed package.
7789     *  @throws PackageManagerException on a parse error.
7790     */
7791    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7792            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7793            throws PackageManagerException {
7794        // If the package has children and this is the first dive in the function
7795        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7796        // packages (parent and children) would be successfully scanned before the
7797        // actual scan since scanning mutates internal state and we want to atomically
7798        // install the package and its children.
7799        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7800            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7801                scanFlags |= SCAN_CHECK_ONLY;
7802            }
7803        } else {
7804            scanFlags &= ~SCAN_CHECK_ONLY;
7805        }
7806
7807        // Scan the parent
7808        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7809                scanFlags, currentTime, user);
7810
7811        // Scan the children
7812        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7813        for (int i = 0; i < childCount; i++) {
7814            PackageParser.Package childPackage = pkg.childPackages.get(i);
7815            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7816                    currentTime, user);
7817        }
7818
7819
7820        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7821            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7822        }
7823
7824        return scannedPkg;
7825    }
7826
7827    /**
7828     *  Scans a package and returns the newly parsed package.
7829     *  @throws PackageManagerException on a parse error.
7830     */
7831    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7832            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7833            throws PackageManagerException {
7834        PackageSetting ps = null;
7835        PackageSetting updatedPkg;
7836        // reader
7837        synchronized (mPackages) {
7838            // Look to see if we already know about this package.
7839            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7840            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7841                // This package has been renamed to its original name.  Let's
7842                // use that.
7843                ps = mSettings.getPackageLPr(oldName);
7844            }
7845            // If there was no original package, see one for the real package name.
7846            if (ps == null) {
7847                ps = mSettings.getPackageLPr(pkg.packageName);
7848            }
7849            // Check to see if this package could be hiding/updating a system
7850            // package.  Must look for it either under the original or real
7851            // package name depending on our state.
7852            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7853            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7854
7855            // If this is a package we don't know about on the system partition, we
7856            // may need to remove disabled child packages on the system partition
7857            // or may need to not add child packages if the parent apk is updated
7858            // on the data partition and no longer defines this child package.
7859            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7860                // If this is a parent package for an updated system app and this system
7861                // app got an OTA update which no longer defines some of the child packages
7862                // we have to prune them from the disabled system packages.
7863                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7864                if (disabledPs != null) {
7865                    final int scannedChildCount = (pkg.childPackages != null)
7866                            ? pkg.childPackages.size() : 0;
7867                    final int disabledChildCount = disabledPs.childPackageNames != null
7868                            ? disabledPs.childPackageNames.size() : 0;
7869                    for (int i = 0; i < disabledChildCount; i++) {
7870                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7871                        boolean disabledPackageAvailable = false;
7872                        for (int j = 0; j < scannedChildCount; j++) {
7873                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7874                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7875                                disabledPackageAvailable = true;
7876                                break;
7877                            }
7878                         }
7879                         if (!disabledPackageAvailable) {
7880                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7881                         }
7882                    }
7883                }
7884            }
7885        }
7886
7887        boolean updatedPkgBetter = false;
7888        // First check if this is a system package that may involve an update
7889        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7890            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7891            // it needs to drop FLAG_PRIVILEGED.
7892            if (locationIsPrivileged(scanFile)) {
7893                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7894            } else {
7895                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7896            }
7897
7898            if (ps != null && !ps.codePath.equals(scanFile)) {
7899                // The path has changed from what was last scanned...  check the
7900                // version of the new path against what we have stored to determine
7901                // what to do.
7902                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7903                if (pkg.mVersionCode <= ps.versionCode) {
7904                    // The system package has been updated and the code path does not match
7905                    // Ignore entry. Skip it.
7906                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7907                            + " ignored: updated version " + ps.versionCode
7908                            + " better than this " + pkg.mVersionCode);
7909                    if (!updatedPkg.codePath.equals(scanFile)) {
7910                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7911                                + ps.name + " changing from " + updatedPkg.codePathString
7912                                + " to " + scanFile);
7913                        updatedPkg.codePath = scanFile;
7914                        updatedPkg.codePathString = scanFile.toString();
7915                        updatedPkg.resourcePath = scanFile;
7916                        updatedPkg.resourcePathString = scanFile.toString();
7917                    }
7918                    updatedPkg.pkg = pkg;
7919                    updatedPkg.versionCode = pkg.mVersionCode;
7920
7921                    // Update the disabled system child packages to point to the package too.
7922                    final int childCount = updatedPkg.childPackageNames != null
7923                            ? updatedPkg.childPackageNames.size() : 0;
7924                    for (int i = 0; i < childCount; i++) {
7925                        String childPackageName = updatedPkg.childPackageNames.get(i);
7926                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7927                                childPackageName);
7928                        if (updatedChildPkg != null) {
7929                            updatedChildPkg.pkg = pkg;
7930                            updatedChildPkg.versionCode = pkg.mVersionCode;
7931                        }
7932                    }
7933
7934                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7935                            + scanFile + " ignored: updated version " + ps.versionCode
7936                            + " better than this " + pkg.mVersionCode);
7937                } else {
7938                    // The current app on the system partition is better than
7939                    // what we have updated to on the data partition; switch
7940                    // back to the system partition version.
7941                    // At this point, its safely assumed that package installation for
7942                    // apps in system partition will go through. If not there won't be a working
7943                    // version of the app
7944                    // writer
7945                    synchronized (mPackages) {
7946                        // Just remove the loaded entries from package lists.
7947                        mPackages.remove(ps.name);
7948                    }
7949
7950                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7951                            + " reverting from " + ps.codePathString
7952                            + ": new version " + pkg.mVersionCode
7953                            + " better than installed " + ps.versionCode);
7954
7955                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7956                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7957                    synchronized (mInstallLock) {
7958                        args.cleanUpResourcesLI();
7959                    }
7960                    synchronized (mPackages) {
7961                        mSettings.enableSystemPackageLPw(ps.name);
7962                    }
7963                    updatedPkgBetter = true;
7964                }
7965            }
7966        }
7967
7968        if (updatedPkg != null) {
7969            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7970            // initially
7971            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7972
7973            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7974            // flag set initially
7975            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7976                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7977            }
7978        }
7979
7980        // Verify certificates against what was last scanned
7981        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7982
7983        /*
7984         * A new system app appeared, but we already had a non-system one of the
7985         * same name installed earlier.
7986         */
7987        boolean shouldHideSystemApp = false;
7988        if (updatedPkg == null && ps != null
7989                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7990            /*
7991             * Check to make sure the signatures match first. If they don't,
7992             * wipe the installed application and its data.
7993             */
7994            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7995                    != PackageManager.SIGNATURE_MATCH) {
7996                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7997                        + " signatures don't match existing userdata copy; removing");
7998                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7999                        "scanPackageInternalLI")) {
8000                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8001                }
8002                ps = null;
8003            } else {
8004                /*
8005                 * If the newly-added system app is an older version than the
8006                 * already installed version, hide it. It will be scanned later
8007                 * and re-added like an update.
8008                 */
8009                if (pkg.mVersionCode <= ps.versionCode) {
8010                    shouldHideSystemApp = true;
8011                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8012                            + " but new version " + pkg.mVersionCode + " better than installed "
8013                            + ps.versionCode + "; hiding system");
8014                } else {
8015                    /*
8016                     * The newly found system app is a newer version that the
8017                     * one previously installed. Simply remove the
8018                     * already-installed application and replace it with our own
8019                     * while keeping the application data.
8020                     */
8021                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8022                            + " reverting from " + ps.codePathString + ": new version "
8023                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8024                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8025                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8026                    synchronized (mInstallLock) {
8027                        args.cleanUpResourcesLI();
8028                    }
8029                }
8030            }
8031        }
8032
8033        // The apk is forward locked (not public) if its code and resources
8034        // are kept in different files. (except for app in either system or
8035        // vendor path).
8036        // TODO grab this value from PackageSettings
8037        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8038            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8039                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8040            }
8041        }
8042
8043        // TODO: extend to support forward-locked splits
8044        String resourcePath = null;
8045        String baseResourcePath = null;
8046        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8047            if (ps != null && ps.resourcePathString != null) {
8048                resourcePath = ps.resourcePathString;
8049                baseResourcePath = ps.resourcePathString;
8050            } else {
8051                // Should not happen at all. Just log an error.
8052                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8053            }
8054        } else {
8055            resourcePath = pkg.codePath;
8056            baseResourcePath = pkg.baseCodePath;
8057        }
8058
8059        // Set application objects path explicitly.
8060        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8061        pkg.setApplicationInfoCodePath(pkg.codePath);
8062        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8063        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8064        pkg.setApplicationInfoResourcePath(resourcePath);
8065        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8066        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8067
8068        final int userId = ((user == null) ? 0 : user.getIdentifier());
8069        if (ps != null && ps.getInstantApp(userId)) {
8070            scanFlags |= SCAN_AS_INSTANT_APP;
8071        }
8072
8073        // Note that we invoke the following method only if we are about to unpack an application
8074        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8075                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8076
8077        /*
8078         * If the system app should be overridden by a previously installed
8079         * data, hide the system app now and let the /data/app scan pick it up
8080         * again.
8081         */
8082        if (shouldHideSystemApp) {
8083            synchronized (mPackages) {
8084                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8085            }
8086        }
8087
8088        return scannedPkg;
8089    }
8090
8091    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8092        // Derive the new package synthetic package name
8093        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8094                + pkg.staticSharedLibVersion);
8095    }
8096
8097    private static String fixProcessName(String defProcessName,
8098            String processName) {
8099        if (processName == null) {
8100            return defProcessName;
8101        }
8102        return processName;
8103    }
8104
8105    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8106            throws PackageManagerException {
8107        if (pkgSetting.signatures.mSignatures != null) {
8108            // Already existing package. Make sure signatures match
8109            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8110                    == PackageManager.SIGNATURE_MATCH;
8111            if (!match) {
8112                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8113                        == PackageManager.SIGNATURE_MATCH;
8114            }
8115            if (!match) {
8116                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8117                        == PackageManager.SIGNATURE_MATCH;
8118            }
8119            if (!match) {
8120                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8121                        + pkg.packageName + " signatures do not match the "
8122                        + "previously installed version; ignoring!");
8123            }
8124        }
8125
8126        // Check for shared user signatures
8127        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8128            // Already existing package. Make sure signatures match
8129            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8130                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8131            if (!match) {
8132                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8133                        == PackageManager.SIGNATURE_MATCH;
8134            }
8135            if (!match) {
8136                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8137                        == PackageManager.SIGNATURE_MATCH;
8138            }
8139            if (!match) {
8140                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8141                        "Package " + pkg.packageName
8142                        + " has no signatures that match those in shared user "
8143                        + pkgSetting.sharedUser.name + "; ignoring!");
8144            }
8145        }
8146    }
8147
8148    /**
8149     * Enforces that only the system UID or root's UID can call a method exposed
8150     * via Binder.
8151     *
8152     * @param message used as message if SecurityException is thrown
8153     * @throws SecurityException if the caller is not system or root
8154     */
8155    private static final void enforceSystemOrRoot(String message) {
8156        final int uid = Binder.getCallingUid();
8157        if (uid != Process.SYSTEM_UID && uid != 0) {
8158            throw new SecurityException(message);
8159        }
8160    }
8161
8162    @Override
8163    public void performFstrimIfNeeded() {
8164        enforceSystemOrRoot("Only the system can request fstrim");
8165
8166        // Before everything else, see whether we need to fstrim.
8167        try {
8168            IStorageManager sm = PackageHelper.getStorageManager();
8169            if (sm != null) {
8170                boolean doTrim = false;
8171                final long interval = android.provider.Settings.Global.getLong(
8172                        mContext.getContentResolver(),
8173                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8174                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8175                if (interval > 0) {
8176                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8177                    if (timeSinceLast > interval) {
8178                        doTrim = true;
8179                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8180                                + "; running immediately");
8181                    }
8182                }
8183                if (doTrim) {
8184                    final boolean dexOptDialogShown;
8185                    synchronized (mPackages) {
8186                        dexOptDialogShown = mDexOptDialogShown;
8187                    }
8188                    if (!isFirstBoot() && dexOptDialogShown) {
8189                        try {
8190                            ActivityManager.getService().showBootMessage(
8191                                    mContext.getResources().getString(
8192                                            R.string.android_upgrading_fstrim), true);
8193                        } catch (RemoteException e) {
8194                        }
8195                    }
8196                    sm.runMaintenance();
8197                }
8198            } else {
8199                Slog.e(TAG, "storageManager service unavailable!");
8200            }
8201        } catch (RemoteException e) {
8202            // Can't happen; StorageManagerService is local
8203        }
8204    }
8205
8206    @Override
8207    public void updatePackagesIfNeeded() {
8208        enforceSystemOrRoot("Only the system can request package update");
8209
8210        // We need to re-extract after an OTA.
8211        boolean causeUpgrade = isUpgrade();
8212
8213        // First boot or factory reset.
8214        // Note: we also handle devices that are upgrading to N right now as if it is their
8215        //       first boot, as they do not have profile data.
8216        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8217
8218        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8219        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8220
8221        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8222            return;
8223        }
8224
8225        List<PackageParser.Package> pkgs;
8226        synchronized (mPackages) {
8227            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8228        }
8229
8230        final long startTime = System.nanoTime();
8231        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8232                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8233
8234        final int elapsedTimeSeconds =
8235                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8236
8237        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8238        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8239        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8240        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8241        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8242    }
8243
8244    /**
8245     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8246     * containing statistics about the invocation. The array consists of three elements,
8247     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8248     * and {@code numberOfPackagesFailed}.
8249     */
8250    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8251            String compilerFilter) {
8252
8253        int numberOfPackagesVisited = 0;
8254        int numberOfPackagesOptimized = 0;
8255        int numberOfPackagesSkipped = 0;
8256        int numberOfPackagesFailed = 0;
8257        final int numberOfPackagesToDexopt = pkgs.size();
8258
8259        for (PackageParser.Package pkg : pkgs) {
8260            numberOfPackagesVisited++;
8261
8262            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8263                if (DEBUG_DEXOPT) {
8264                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8265                }
8266                numberOfPackagesSkipped++;
8267                continue;
8268            }
8269
8270            if (DEBUG_DEXOPT) {
8271                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8272                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8273            }
8274
8275            if (showDialog) {
8276                try {
8277                    ActivityManager.getService().showBootMessage(
8278                            mContext.getResources().getString(R.string.android_upgrading_apk,
8279                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8280                } catch (RemoteException e) {
8281                }
8282                synchronized (mPackages) {
8283                    mDexOptDialogShown = true;
8284                }
8285            }
8286
8287            // If the OTA updates a system app which was previously preopted to a non-preopted state
8288            // the app might end up being verified at runtime. That's because by default the apps
8289            // are verify-profile but for preopted apps there's no profile.
8290            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8291            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8292            // filter (by default interpret-only).
8293            // Note that at this stage unused apps are already filtered.
8294            if (isSystemApp(pkg) &&
8295                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8296                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8297                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8298            }
8299
8300            // checkProfiles is false to avoid merging profiles during boot which
8301            // might interfere with background compilation (b/28612421).
8302            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8303            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8304            // trade-off worth doing to save boot time work.
8305            int dexOptStatus = performDexOptTraced(pkg.packageName,
8306                    false /* checkProfiles */,
8307                    compilerFilter,
8308                    false /* force */);
8309            switch (dexOptStatus) {
8310                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8311                    numberOfPackagesOptimized++;
8312                    break;
8313                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8314                    numberOfPackagesSkipped++;
8315                    break;
8316                case PackageDexOptimizer.DEX_OPT_FAILED:
8317                    numberOfPackagesFailed++;
8318                    break;
8319                default:
8320                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8321                    break;
8322            }
8323        }
8324
8325        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8326                numberOfPackagesFailed };
8327    }
8328
8329    @Override
8330    public void notifyPackageUse(String packageName, int reason) {
8331        synchronized (mPackages) {
8332            PackageParser.Package p = mPackages.get(packageName);
8333            if (p == null) {
8334                return;
8335            }
8336            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8337        }
8338    }
8339
8340    @Override
8341    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8342        int userId = UserHandle.getCallingUserId();
8343        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8344        if (ai == null) {
8345            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8346                + loadingPackageName + ", user=" + userId);
8347            return;
8348        }
8349        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8350    }
8351
8352    // TODO: this is not used nor needed. Delete it.
8353    @Override
8354    public boolean performDexOptIfNeeded(String packageName) {
8355        int dexOptStatus = performDexOptTraced(packageName,
8356                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8357        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8358    }
8359
8360    @Override
8361    public boolean performDexOpt(String packageName,
8362            boolean checkProfiles, int compileReason, boolean force) {
8363        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8364                getCompilerFilterForReason(compileReason), force);
8365        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8366    }
8367
8368    @Override
8369    public boolean performDexOptMode(String packageName,
8370            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8371        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8372                targetCompilerFilter, force);
8373        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8374    }
8375
8376    private int performDexOptTraced(String packageName,
8377                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8378        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8379        try {
8380            return performDexOptInternal(packageName, checkProfiles,
8381                    targetCompilerFilter, force);
8382        } finally {
8383            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8384        }
8385    }
8386
8387    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8388    // if the package can now be considered up to date for the given filter.
8389    private int performDexOptInternal(String packageName,
8390                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8391        PackageParser.Package p;
8392        synchronized (mPackages) {
8393            p = mPackages.get(packageName);
8394            if (p == null) {
8395                // Package could not be found. Report failure.
8396                return PackageDexOptimizer.DEX_OPT_FAILED;
8397            }
8398            mPackageUsage.maybeWriteAsync(mPackages);
8399            mCompilerStats.maybeWriteAsync();
8400        }
8401        long callingId = Binder.clearCallingIdentity();
8402        try {
8403            synchronized (mInstallLock) {
8404                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8405                        targetCompilerFilter, force);
8406            }
8407        } finally {
8408            Binder.restoreCallingIdentity(callingId);
8409        }
8410    }
8411
8412    public ArraySet<String> getOptimizablePackages() {
8413        ArraySet<String> pkgs = new ArraySet<String>();
8414        synchronized (mPackages) {
8415            for (PackageParser.Package p : mPackages.values()) {
8416                if (PackageDexOptimizer.canOptimizePackage(p)) {
8417                    pkgs.add(p.packageName);
8418                }
8419            }
8420        }
8421        return pkgs;
8422    }
8423
8424    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8425            boolean checkProfiles, String targetCompilerFilter,
8426            boolean force) {
8427        // Select the dex optimizer based on the force parameter.
8428        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8429        //       allocate an object here.
8430        PackageDexOptimizer pdo = force
8431                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8432                : mPackageDexOptimizer;
8433
8434        // Optimize all dependencies first. Note: we ignore the return value and march on
8435        // on errors.
8436        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8437        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8438        if (!deps.isEmpty()) {
8439            for (PackageParser.Package depPackage : deps) {
8440                // TODO: Analyze and investigate if we (should) profile libraries.
8441                // Currently this will do a full compilation of the library by default.
8442                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8443                        false /* checkProfiles */,
8444                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8445                        getOrCreateCompilerPackageStats(depPackage),
8446                        mDexManager.isUsedByOtherApps(p.packageName));
8447            }
8448        }
8449        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8450                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8451                mDexManager.isUsedByOtherApps(p.packageName));
8452    }
8453
8454    // Performs dexopt on the used secondary dex files belonging to the given package.
8455    // Returns true if all dex files were process successfully (which could mean either dexopt or
8456    // skip). Returns false if any of the files caused errors.
8457    @Override
8458    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8459            boolean force) {
8460        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8461    }
8462
8463    /**
8464     * Reconcile the information we have about the secondary dex files belonging to
8465     * {@code packagName} and the actual dex files. For all dex files that were
8466     * deleted, update the internal records and delete the generated oat files.
8467     */
8468    @Override
8469    public void reconcileSecondaryDexFiles(String packageName) {
8470        mDexManager.reconcileSecondaryDexFiles(packageName);
8471    }
8472
8473    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8474    // a reference there.
8475    /*package*/ DexManager getDexManager() {
8476        return mDexManager;
8477    }
8478
8479    /**
8480     * Execute the background dexopt job immediately.
8481     */
8482    @Override
8483    public boolean runBackgroundDexoptJob() {
8484        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8485    }
8486
8487    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8488        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8489                || p.usesStaticLibraries != null) {
8490            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8491            Set<String> collectedNames = new HashSet<>();
8492            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8493
8494            retValue.remove(p);
8495
8496            return retValue;
8497        } else {
8498            return Collections.emptyList();
8499        }
8500    }
8501
8502    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8503            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8504        if (!collectedNames.contains(p.packageName)) {
8505            collectedNames.add(p.packageName);
8506            collected.add(p);
8507
8508            if (p.usesLibraries != null) {
8509                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8510                        null, collected, collectedNames);
8511            }
8512            if (p.usesOptionalLibraries != null) {
8513                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8514                        null, collected, collectedNames);
8515            }
8516            if (p.usesStaticLibraries != null) {
8517                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8518                        p.usesStaticLibrariesVersions, collected, collectedNames);
8519            }
8520        }
8521    }
8522
8523    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8524            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8525        final int libNameCount = libs.size();
8526        for (int i = 0; i < libNameCount; i++) {
8527            String libName = libs.get(i);
8528            int version = (versions != null && versions.length == libNameCount)
8529                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8530            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8531            if (libPkg != null) {
8532                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8533            }
8534        }
8535    }
8536
8537    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8538        synchronized (mPackages) {
8539            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8540            if (libEntry != null) {
8541                return mPackages.get(libEntry.apk);
8542            }
8543            return null;
8544        }
8545    }
8546
8547    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8548        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8549        if (versionedLib == null) {
8550            return null;
8551        }
8552        return versionedLib.get(version);
8553    }
8554
8555    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8556        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8557                pkg.staticSharedLibName);
8558        if (versionedLib == null) {
8559            return null;
8560        }
8561        int previousLibVersion = -1;
8562        final int versionCount = versionedLib.size();
8563        for (int i = 0; i < versionCount; i++) {
8564            final int libVersion = versionedLib.keyAt(i);
8565            if (libVersion < pkg.staticSharedLibVersion) {
8566                previousLibVersion = Math.max(previousLibVersion, libVersion);
8567            }
8568        }
8569        if (previousLibVersion >= 0) {
8570            return versionedLib.get(previousLibVersion);
8571        }
8572        return null;
8573    }
8574
8575    public void shutdown() {
8576        mPackageUsage.writeNow(mPackages);
8577        mCompilerStats.writeNow();
8578    }
8579
8580    @Override
8581    public void dumpProfiles(String packageName) {
8582        PackageParser.Package pkg;
8583        synchronized (mPackages) {
8584            pkg = mPackages.get(packageName);
8585            if (pkg == null) {
8586                throw new IllegalArgumentException("Unknown package: " + packageName);
8587            }
8588        }
8589        /* Only the shell, root, or the app user should be able to dump profiles. */
8590        int callingUid = Binder.getCallingUid();
8591        if (callingUid != Process.SHELL_UID &&
8592            callingUid != Process.ROOT_UID &&
8593            callingUid != pkg.applicationInfo.uid) {
8594            throw new SecurityException("dumpProfiles");
8595        }
8596
8597        synchronized (mInstallLock) {
8598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8599            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8600            try {
8601                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8602                String codePaths = TextUtils.join(";", allCodePaths);
8603                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8604            } catch (InstallerException e) {
8605                Slog.w(TAG, "Failed to dump profiles", e);
8606            }
8607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8608        }
8609    }
8610
8611    @Override
8612    public void forceDexOpt(String packageName) {
8613        enforceSystemOrRoot("forceDexOpt");
8614
8615        PackageParser.Package pkg;
8616        synchronized (mPackages) {
8617            pkg = mPackages.get(packageName);
8618            if (pkg == null) {
8619                throw new IllegalArgumentException("Unknown package: " + packageName);
8620            }
8621        }
8622
8623        synchronized (mInstallLock) {
8624            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8625
8626            // Whoever is calling forceDexOpt wants a fully compiled package.
8627            // Don't use profiles since that may cause compilation to be skipped.
8628            final int res = performDexOptInternalWithDependenciesLI(pkg,
8629                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8630                    true /* force */);
8631
8632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8633            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8634                throw new IllegalStateException("Failed to dexopt: " + res);
8635            }
8636        }
8637    }
8638
8639    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8640        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8641            Slog.w(TAG, "Unable to update from " + oldPkg.name
8642                    + " to " + newPkg.packageName
8643                    + ": old package not in system partition");
8644            return false;
8645        } else if (mPackages.get(oldPkg.name) != null) {
8646            Slog.w(TAG, "Unable to update from " + oldPkg.name
8647                    + " to " + newPkg.packageName
8648                    + ": old package still exists");
8649            return false;
8650        }
8651        return true;
8652    }
8653
8654    void removeCodePathLI(File codePath) {
8655        if (codePath.isDirectory()) {
8656            try {
8657                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8658            } catch (InstallerException e) {
8659                Slog.w(TAG, "Failed to remove code path", e);
8660            }
8661        } else {
8662            codePath.delete();
8663        }
8664    }
8665
8666    private int[] resolveUserIds(int userId) {
8667        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8668    }
8669
8670    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8671        if (pkg == null) {
8672            Slog.wtf(TAG, "Package was null!", new Throwable());
8673            return;
8674        }
8675        clearAppDataLeafLIF(pkg, userId, flags);
8676        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8677        for (int i = 0; i < childCount; i++) {
8678            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8679        }
8680    }
8681
8682    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8683        final PackageSetting ps;
8684        synchronized (mPackages) {
8685            ps = mSettings.mPackages.get(pkg.packageName);
8686        }
8687        for (int realUserId : resolveUserIds(userId)) {
8688            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8689            try {
8690                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8691                        ceDataInode);
8692            } catch (InstallerException e) {
8693                Slog.w(TAG, String.valueOf(e));
8694            }
8695        }
8696    }
8697
8698    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8699        if (pkg == null) {
8700            Slog.wtf(TAG, "Package was null!", new Throwable());
8701            return;
8702        }
8703        destroyAppDataLeafLIF(pkg, userId, flags);
8704        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8705        for (int i = 0; i < childCount; i++) {
8706            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8707        }
8708    }
8709
8710    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8711        final PackageSetting ps;
8712        synchronized (mPackages) {
8713            ps = mSettings.mPackages.get(pkg.packageName);
8714        }
8715        for (int realUserId : resolveUserIds(userId)) {
8716            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8717            try {
8718                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8719                        ceDataInode);
8720            } catch (InstallerException e) {
8721                Slog.w(TAG, String.valueOf(e));
8722            }
8723            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8724        }
8725    }
8726
8727    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8728        if (pkg == null) {
8729            Slog.wtf(TAG, "Package was null!", new Throwable());
8730            return;
8731        }
8732        destroyAppProfilesLeafLIF(pkg);
8733        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8734        for (int i = 0; i < childCount; i++) {
8735            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8736        }
8737    }
8738
8739    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8740        try {
8741            mInstaller.destroyAppProfiles(pkg.packageName);
8742        } catch (InstallerException e) {
8743            Slog.w(TAG, String.valueOf(e));
8744        }
8745    }
8746
8747    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8748        if (pkg == null) {
8749            Slog.wtf(TAG, "Package was null!", new Throwable());
8750            return;
8751        }
8752        clearAppProfilesLeafLIF(pkg);
8753        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8754        for (int i = 0; i < childCount; i++) {
8755            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8756        }
8757    }
8758
8759    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8760        try {
8761            mInstaller.clearAppProfiles(pkg.packageName);
8762        } catch (InstallerException e) {
8763            Slog.w(TAG, String.valueOf(e));
8764        }
8765    }
8766
8767    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8768            long lastUpdateTime) {
8769        // Set parent install/update time
8770        PackageSetting ps = (PackageSetting) pkg.mExtras;
8771        if (ps != null) {
8772            ps.firstInstallTime = firstInstallTime;
8773            ps.lastUpdateTime = lastUpdateTime;
8774        }
8775        // Set children install/update time
8776        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8777        for (int i = 0; i < childCount; i++) {
8778            PackageParser.Package childPkg = pkg.childPackages.get(i);
8779            ps = (PackageSetting) childPkg.mExtras;
8780            if (ps != null) {
8781                ps.firstInstallTime = firstInstallTime;
8782                ps.lastUpdateTime = lastUpdateTime;
8783            }
8784        }
8785    }
8786
8787    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8788            PackageParser.Package changingLib) {
8789        if (file.path != null) {
8790            usesLibraryFiles.add(file.path);
8791            return;
8792        }
8793        PackageParser.Package p = mPackages.get(file.apk);
8794        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8795            // If we are doing this while in the middle of updating a library apk,
8796            // then we need to make sure to use that new apk for determining the
8797            // dependencies here.  (We haven't yet finished committing the new apk
8798            // to the package manager state.)
8799            if (p == null || p.packageName.equals(changingLib.packageName)) {
8800                p = changingLib;
8801            }
8802        }
8803        if (p != null) {
8804            usesLibraryFiles.addAll(p.getAllCodePaths());
8805        }
8806    }
8807
8808    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8809            PackageParser.Package changingLib) throws PackageManagerException {
8810        if (pkg == null) {
8811            return;
8812        }
8813        ArraySet<String> usesLibraryFiles = null;
8814        if (pkg.usesLibraries != null) {
8815            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8816                    null, null, pkg.packageName, changingLib, true, null);
8817        }
8818        if (pkg.usesStaticLibraries != null) {
8819            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8820                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8821                    pkg.packageName, changingLib, true, usesLibraryFiles);
8822        }
8823        if (pkg.usesOptionalLibraries != null) {
8824            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8825                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8826        }
8827        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8828            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8829        } else {
8830            pkg.usesLibraryFiles = null;
8831        }
8832    }
8833
8834    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8835            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8836            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8837            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8838            throws PackageManagerException {
8839        final int libCount = requestedLibraries.size();
8840        for (int i = 0; i < libCount; i++) {
8841            final String libName = requestedLibraries.get(i);
8842            final int libVersion = requiredVersions != null ? requiredVersions[i]
8843                    : SharedLibraryInfo.VERSION_UNDEFINED;
8844            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8845            if (libEntry == null) {
8846                if (required) {
8847                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8848                            "Package " + packageName + " requires unavailable shared library "
8849                                    + libName + "; failing!");
8850                } else {
8851                    Slog.w(TAG, "Package " + packageName
8852                            + " desires unavailable shared library "
8853                            + libName + "; ignoring!");
8854                }
8855            } else {
8856                if (requiredVersions != null && requiredCertDigests != null) {
8857                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8858                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8859                            "Package " + packageName + " requires unavailable static shared"
8860                                    + " library " + libName + " version "
8861                                    + libEntry.info.getVersion() + "; failing!");
8862                    }
8863
8864                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8865                    if (libPkg == null) {
8866                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8867                                "Package " + packageName + " requires unavailable static shared"
8868                                        + " library; failing!");
8869                    }
8870
8871                    String expectedCertDigest = requiredCertDigests[i];
8872                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8873                                libPkg.mSignatures[0]);
8874                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8875                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8876                                "Package " + packageName + " requires differently signed" +
8877                                        " static shared library; failing!");
8878                    }
8879                }
8880
8881                if (outUsedLibraries == null) {
8882                    outUsedLibraries = new ArraySet<>();
8883                }
8884                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8885            }
8886        }
8887        return outUsedLibraries;
8888    }
8889
8890    private static boolean hasString(List<String> list, List<String> which) {
8891        if (list == null) {
8892            return false;
8893        }
8894        for (int i=list.size()-1; i>=0; i--) {
8895            for (int j=which.size()-1; j>=0; j--) {
8896                if (which.get(j).equals(list.get(i))) {
8897                    return true;
8898                }
8899            }
8900        }
8901        return false;
8902    }
8903
8904    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8905            PackageParser.Package changingPkg) {
8906        ArrayList<PackageParser.Package> res = null;
8907        for (PackageParser.Package pkg : mPackages.values()) {
8908            if (changingPkg != null
8909                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8910                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8911                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8912                            changingPkg.staticSharedLibName)) {
8913                return null;
8914            }
8915            if (res == null) {
8916                res = new ArrayList<>();
8917            }
8918            res.add(pkg);
8919            try {
8920                updateSharedLibrariesLPr(pkg, changingPkg);
8921            } catch (PackageManagerException e) {
8922                // If a system app update or an app and a required lib missing we
8923                // delete the package and for updated system apps keep the data as
8924                // it is better for the user to reinstall than to be in an limbo
8925                // state. Also libs disappearing under an app should never happen
8926                // - just in case.
8927                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8928                    final int flags = pkg.isUpdatedSystemApp()
8929                            ? PackageManager.DELETE_KEEP_DATA : 0;
8930                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8931                            flags , null, true, null);
8932                }
8933                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8934            }
8935        }
8936        return res;
8937    }
8938
8939    /**
8940     * Derive the value of the {@code cpuAbiOverride} based on the provided
8941     * value and an optional stored value from the package settings.
8942     */
8943    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8944        String cpuAbiOverride = null;
8945
8946        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8947            cpuAbiOverride = null;
8948        } else if (abiOverride != null) {
8949            cpuAbiOverride = abiOverride;
8950        } else if (settings != null) {
8951            cpuAbiOverride = settings.cpuAbiOverrideString;
8952        }
8953
8954        return cpuAbiOverride;
8955    }
8956
8957    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8958            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8959                    throws PackageManagerException {
8960        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8961        // If the package has children and this is the first dive in the function
8962        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8963        // whether all packages (parent and children) would be successfully scanned
8964        // before the actual scan since scanning mutates internal state and we want
8965        // to atomically install the package and its children.
8966        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8967            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8968                scanFlags |= SCAN_CHECK_ONLY;
8969            }
8970        } else {
8971            scanFlags &= ~SCAN_CHECK_ONLY;
8972        }
8973
8974        final PackageParser.Package scannedPkg;
8975        try {
8976            // Scan the parent
8977            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8978            // Scan the children
8979            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8980            for (int i = 0; i < childCount; i++) {
8981                PackageParser.Package childPkg = pkg.childPackages.get(i);
8982                scanPackageLI(childPkg, policyFlags,
8983                        scanFlags, currentTime, user);
8984            }
8985        } finally {
8986            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8987        }
8988
8989        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8990            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8991        }
8992
8993        return scannedPkg;
8994    }
8995
8996    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8997            int scanFlags, long currentTime, @Nullable UserHandle user)
8998                    throws PackageManagerException {
8999        boolean success = false;
9000        try {
9001            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9002                    currentTime, user);
9003            success = true;
9004            return res;
9005        } finally {
9006            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9007                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9008                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9009                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9010                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9011            }
9012        }
9013    }
9014
9015    /**
9016     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9017     */
9018    private static boolean apkHasCode(String fileName) {
9019        StrictJarFile jarFile = null;
9020        try {
9021            jarFile = new StrictJarFile(fileName,
9022                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9023            return jarFile.findEntry("classes.dex") != null;
9024        } catch (IOException ignore) {
9025        } finally {
9026            try {
9027                if (jarFile != null) {
9028                    jarFile.close();
9029                }
9030            } catch (IOException ignore) {}
9031        }
9032        return false;
9033    }
9034
9035    /**
9036     * Enforces code policy for the package. This ensures that if an APK has
9037     * declared hasCode="true" in its manifest that the APK actually contains
9038     * code.
9039     *
9040     * @throws PackageManagerException If bytecode could not be found when it should exist
9041     */
9042    private static void assertCodePolicy(PackageParser.Package pkg)
9043            throws PackageManagerException {
9044        final boolean shouldHaveCode =
9045                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9046        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9047            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9048                    "Package " + pkg.baseCodePath + " code is missing");
9049        }
9050
9051        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9052            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9053                final boolean splitShouldHaveCode =
9054                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9055                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9056                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9057                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9058                }
9059            }
9060        }
9061    }
9062
9063    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9064            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9065                    throws PackageManagerException {
9066        if (DEBUG_PACKAGE_SCANNING) {
9067            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9068                Log.d(TAG, "Scanning package " + pkg.packageName);
9069        }
9070
9071        applyPolicy(pkg, policyFlags);
9072
9073        assertPackageIsValid(pkg, policyFlags, scanFlags);
9074
9075        // Initialize package source and resource directories
9076        final File scanFile = new File(pkg.codePath);
9077        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9078        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9079
9080        SharedUserSetting suid = null;
9081        PackageSetting pkgSetting = null;
9082
9083        // Getting the package setting may have a side-effect, so if we
9084        // are only checking if scan would succeed, stash a copy of the
9085        // old setting to restore at the end.
9086        PackageSetting nonMutatedPs = null;
9087
9088        // We keep references to the derived CPU Abis from settings in oder to reuse
9089        // them in the case where we're not upgrading or booting for the first time.
9090        String primaryCpuAbiFromSettings = null;
9091        String secondaryCpuAbiFromSettings = null;
9092
9093        // writer
9094        synchronized (mPackages) {
9095            if (pkg.mSharedUserId != null) {
9096                // SIDE EFFECTS; may potentially allocate a new shared user
9097                suid = mSettings.getSharedUserLPw(
9098                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9099                if (DEBUG_PACKAGE_SCANNING) {
9100                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9101                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9102                                + "): packages=" + suid.packages);
9103                }
9104            }
9105
9106            // Check if we are renaming from an original package name.
9107            PackageSetting origPackage = null;
9108            String realName = null;
9109            if (pkg.mOriginalPackages != null) {
9110                // This package may need to be renamed to a previously
9111                // installed name.  Let's check on that...
9112                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9113                if (pkg.mOriginalPackages.contains(renamed)) {
9114                    // This package had originally been installed as the
9115                    // original name, and we have already taken care of
9116                    // transitioning to the new one.  Just update the new
9117                    // one to continue using the old name.
9118                    realName = pkg.mRealPackage;
9119                    if (!pkg.packageName.equals(renamed)) {
9120                        // Callers into this function may have already taken
9121                        // care of renaming the package; only do it here if
9122                        // it is not already done.
9123                        pkg.setPackageName(renamed);
9124                    }
9125                } else {
9126                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9127                        if ((origPackage = mSettings.getPackageLPr(
9128                                pkg.mOriginalPackages.get(i))) != null) {
9129                            // We do have the package already installed under its
9130                            // original name...  should we use it?
9131                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9132                                // New package is not compatible with original.
9133                                origPackage = null;
9134                                continue;
9135                            } else if (origPackage.sharedUser != null) {
9136                                // Make sure uid is compatible between packages.
9137                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9138                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9139                                            + " to " + pkg.packageName + ": old uid "
9140                                            + origPackage.sharedUser.name
9141                                            + " differs from " + pkg.mSharedUserId);
9142                                    origPackage = null;
9143                                    continue;
9144                                }
9145                                // TODO: Add case when shared user id is added [b/28144775]
9146                            } else {
9147                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9148                                        + pkg.packageName + " to old name " + origPackage.name);
9149                            }
9150                            break;
9151                        }
9152                    }
9153                }
9154            }
9155
9156            if (mTransferedPackages.contains(pkg.packageName)) {
9157                Slog.w(TAG, "Package " + pkg.packageName
9158                        + " was transferred to another, but its .apk remains");
9159            }
9160
9161            // See comments in nonMutatedPs declaration
9162            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9163                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9164                if (foundPs != null) {
9165                    nonMutatedPs = new PackageSetting(foundPs);
9166                }
9167            }
9168
9169            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9170                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9171                if (foundPs != null) {
9172                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9173                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9174                }
9175            }
9176
9177            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9178            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9179                PackageManagerService.reportSettingsProblem(Log.WARN,
9180                        "Package " + pkg.packageName + " shared user changed from "
9181                                + (pkgSetting.sharedUser != null
9182                                        ? pkgSetting.sharedUser.name : "<nothing>")
9183                                + " to "
9184                                + (suid != null ? suid.name : "<nothing>")
9185                                + "; replacing with new");
9186                pkgSetting = null;
9187            }
9188            final PackageSetting oldPkgSetting =
9189                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9190            final PackageSetting disabledPkgSetting =
9191                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9192
9193            String[] usesStaticLibraries = null;
9194            if (pkg.usesStaticLibraries != null) {
9195                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9196                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9197            }
9198
9199            if (pkgSetting == null) {
9200                final String parentPackageName = (pkg.parentPackage != null)
9201                        ? pkg.parentPackage.packageName : null;
9202                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9203                // REMOVE SharedUserSetting from method; update in a separate call
9204                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9205                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9206                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9207                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9208                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9209                        true /*allowInstall*/, instantApp, parentPackageName,
9210                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9211                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9212                // SIDE EFFECTS; updates system state; move elsewhere
9213                if (origPackage != null) {
9214                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9215                }
9216                mSettings.addUserToSettingLPw(pkgSetting);
9217            } else {
9218                // REMOVE SharedUserSetting from method; update in a separate call.
9219                //
9220                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9221                // secondaryCpuAbi are not known at this point so we always update them
9222                // to null here, only to reset them at a later point.
9223                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9224                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9225                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9226                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9227                        UserManagerService.getInstance(), usesStaticLibraries,
9228                        pkg.usesStaticLibrariesVersions);
9229            }
9230            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9231            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9232
9233            // SIDE EFFECTS; modifies system state; move elsewhere
9234            if (pkgSetting.origPackage != null) {
9235                // If we are first transitioning from an original package,
9236                // fix up the new package's name now.  We need to do this after
9237                // looking up the package under its new name, so getPackageLP
9238                // can take care of fiddling things correctly.
9239                pkg.setPackageName(origPackage.name);
9240
9241                // File a report about this.
9242                String msg = "New package " + pkgSetting.realName
9243                        + " renamed to replace old package " + pkgSetting.name;
9244                reportSettingsProblem(Log.WARN, msg);
9245
9246                // Make a note of it.
9247                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9248                    mTransferedPackages.add(origPackage.name);
9249                }
9250
9251                // No longer need to retain this.
9252                pkgSetting.origPackage = null;
9253            }
9254
9255            // SIDE EFFECTS; modifies system state; move elsewhere
9256            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9257                // Make a note of it.
9258                mTransferedPackages.add(pkg.packageName);
9259            }
9260
9261            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9262                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9263            }
9264
9265            if ((scanFlags & SCAN_BOOTING) == 0
9266                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9267                // Check all shared libraries and map to their actual file path.
9268                // We only do this here for apps not on a system dir, because those
9269                // are the only ones that can fail an install due to this.  We
9270                // will take care of the system apps by updating all of their
9271                // library paths after the scan is done. Also during the initial
9272                // scan don't update any libs as we do this wholesale after all
9273                // apps are scanned to avoid dependency based scanning.
9274                updateSharedLibrariesLPr(pkg, null);
9275            }
9276
9277            if (mFoundPolicyFile) {
9278                SELinuxMMAC.assignSeInfoValue(pkg);
9279            }
9280            pkg.applicationInfo.uid = pkgSetting.appId;
9281            pkg.mExtras = pkgSetting;
9282
9283
9284            // Static shared libs have same package with different versions where
9285            // we internally use a synthetic package name to allow multiple versions
9286            // of the same package, therefore we need to compare signatures against
9287            // the package setting for the latest library version.
9288            PackageSetting signatureCheckPs = pkgSetting;
9289            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9290                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9291                if (libraryEntry != null) {
9292                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9293                }
9294            }
9295
9296            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9297                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9298                    // We just determined the app is signed correctly, so bring
9299                    // over the latest parsed certs.
9300                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9301                } else {
9302                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9303                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9304                                "Package " + pkg.packageName + " upgrade keys do not match the "
9305                                + "previously installed version");
9306                    } else {
9307                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9308                        String msg = "System package " + pkg.packageName
9309                                + " signature changed; retaining data.";
9310                        reportSettingsProblem(Log.WARN, msg);
9311                    }
9312                }
9313            } else {
9314                try {
9315                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9316                    verifySignaturesLP(signatureCheckPs, pkg);
9317                    // We just determined the app is signed correctly, so bring
9318                    // over the latest parsed certs.
9319                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9320                } catch (PackageManagerException e) {
9321                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9322                        throw e;
9323                    }
9324                    // The signature has changed, but this package is in the system
9325                    // image...  let's recover!
9326                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9327                    // However...  if this package is part of a shared user, but it
9328                    // doesn't match the signature of the shared user, let's fail.
9329                    // What this means is that you can't change the signatures
9330                    // associated with an overall shared user, which doesn't seem all
9331                    // that unreasonable.
9332                    if (signatureCheckPs.sharedUser != null) {
9333                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9334                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9335                            throw new PackageManagerException(
9336                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9337                                    "Signature mismatch for shared user: "
9338                                            + pkgSetting.sharedUser);
9339                        }
9340                    }
9341                    // File a report about this.
9342                    String msg = "System package " + pkg.packageName
9343                            + " signature changed; retaining data.";
9344                    reportSettingsProblem(Log.WARN, msg);
9345                }
9346            }
9347
9348            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9349                // This package wants to adopt ownership of permissions from
9350                // another package.
9351                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9352                    final String origName = pkg.mAdoptPermissions.get(i);
9353                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9354                    if (orig != null) {
9355                        if (verifyPackageUpdateLPr(orig, pkg)) {
9356                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9357                                    + pkg.packageName);
9358                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9359                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9360                        }
9361                    }
9362                }
9363            }
9364        }
9365
9366        pkg.applicationInfo.processName = fixProcessName(
9367                pkg.applicationInfo.packageName,
9368                pkg.applicationInfo.processName);
9369
9370        if (pkg != mPlatformPackage) {
9371            // Get all of our default paths setup
9372            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9373        }
9374
9375        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9376
9377        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9378            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9379                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9380                derivePackageAbi(
9381                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9382                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9383
9384                // Some system apps still use directory structure for native libraries
9385                // in which case we might end up not detecting abi solely based on apk
9386                // structure. Try to detect abi based on directory structure.
9387                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9388                        pkg.applicationInfo.primaryCpuAbi == null) {
9389                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9390                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9391                }
9392            } else {
9393                // This is not a first boot or an upgrade, don't bother deriving the
9394                // ABI during the scan. Instead, trust the value that was stored in the
9395                // package setting.
9396                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9397                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9398
9399                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9400
9401                if (DEBUG_ABI_SELECTION) {
9402                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9403                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9404                        pkg.applicationInfo.secondaryCpuAbi);
9405                }
9406            }
9407        } else {
9408            if ((scanFlags & SCAN_MOVE) != 0) {
9409                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9410                // but we already have this packages package info in the PackageSetting. We just
9411                // use that and derive the native library path based on the new codepath.
9412                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9413                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9414            }
9415
9416            // Set native library paths again. For moves, the path will be updated based on the
9417            // ABIs we've determined above. For non-moves, the path will be updated based on the
9418            // ABIs we determined during compilation, but the path will depend on the final
9419            // package path (after the rename away from the stage path).
9420            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9421        }
9422
9423        // This is a special case for the "system" package, where the ABI is
9424        // dictated by the zygote configuration (and init.rc). We should keep track
9425        // of this ABI so that we can deal with "normal" applications that run under
9426        // the same UID correctly.
9427        if (mPlatformPackage == pkg) {
9428            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9429                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9430        }
9431
9432        // If there's a mismatch between the abi-override in the package setting
9433        // and the abiOverride specified for the install. Warn about this because we
9434        // would've already compiled the app without taking the package setting into
9435        // account.
9436        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9437            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9438                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9439                        " for package " + pkg.packageName);
9440            }
9441        }
9442
9443        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9444        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9445        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9446
9447        // Copy the derived override back to the parsed package, so that we can
9448        // update the package settings accordingly.
9449        pkg.cpuAbiOverride = cpuAbiOverride;
9450
9451        if (DEBUG_ABI_SELECTION) {
9452            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9453                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9454                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9455        }
9456
9457        // Push the derived path down into PackageSettings so we know what to
9458        // clean up at uninstall time.
9459        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9460
9461        if (DEBUG_ABI_SELECTION) {
9462            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9463                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9464                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9465        }
9466
9467        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9468        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9469            // We don't do this here during boot because we can do it all
9470            // at once after scanning all existing packages.
9471            //
9472            // We also do this *before* we perform dexopt on this package, so that
9473            // we can avoid redundant dexopts, and also to make sure we've got the
9474            // code and package path correct.
9475            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9476        }
9477
9478        if (mFactoryTest && pkg.requestedPermissions.contains(
9479                android.Manifest.permission.FACTORY_TEST)) {
9480            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9481        }
9482
9483        if (isSystemApp(pkg)) {
9484            pkgSetting.isOrphaned = true;
9485        }
9486
9487        // Take care of first install / last update times.
9488        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9489        if (currentTime != 0) {
9490            if (pkgSetting.firstInstallTime == 0) {
9491                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9492            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9493                pkgSetting.lastUpdateTime = currentTime;
9494            }
9495        } else if (pkgSetting.firstInstallTime == 0) {
9496            // We need *something*.  Take time time stamp of the file.
9497            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9498        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9499            if (scanFileTime != pkgSetting.timeStamp) {
9500                // A package on the system image has changed; consider this
9501                // to be an update.
9502                pkgSetting.lastUpdateTime = scanFileTime;
9503            }
9504        }
9505        pkgSetting.setTimeStamp(scanFileTime);
9506
9507        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9508            if (nonMutatedPs != null) {
9509                synchronized (mPackages) {
9510                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9511                }
9512            }
9513        } else {
9514            final int userId = user == null ? 0 : user.getIdentifier();
9515            // Modify state for the given package setting
9516            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9517                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9518            if (pkgSetting.getInstantApp(userId)) {
9519                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9520            }
9521        }
9522        return pkg;
9523    }
9524
9525    /**
9526     * Applies policy to the parsed package based upon the given policy flags.
9527     * Ensures the package is in a good state.
9528     * <p>
9529     * Implementation detail: This method must NOT have any side effect. It would
9530     * ideally be static, but, it requires locks to read system state.
9531     */
9532    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9533        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9534            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9535            if (pkg.applicationInfo.isDirectBootAware()) {
9536                // we're direct boot aware; set for all components
9537                for (PackageParser.Service s : pkg.services) {
9538                    s.info.encryptionAware = s.info.directBootAware = true;
9539                }
9540                for (PackageParser.Provider p : pkg.providers) {
9541                    p.info.encryptionAware = p.info.directBootAware = true;
9542                }
9543                for (PackageParser.Activity a : pkg.activities) {
9544                    a.info.encryptionAware = a.info.directBootAware = true;
9545                }
9546                for (PackageParser.Activity r : pkg.receivers) {
9547                    r.info.encryptionAware = r.info.directBootAware = true;
9548                }
9549            }
9550        } else {
9551            // Only allow system apps to be flagged as core apps.
9552            pkg.coreApp = false;
9553            // clear flags not applicable to regular apps
9554            pkg.applicationInfo.privateFlags &=
9555                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9556            pkg.applicationInfo.privateFlags &=
9557                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9558        }
9559        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9560
9561        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9562            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9563        }
9564
9565        if (!isSystemApp(pkg)) {
9566            // Only system apps can use these features.
9567            pkg.mOriginalPackages = null;
9568            pkg.mRealPackage = null;
9569            pkg.mAdoptPermissions = null;
9570        }
9571    }
9572
9573    /**
9574     * Asserts the parsed package is valid according to the given policy. If the
9575     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9576     * <p>
9577     * Implementation detail: This method must NOT have any side effects. It would
9578     * ideally be static, but, it requires locks to read system state.
9579     *
9580     * @throws PackageManagerException If the package fails any of the validation checks
9581     */
9582    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9583            throws PackageManagerException {
9584        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9585            assertCodePolicy(pkg);
9586        }
9587
9588        if (pkg.applicationInfo.getCodePath() == null ||
9589                pkg.applicationInfo.getResourcePath() == null) {
9590            // Bail out. The resource and code paths haven't been set.
9591            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9592                    "Code and resource paths haven't been set correctly");
9593        }
9594
9595        // Make sure we're not adding any bogus keyset info
9596        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9597        ksms.assertScannedPackageValid(pkg);
9598
9599        synchronized (mPackages) {
9600            // The special "android" package can only be defined once
9601            if (pkg.packageName.equals("android")) {
9602                if (mAndroidApplication != null) {
9603                    Slog.w(TAG, "*************************************************");
9604                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9605                    Slog.w(TAG, " codePath=" + pkg.codePath);
9606                    Slog.w(TAG, "*************************************************");
9607                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9608                            "Core android package being redefined.  Skipping.");
9609                }
9610            }
9611
9612            // A package name must be unique; don't allow duplicates
9613            if (mPackages.containsKey(pkg.packageName)) {
9614                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9615                        "Application package " + pkg.packageName
9616                        + " already installed.  Skipping duplicate.");
9617            }
9618
9619            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9620                // Static libs have a synthetic package name containing the version
9621                // but we still want the base name to be unique.
9622                if (mPackages.containsKey(pkg.manifestPackageName)) {
9623                    throw new PackageManagerException(
9624                            "Duplicate static shared lib provider package");
9625                }
9626
9627                // Static shared libraries should have at least O target SDK
9628                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9629                    throw new PackageManagerException(
9630                            "Packages declaring static-shared libs must target O SDK or higher");
9631                }
9632
9633                // Package declaring static a shared lib cannot be instant apps
9634                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9635                    throw new PackageManagerException(
9636                            "Packages declaring static-shared libs cannot be instant apps");
9637                }
9638
9639                // Package declaring static a shared lib cannot be renamed since the package
9640                // name is synthetic and apps can't code around package manager internals.
9641                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9642                    throw new PackageManagerException(
9643                            "Packages declaring static-shared libs cannot be renamed");
9644                }
9645
9646                // Package declaring static a shared lib cannot declare child packages
9647                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9648                    throw new PackageManagerException(
9649                            "Packages declaring static-shared libs cannot have child packages");
9650                }
9651
9652                // Package declaring static a shared lib cannot declare dynamic libs
9653                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9654                    throw new PackageManagerException(
9655                            "Packages declaring static-shared libs cannot declare dynamic libs");
9656                }
9657
9658                // Package declaring static a shared lib cannot declare shared users
9659                if (pkg.mSharedUserId != null) {
9660                    throw new PackageManagerException(
9661                            "Packages declaring static-shared libs cannot declare shared users");
9662                }
9663
9664                // Static shared libs cannot declare activities
9665                if (!pkg.activities.isEmpty()) {
9666                    throw new PackageManagerException(
9667                            "Static shared libs cannot declare activities");
9668                }
9669
9670                // Static shared libs cannot declare services
9671                if (!pkg.services.isEmpty()) {
9672                    throw new PackageManagerException(
9673                            "Static shared libs cannot declare services");
9674                }
9675
9676                // Static shared libs cannot declare providers
9677                if (!pkg.providers.isEmpty()) {
9678                    throw new PackageManagerException(
9679                            "Static shared libs cannot declare content providers");
9680                }
9681
9682                // Static shared libs cannot declare receivers
9683                if (!pkg.receivers.isEmpty()) {
9684                    throw new PackageManagerException(
9685                            "Static shared libs cannot declare broadcast receivers");
9686                }
9687
9688                // Static shared libs cannot declare permission groups
9689                if (!pkg.permissionGroups.isEmpty()) {
9690                    throw new PackageManagerException(
9691                            "Static shared libs cannot declare permission groups");
9692                }
9693
9694                // Static shared libs cannot declare permissions
9695                if (!pkg.permissions.isEmpty()) {
9696                    throw new PackageManagerException(
9697                            "Static shared libs cannot declare permissions");
9698                }
9699
9700                // Static shared libs cannot declare protected broadcasts
9701                if (pkg.protectedBroadcasts != null) {
9702                    throw new PackageManagerException(
9703                            "Static shared libs cannot declare protected broadcasts");
9704                }
9705
9706                // Static shared libs cannot be overlay targets
9707                if (pkg.mOverlayTarget != null) {
9708                    throw new PackageManagerException(
9709                            "Static shared libs cannot be overlay targets");
9710                }
9711
9712                // The version codes must be ordered as lib versions
9713                int minVersionCode = Integer.MIN_VALUE;
9714                int maxVersionCode = Integer.MAX_VALUE;
9715
9716                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9717                        pkg.staticSharedLibName);
9718                if (versionedLib != null) {
9719                    final int versionCount = versionedLib.size();
9720                    for (int i = 0; i < versionCount; i++) {
9721                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9722                        // TODO: We will change version code to long, so in the new API it is long
9723                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9724                                .getVersionCode();
9725                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9726                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9727                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9728                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9729                        } else {
9730                            minVersionCode = maxVersionCode = libVersionCode;
9731                            break;
9732                        }
9733                    }
9734                }
9735                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9736                    throw new PackageManagerException("Static shared"
9737                            + " lib version codes must be ordered as lib versions");
9738                }
9739            }
9740
9741            // Only privileged apps and updated privileged apps can add child packages.
9742            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9743                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9744                    throw new PackageManagerException("Only privileged apps can add child "
9745                            + "packages. Ignoring package " + pkg.packageName);
9746                }
9747                final int childCount = pkg.childPackages.size();
9748                for (int i = 0; i < childCount; i++) {
9749                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9750                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9751                            childPkg.packageName)) {
9752                        throw new PackageManagerException("Can't override child of "
9753                                + "another disabled app. Ignoring package " + pkg.packageName);
9754                    }
9755                }
9756            }
9757
9758            // If we're only installing presumed-existing packages, require that the
9759            // scanned APK is both already known and at the path previously established
9760            // for it.  Previously unknown packages we pick up normally, but if we have an
9761            // a priori expectation about this package's install presence, enforce it.
9762            // With a singular exception for new system packages. When an OTA contains
9763            // a new system package, we allow the codepath to change from a system location
9764            // to the user-installed location. If we don't allow this change, any newer,
9765            // user-installed version of the application will be ignored.
9766            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9767                if (mExpectingBetter.containsKey(pkg.packageName)) {
9768                    logCriticalInfo(Log.WARN,
9769                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9770                } else {
9771                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9772                    if (known != null) {
9773                        if (DEBUG_PACKAGE_SCANNING) {
9774                            Log.d(TAG, "Examining " + pkg.codePath
9775                                    + " and requiring known paths " + known.codePathString
9776                                    + " & " + known.resourcePathString);
9777                        }
9778                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9779                                || !pkg.applicationInfo.getResourcePath().equals(
9780                                        known.resourcePathString)) {
9781                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9782                                    "Application package " + pkg.packageName
9783                                    + " found at " + pkg.applicationInfo.getCodePath()
9784                                    + " but expected at " + known.codePathString
9785                                    + "; ignoring.");
9786                        }
9787                    }
9788                }
9789            }
9790
9791            // Verify that this new package doesn't have any content providers
9792            // that conflict with existing packages.  Only do this if the
9793            // package isn't already installed, since we don't want to break
9794            // things that are installed.
9795            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9796                final int N = pkg.providers.size();
9797                int i;
9798                for (i=0; i<N; i++) {
9799                    PackageParser.Provider p = pkg.providers.get(i);
9800                    if (p.info.authority != null) {
9801                        String names[] = p.info.authority.split(";");
9802                        for (int j = 0; j < names.length; j++) {
9803                            if (mProvidersByAuthority.containsKey(names[j])) {
9804                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9805                                final String otherPackageName =
9806                                        ((other != null && other.getComponentName() != null) ?
9807                                                other.getComponentName().getPackageName() : "?");
9808                                throw new PackageManagerException(
9809                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9810                                        "Can't install because provider name " + names[j]
9811                                                + " (in package " + pkg.applicationInfo.packageName
9812                                                + ") is already used by " + otherPackageName);
9813                            }
9814                        }
9815                    }
9816                }
9817            }
9818        }
9819    }
9820
9821    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9822            int type, String declaringPackageName, int declaringVersionCode) {
9823        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9824        if (versionedLib == null) {
9825            versionedLib = new SparseArray<>();
9826            mSharedLibraries.put(name, versionedLib);
9827            if (type == SharedLibraryInfo.TYPE_STATIC) {
9828                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9829            }
9830        } else if (versionedLib.indexOfKey(version) >= 0) {
9831            return false;
9832        }
9833        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9834                version, type, declaringPackageName, declaringVersionCode);
9835        versionedLib.put(version, libEntry);
9836        return true;
9837    }
9838
9839    private boolean removeSharedLibraryLPw(String name, int version) {
9840        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9841        if (versionedLib == null) {
9842            return false;
9843        }
9844        final int libIdx = versionedLib.indexOfKey(version);
9845        if (libIdx < 0) {
9846            return false;
9847        }
9848        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9849        versionedLib.remove(version);
9850        if (versionedLib.size() <= 0) {
9851            mSharedLibraries.remove(name);
9852            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9853                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9854                        .getPackageName());
9855            }
9856        }
9857        return true;
9858    }
9859
9860    /**
9861     * Adds a scanned package to the system. When this method is finished, the package will
9862     * be available for query, resolution, etc...
9863     */
9864    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9865            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9866        final String pkgName = pkg.packageName;
9867        if (mCustomResolverComponentName != null &&
9868                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9869            setUpCustomResolverActivity(pkg);
9870        }
9871
9872        if (pkg.packageName.equals("android")) {
9873            synchronized (mPackages) {
9874                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9875                    // Set up information for our fall-back user intent resolution activity.
9876                    mPlatformPackage = pkg;
9877                    pkg.mVersionCode = mSdkVersion;
9878                    mAndroidApplication = pkg.applicationInfo;
9879                    if (!mResolverReplaced) {
9880                        mResolveActivity.applicationInfo = mAndroidApplication;
9881                        mResolveActivity.name = ResolverActivity.class.getName();
9882                        mResolveActivity.packageName = mAndroidApplication.packageName;
9883                        mResolveActivity.processName = "system:ui";
9884                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9885                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9886                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9887                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9888                        mResolveActivity.exported = true;
9889                        mResolveActivity.enabled = true;
9890                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9891                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9892                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9893                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9894                                | ActivityInfo.CONFIG_ORIENTATION
9895                                | ActivityInfo.CONFIG_KEYBOARD
9896                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9897                        mResolveInfo.activityInfo = mResolveActivity;
9898                        mResolveInfo.priority = 0;
9899                        mResolveInfo.preferredOrder = 0;
9900                        mResolveInfo.match = 0;
9901                        mResolveComponentName = new ComponentName(
9902                                mAndroidApplication.packageName, mResolveActivity.name);
9903                    }
9904                }
9905            }
9906        }
9907
9908        ArrayList<PackageParser.Package> clientLibPkgs = null;
9909        // writer
9910        synchronized (mPackages) {
9911            boolean hasStaticSharedLibs = false;
9912
9913            // Any app can add new static shared libraries
9914            if (pkg.staticSharedLibName != null) {
9915                // Static shared libs don't allow renaming as they have synthetic package
9916                // names to allow install of multiple versions, so use name from manifest.
9917                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9918                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9919                        pkg.manifestPackageName, pkg.mVersionCode)) {
9920                    hasStaticSharedLibs = true;
9921                } else {
9922                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9923                                + pkg.staticSharedLibName + " already exists; skipping");
9924                }
9925                // Static shared libs cannot be updated once installed since they
9926                // use synthetic package name which includes the version code, so
9927                // not need to update other packages's shared lib dependencies.
9928            }
9929
9930            if (!hasStaticSharedLibs
9931                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9932                // Only system apps can add new dynamic shared libraries.
9933                if (pkg.libraryNames != null) {
9934                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9935                        String name = pkg.libraryNames.get(i);
9936                        boolean allowed = false;
9937                        if (pkg.isUpdatedSystemApp()) {
9938                            // New library entries can only be added through the
9939                            // system image.  This is important to get rid of a lot
9940                            // of nasty edge cases: for example if we allowed a non-
9941                            // system update of the app to add a library, then uninstalling
9942                            // the update would make the library go away, and assumptions
9943                            // we made such as through app install filtering would now
9944                            // have allowed apps on the device which aren't compatible
9945                            // with it.  Better to just have the restriction here, be
9946                            // conservative, and create many fewer cases that can negatively
9947                            // impact the user experience.
9948                            final PackageSetting sysPs = mSettings
9949                                    .getDisabledSystemPkgLPr(pkg.packageName);
9950                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9951                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9952                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9953                                        allowed = true;
9954                                        break;
9955                                    }
9956                                }
9957                            }
9958                        } else {
9959                            allowed = true;
9960                        }
9961                        if (allowed) {
9962                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9963                                    SharedLibraryInfo.VERSION_UNDEFINED,
9964                                    SharedLibraryInfo.TYPE_DYNAMIC,
9965                                    pkg.packageName, pkg.mVersionCode)) {
9966                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9967                                        + name + " already exists; skipping");
9968                            }
9969                        } else {
9970                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9971                                    + name + " that is not declared on system image; skipping");
9972                        }
9973                    }
9974
9975                    if ((scanFlags & SCAN_BOOTING) == 0) {
9976                        // If we are not booting, we need to update any applications
9977                        // that are clients of our shared library.  If we are booting,
9978                        // this will all be done once the scan is complete.
9979                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9980                    }
9981                }
9982            }
9983        }
9984
9985        if ((scanFlags & SCAN_BOOTING) != 0) {
9986            // No apps can run during boot scan, so they don't need to be frozen
9987        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9988            // Caller asked to not kill app, so it's probably not frozen
9989        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9990            // Caller asked us to ignore frozen check for some reason; they
9991            // probably didn't know the package name
9992        } else {
9993            // We're doing major surgery on this package, so it better be frozen
9994            // right now to keep it from launching
9995            checkPackageFrozen(pkgName);
9996        }
9997
9998        // Also need to kill any apps that are dependent on the library.
9999        if (clientLibPkgs != null) {
10000            for (int i=0; i<clientLibPkgs.size(); i++) {
10001                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10002                killApplication(clientPkg.applicationInfo.packageName,
10003                        clientPkg.applicationInfo.uid, "update lib");
10004            }
10005        }
10006
10007        // writer
10008        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10009
10010        synchronized (mPackages) {
10011            // We don't expect installation to fail beyond this point
10012
10013            // Add the new setting to mSettings
10014            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10015            // Add the new setting to mPackages
10016            mPackages.put(pkg.applicationInfo.packageName, pkg);
10017            // Make sure we don't accidentally delete its data.
10018            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10019            while (iter.hasNext()) {
10020                PackageCleanItem item = iter.next();
10021                if (pkgName.equals(item.packageName)) {
10022                    iter.remove();
10023                }
10024            }
10025
10026            // Add the package's KeySets to the global KeySetManagerService
10027            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10028            ksms.addScannedPackageLPw(pkg);
10029
10030            int N = pkg.providers.size();
10031            StringBuilder r = null;
10032            int i;
10033            for (i=0; i<N; i++) {
10034                PackageParser.Provider p = pkg.providers.get(i);
10035                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10036                        p.info.processName);
10037                mProviders.addProvider(p);
10038                p.syncable = p.info.isSyncable;
10039                if (p.info.authority != null) {
10040                    String names[] = p.info.authority.split(";");
10041                    p.info.authority = null;
10042                    for (int j = 0; j < names.length; j++) {
10043                        if (j == 1 && p.syncable) {
10044                            // We only want the first authority for a provider to possibly be
10045                            // syncable, so if we already added this provider using a different
10046                            // authority clear the syncable flag. We copy the provider before
10047                            // changing it because the mProviders object contains a reference
10048                            // to a provider that we don't want to change.
10049                            // Only do this for the second authority since the resulting provider
10050                            // object can be the same for all future authorities for this provider.
10051                            p = new PackageParser.Provider(p);
10052                            p.syncable = false;
10053                        }
10054                        if (!mProvidersByAuthority.containsKey(names[j])) {
10055                            mProvidersByAuthority.put(names[j], p);
10056                            if (p.info.authority == null) {
10057                                p.info.authority = names[j];
10058                            } else {
10059                                p.info.authority = p.info.authority + ";" + names[j];
10060                            }
10061                            if (DEBUG_PACKAGE_SCANNING) {
10062                                if (chatty)
10063                                    Log.d(TAG, "Registered content provider: " + names[j]
10064                                            + ", className = " + p.info.name + ", isSyncable = "
10065                                            + p.info.isSyncable);
10066                            }
10067                        } else {
10068                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10069                            Slog.w(TAG, "Skipping provider name " + names[j] +
10070                                    " (in package " + pkg.applicationInfo.packageName +
10071                                    "): name already used by "
10072                                    + ((other != null && other.getComponentName() != null)
10073                                            ? other.getComponentName().getPackageName() : "?"));
10074                        }
10075                    }
10076                }
10077                if (chatty) {
10078                    if (r == null) {
10079                        r = new StringBuilder(256);
10080                    } else {
10081                        r.append(' ');
10082                    }
10083                    r.append(p.info.name);
10084                }
10085            }
10086            if (r != null) {
10087                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10088            }
10089
10090            N = pkg.services.size();
10091            r = null;
10092            for (i=0; i<N; i++) {
10093                PackageParser.Service s = pkg.services.get(i);
10094                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10095                        s.info.processName);
10096                mServices.addService(s);
10097                if (chatty) {
10098                    if (r == null) {
10099                        r = new StringBuilder(256);
10100                    } else {
10101                        r.append(' ');
10102                    }
10103                    r.append(s.info.name);
10104                }
10105            }
10106            if (r != null) {
10107                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10108            }
10109
10110            N = pkg.receivers.size();
10111            r = null;
10112            for (i=0; i<N; i++) {
10113                PackageParser.Activity a = pkg.receivers.get(i);
10114                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10115                        a.info.processName);
10116                mReceivers.addActivity(a, "receiver");
10117                if (chatty) {
10118                    if (r == null) {
10119                        r = new StringBuilder(256);
10120                    } else {
10121                        r.append(' ');
10122                    }
10123                    r.append(a.info.name);
10124                }
10125            }
10126            if (r != null) {
10127                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10128            }
10129
10130            N = pkg.activities.size();
10131            r = null;
10132            for (i=0; i<N; i++) {
10133                PackageParser.Activity a = pkg.activities.get(i);
10134                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10135                        a.info.processName);
10136                mActivities.addActivity(a, "activity");
10137                if (chatty) {
10138                    if (r == null) {
10139                        r = new StringBuilder(256);
10140                    } else {
10141                        r.append(' ');
10142                    }
10143                    r.append(a.info.name);
10144                }
10145            }
10146            if (r != null) {
10147                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10148            }
10149
10150            N = pkg.permissionGroups.size();
10151            r = null;
10152            for (i=0; i<N; i++) {
10153                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10154                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10155                final String curPackageName = cur == null ? null : cur.info.packageName;
10156                // Dont allow ephemeral apps to define new permission groups.
10157                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10158                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10159                            + pg.info.packageName
10160                            + " ignored: instant apps cannot define new permission groups.");
10161                    continue;
10162                }
10163                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10164                if (cur == null || isPackageUpdate) {
10165                    mPermissionGroups.put(pg.info.name, pg);
10166                    if (chatty) {
10167                        if (r == null) {
10168                            r = new StringBuilder(256);
10169                        } else {
10170                            r.append(' ');
10171                        }
10172                        if (isPackageUpdate) {
10173                            r.append("UPD:");
10174                        }
10175                        r.append(pg.info.name);
10176                    }
10177                } else {
10178                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10179                            + pg.info.packageName + " ignored: original from "
10180                            + cur.info.packageName);
10181                    if (chatty) {
10182                        if (r == null) {
10183                            r = new StringBuilder(256);
10184                        } else {
10185                            r.append(' ');
10186                        }
10187                        r.append("DUP:");
10188                        r.append(pg.info.name);
10189                    }
10190                }
10191            }
10192            if (r != null) {
10193                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10194            }
10195
10196            N = pkg.permissions.size();
10197            r = null;
10198            for (i=0; i<N; i++) {
10199                PackageParser.Permission p = pkg.permissions.get(i);
10200
10201                // Dont allow ephemeral apps to define new permissions.
10202                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10203                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10204                            + p.info.packageName
10205                            + " ignored: instant apps cannot define new permissions.");
10206                    continue;
10207                }
10208
10209                // Assume by default that we did not install this permission into the system.
10210                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10211
10212                // Now that permission groups have a special meaning, we ignore permission
10213                // groups for legacy apps to prevent unexpected behavior. In particular,
10214                // permissions for one app being granted to someone just becase they happen
10215                // to be in a group defined by another app (before this had no implications).
10216                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10217                    p.group = mPermissionGroups.get(p.info.group);
10218                    // Warn for a permission in an unknown group.
10219                    if (p.info.group != null && p.group == null) {
10220                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10221                                + p.info.packageName + " in an unknown group " + p.info.group);
10222                    }
10223                }
10224
10225                ArrayMap<String, BasePermission> permissionMap =
10226                        p.tree ? mSettings.mPermissionTrees
10227                                : mSettings.mPermissions;
10228                BasePermission bp = permissionMap.get(p.info.name);
10229
10230                // Allow system apps to redefine non-system permissions
10231                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10232                    final boolean currentOwnerIsSystem = (bp.perm != null
10233                            && isSystemApp(bp.perm.owner));
10234                    if (isSystemApp(p.owner)) {
10235                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10236                            // It's a built-in permission and no owner, take ownership now
10237                            bp.packageSetting = pkgSetting;
10238                            bp.perm = p;
10239                            bp.uid = pkg.applicationInfo.uid;
10240                            bp.sourcePackage = p.info.packageName;
10241                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10242                        } else if (!currentOwnerIsSystem) {
10243                            String msg = "New decl " + p.owner + " of permission  "
10244                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10245                            reportSettingsProblem(Log.WARN, msg);
10246                            bp = null;
10247                        }
10248                    }
10249                }
10250
10251                if (bp == null) {
10252                    bp = new BasePermission(p.info.name, p.info.packageName,
10253                            BasePermission.TYPE_NORMAL);
10254                    permissionMap.put(p.info.name, bp);
10255                }
10256
10257                if (bp.perm == null) {
10258                    if (bp.sourcePackage == null
10259                            || bp.sourcePackage.equals(p.info.packageName)) {
10260                        BasePermission tree = findPermissionTreeLP(p.info.name);
10261                        if (tree == null
10262                                || tree.sourcePackage.equals(p.info.packageName)) {
10263                            bp.packageSetting = pkgSetting;
10264                            bp.perm = p;
10265                            bp.uid = pkg.applicationInfo.uid;
10266                            bp.sourcePackage = p.info.packageName;
10267                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10268                            if (chatty) {
10269                                if (r == null) {
10270                                    r = new StringBuilder(256);
10271                                } else {
10272                                    r.append(' ');
10273                                }
10274                                r.append(p.info.name);
10275                            }
10276                        } else {
10277                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10278                                    + p.info.packageName + " ignored: base tree "
10279                                    + tree.name + " is from package "
10280                                    + tree.sourcePackage);
10281                        }
10282                    } else {
10283                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10284                                + p.info.packageName + " ignored: original from "
10285                                + bp.sourcePackage);
10286                    }
10287                } else if (chatty) {
10288                    if (r == null) {
10289                        r = new StringBuilder(256);
10290                    } else {
10291                        r.append(' ');
10292                    }
10293                    r.append("DUP:");
10294                    r.append(p.info.name);
10295                }
10296                if (bp.perm == p) {
10297                    bp.protectionLevel = p.info.protectionLevel;
10298                }
10299            }
10300
10301            if (r != null) {
10302                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10303            }
10304
10305            N = pkg.instrumentation.size();
10306            r = null;
10307            for (i=0; i<N; i++) {
10308                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10309                a.info.packageName = pkg.applicationInfo.packageName;
10310                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10311                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10312                a.info.splitNames = pkg.splitNames;
10313                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10314                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10315                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10316                a.info.dataDir = pkg.applicationInfo.dataDir;
10317                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10318                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10319                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10320                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10321                mInstrumentation.put(a.getComponentName(), a);
10322                if (chatty) {
10323                    if (r == null) {
10324                        r = new StringBuilder(256);
10325                    } else {
10326                        r.append(' ');
10327                    }
10328                    r.append(a.info.name);
10329                }
10330            }
10331            if (r != null) {
10332                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10333            }
10334
10335            if (pkg.protectedBroadcasts != null) {
10336                N = pkg.protectedBroadcasts.size();
10337                for (i=0; i<N; i++) {
10338                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10339                }
10340            }
10341        }
10342
10343        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10344    }
10345
10346    /**
10347     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10348     * is derived purely on the basis of the contents of {@code scanFile} and
10349     * {@code cpuAbiOverride}.
10350     *
10351     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10352     */
10353    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10354                                 String cpuAbiOverride, boolean extractLibs,
10355                                 File appLib32InstallDir)
10356            throws PackageManagerException {
10357        // Give ourselves some initial paths; we'll come back for another
10358        // pass once we've determined ABI below.
10359        setNativeLibraryPaths(pkg, appLib32InstallDir);
10360
10361        // We would never need to extract libs for forward-locked and external packages,
10362        // since the container service will do it for us. We shouldn't attempt to
10363        // extract libs from system app when it was not updated.
10364        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10365                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10366            extractLibs = false;
10367        }
10368
10369        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10370        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10371
10372        NativeLibraryHelper.Handle handle = null;
10373        try {
10374            handle = NativeLibraryHelper.Handle.create(pkg);
10375            // TODO(multiArch): This can be null for apps that didn't go through the
10376            // usual installation process. We can calculate it again, like we
10377            // do during install time.
10378            //
10379            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10380            // unnecessary.
10381            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10382
10383            // Null out the abis so that they can be recalculated.
10384            pkg.applicationInfo.primaryCpuAbi = null;
10385            pkg.applicationInfo.secondaryCpuAbi = null;
10386            if (isMultiArch(pkg.applicationInfo)) {
10387                // Warn if we've set an abiOverride for multi-lib packages..
10388                // By definition, we need to copy both 32 and 64 bit libraries for
10389                // such packages.
10390                if (pkg.cpuAbiOverride != null
10391                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10392                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10393                }
10394
10395                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10396                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10397                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10398                    if (extractLibs) {
10399                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10400                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10401                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10402                                useIsaSpecificSubdirs);
10403                    } else {
10404                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10405                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10406                    }
10407                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10408                }
10409
10410                maybeThrowExceptionForMultiArchCopy(
10411                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10412
10413                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10414                    if (extractLibs) {
10415                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10416                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10417                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10418                                useIsaSpecificSubdirs);
10419                    } else {
10420                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10421                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10422                    }
10423                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10424                }
10425
10426                maybeThrowExceptionForMultiArchCopy(
10427                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10428
10429                if (abi64 >= 0) {
10430                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10431                }
10432
10433                if (abi32 >= 0) {
10434                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10435                    if (abi64 >= 0) {
10436                        if (pkg.use32bitAbi) {
10437                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10438                            pkg.applicationInfo.primaryCpuAbi = abi;
10439                        } else {
10440                            pkg.applicationInfo.secondaryCpuAbi = abi;
10441                        }
10442                    } else {
10443                        pkg.applicationInfo.primaryCpuAbi = abi;
10444                    }
10445                }
10446
10447            } else {
10448                String[] abiList = (cpuAbiOverride != null) ?
10449                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10450
10451                // Enable gross and lame hacks for apps that are built with old
10452                // SDK tools. We must scan their APKs for renderscript bitcode and
10453                // not launch them if it's present. Don't bother checking on devices
10454                // that don't have 64 bit support.
10455                boolean needsRenderScriptOverride = false;
10456                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10457                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10458                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10459                    needsRenderScriptOverride = true;
10460                }
10461
10462                final int copyRet;
10463                if (extractLibs) {
10464                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10465                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10466                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10467                } else {
10468                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10469                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10470                }
10471                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10472
10473                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10474                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10475                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10476                }
10477
10478                if (copyRet >= 0) {
10479                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10480                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10481                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10482                } else if (needsRenderScriptOverride) {
10483                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10484                }
10485            }
10486        } catch (IOException ioe) {
10487            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10488        } finally {
10489            IoUtils.closeQuietly(handle);
10490        }
10491
10492        // Now that we've calculated the ABIs and determined if it's an internal app,
10493        // we will go ahead and populate the nativeLibraryPath.
10494        setNativeLibraryPaths(pkg, appLib32InstallDir);
10495    }
10496
10497    /**
10498     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10499     * i.e, so that all packages can be run inside a single process if required.
10500     *
10501     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10502     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10503     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10504     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10505     * updating a package that belongs to a shared user.
10506     *
10507     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10508     * adds unnecessary complexity.
10509     */
10510    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10511            PackageParser.Package scannedPackage) {
10512        String requiredInstructionSet = null;
10513        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10514            requiredInstructionSet = VMRuntime.getInstructionSet(
10515                     scannedPackage.applicationInfo.primaryCpuAbi);
10516        }
10517
10518        PackageSetting requirer = null;
10519        for (PackageSetting ps : packagesForUser) {
10520            // If packagesForUser contains scannedPackage, we skip it. This will happen
10521            // when scannedPackage is an update of an existing package. Without this check,
10522            // we will never be able to change the ABI of any package belonging to a shared
10523            // user, even if it's compatible with other packages.
10524            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10525                if (ps.primaryCpuAbiString == null) {
10526                    continue;
10527                }
10528
10529                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10530                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10531                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10532                    // this but there's not much we can do.
10533                    String errorMessage = "Instruction set mismatch, "
10534                            + ((requirer == null) ? "[caller]" : requirer)
10535                            + " requires " + requiredInstructionSet + " whereas " + ps
10536                            + " requires " + instructionSet;
10537                    Slog.w(TAG, errorMessage);
10538                }
10539
10540                if (requiredInstructionSet == null) {
10541                    requiredInstructionSet = instructionSet;
10542                    requirer = ps;
10543                }
10544            }
10545        }
10546
10547        if (requiredInstructionSet != null) {
10548            String adjustedAbi;
10549            if (requirer != null) {
10550                // requirer != null implies that either scannedPackage was null or that scannedPackage
10551                // did not require an ABI, in which case we have to adjust scannedPackage to match
10552                // the ABI of the set (which is the same as requirer's ABI)
10553                adjustedAbi = requirer.primaryCpuAbiString;
10554                if (scannedPackage != null) {
10555                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10556                }
10557            } else {
10558                // requirer == null implies that we're updating all ABIs in the set to
10559                // match scannedPackage.
10560                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10561            }
10562
10563            for (PackageSetting ps : packagesForUser) {
10564                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10565                    if (ps.primaryCpuAbiString != null) {
10566                        continue;
10567                    }
10568
10569                    ps.primaryCpuAbiString = adjustedAbi;
10570                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10571                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10572                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10573                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10574                                + " (requirer="
10575                                + (requirer != null ? requirer.pkg : "null")
10576                                + ", scannedPackage="
10577                                + (scannedPackage != null ? scannedPackage : "null")
10578                                + ")");
10579                        try {
10580                            mInstaller.rmdex(ps.codePathString,
10581                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10582                        } catch (InstallerException ignored) {
10583                        }
10584                    }
10585                }
10586            }
10587        }
10588    }
10589
10590    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10591        synchronized (mPackages) {
10592            mResolverReplaced = true;
10593            // Set up information for custom user intent resolution activity.
10594            mResolveActivity.applicationInfo = pkg.applicationInfo;
10595            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10596            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10597            mResolveActivity.processName = pkg.applicationInfo.packageName;
10598            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10599            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10600                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10601            mResolveActivity.theme = 0;
10602            mResolveActivity.exported = true;
10603            mResolveActivity.enabled = true;
10604            mResolveInfo.activityInfo = mResolveActivity;
10605            mResolveInfo.priority = 0;
10606            mResolveInfo.preferredOrder = 0;
10607            mResolveInfo.match = 0;
10608            mResolveComponentName = mCustomResolverComponentName;
10609            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10610                    mResolveComponentName);
10611        }
10612    }
10613
10614    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10615        if (installerComponent == null) {
10616            if (DEBUG_EPHEMERAL) {
10617                Slog.d(TAG, "Clear ephemeral installer activity");
10618            }
10619            mInstantAppInstallerActivity.applicationInfo = null;
10620            return;
10621        }
10622
10623        if (DEBUG_EPHEMERAL) {
10624            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10625        }
10626        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10627        // Set up information for ephemeral installer activity
10628        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10629        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10630        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10631        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10632        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10633        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10634                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10635        mInstantAppInstallerActivity.theme = 0;
10636        mInstantAppInstallerActivity.exported = true;
10637        mInstantAppInstallerActivity.enabled = true;
10638        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10639        mInstantAppInstallerInfo.priority = 0;
10640        mInstantAppInstallerInfo.preferredOrder = 1;
10641        mInstantAppInstallerInfo.isDefault = true;
10642        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10643                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10644    }
10645
10646    private static String calculateBundledApkRoot(final String codePathString) {
10647        final File codePath = new File(codePathString);
10648        final File codeRoot;
10649        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10650            codeRoot = Environment.getRootDirectory();
10651        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10652            codeRoot = Environment.getOemDirectory();
10653        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10654            codeRoot = Environment.getVendorDirectory();
10655        } else {
10656            // Unrecognized code path; take its top real segment as the apk root:
10657            // e.g. /something/app/blah.apk => /something
10658            try {
10659                File f = codePath.getCanonicalFile();
10660                File parent = f.getParentFile();    // non-null because codePath is a file
10661                File tmp;
10662                while ((tmp = parent.getParentFile()) != null) {
10663                    f = parent;
10664                    parent = tmp;
10665                }
10666                codeRoot = f;
10667                Slog.w(TAG, "Unrecognized code path "
10668                        + codePath + " - using " + codeRoot);
10669            } catch (IOException e) {
10670                // Can't canonicalize the code path -- shenanigans?
10671                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10672                return Environment.getRootDirectory().getPath();
10673            }
10674        }
10675        return codeRoot.getPath();
10676    }
10677
10678    /**
10679     * Derive and set the location of native libraries for the given package,
10680     * which varies depending on where and how the package was installed.
10681     */
10682    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10683        final ApplicationInfo info = pkg.applicationInfo;
10684        final String codePath = pkg.codePath;
10685        final File codeFile = new File(codePath);
10686        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10687        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10688
10689        info.nativeLibraryRootDir = null;
10690        info.nativeLibraryRootRequiresIsa = false;
10691        info.nativeLibraryDir = null;
10692        info.secondaryNativeLibraryDir = null;
10693
10694        if (isApkFile(codeFile)) {
10695            // Monolithic install
10696            if (bundledApp) {
10697                // If "/system/lib64/apkname" exists, assume that is the per-package
10698                // native library directory to use; otherwise use "/system/lib/apkname".
10699                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10700                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10701                        getPrimaryInstructionSet(info));
10702
10703                // This is a bundled system app so choose the path based on the ABI.
10704                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10705                // is just the default path.
10706                final String apkName = deriveCodePathName(codePath);
10707                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10708                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10709                        apkName).getAbsolutePath();
10710
10711                if (info.secondaryCpuAbi != null) {
10712                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10713                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10714                            secondaryLibDir, apkName).getAbsolutePath();
10715                }
10716            } else if (asecApp) {
10717                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10718                        .getAbsolutePath();
10719            } else {
10720                final String apkName = deriveCodePathName(codePath);
10721                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10722                        .getAbsolutePath();
10723            }
10724
10725            info.nativeLibraryRootRequiresIsa = false;
10726            info.nativeLibraryDir = info.nativeLibraryRootDir;
10727        } else {
10728            // Cluster install
10729            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10730            info.nativeLibraryRootRequiresIsa = true;
10731
10732            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10733                    getPrimaryInstructionSet(info)).getAbsolutePath();
10734
10735            if (info.secondaryCpuAbi != null) {
10736                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10737                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10738            }
10739        }
10740    }
10741
10742    /**
10743     * Calculate the abis and roots for a bundled app. These can uniquely
10744     * be determined from the contents of the system partition, i.e whether
10745     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10746     * of this information, and instead assume that the system was built
10747     * sensibly.
10748     */
10749    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10750                                           PackageSetting pkgSetting) {
10751        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10752
10753        // If "/system/lib64/apkname" exists, assume that is the per-package
10754        // native library directory to use; otherwise use "/system/lib/apkname".
10755        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10756        setBundledAppAbi(pkg, apkRoot, apkName);
10757        // pkgSetting might be null during rescan following uninstall of updates
10758        // to a bundled app, so accommodate that possibility.  The settings in
10759        // that case will be established later from the parsed package.
10760        //
10761        // If the settings aren't null, sync them up with what we've just derived.
10762        // note that apkRoot isn't stored in the package settings.
10763        if (pkgSetting != null) {
10764            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10765            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10766        }
10767    }
10768
10769    /**
10770     * Deduces the ABI of a bundled app and sets the relevant fields on the
10771     * parsed pkg object.
10772     *
10773     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10774     *        under which system libraries are installed.
10775     * @param apkName the name of the installed package.
10776     */
10777    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10778        final File codeFile = new File(pkg.codePath);
10779
10780        final boolean has64BitLibs;
10781        final boolean has32BitLibs;
10782        if (isApkFile(codeFile)) {
10783            // Monolithic install
10784            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10785            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10786        } else {
10787            // Cluster install
10788            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10789            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10790                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10791                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10792                has64BitLibs = (new File(rootDir, isa)).exists();
10793            } else {
10794                has64BitLibs = false;
10795            }
10796            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10797                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10798                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10799                has32BitLibs = (new File(rootDir, isa)).exists();
10800            } else {
10801                has32BitLibs = false;
10802            }
10803        }
10804
10805        if (has64BitLibs && !has32BitLibs) {
10806            // The package has 64 bit libs, but not 32 bit libs. Its primary
10807            // ABI should be 64 bit. We can safely assume here that the bundled
10808            // native libraries correspond to the most preferred ABI in the list.
10809
10810            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10811            pkg.applicationInfo.secondaryCpuAbi = null;
10812        } else if (has32BitLibs && !has64BitLibs) {
10813            // The package has 32 bit libs but not 64 bit libs. Its primary
10814            // ABI should be 32 bit.
10815
10816            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10817            pkg.applicationInfo.secondaryCpuAbi = null;
10818        } else if (has32BitLibs && has64BitLibs) {
10819            // The application has both 64 and 32 bit bundled libraries. We check
10820            // here that the app declares multiArch support, and warn if it doesn't.
10821            //
10822            // We will be lenient here and record both ABIs. The primary will be the
10823            // ABI that's higher on the list, i.e, a device that's configured to prefer
10824            // 64 bit apps will see a 64 bit primary ABI,
10825
10826            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10827                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10828            }
10829
10830            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10831                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10832                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10833            } else {
10834                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10835                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10836            }
10837        } else {
10838            pkg.applicationInfo.primaryCpuAbi = null;
10839            pkg.applicationInfo.secondaryCpuAbi = null;
10840        }
10841    }
10842
10843    private void killApplication(String pkgName, int appId, String reason) {
10844        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10845    }
10846
10847    private void killApplication(String pkgName, int appId, int userId, String reason) {
10848        // Request the ActivityManager to kill the process(only for existing packages)
10849        // so that we do not end up in a confused state while the user is still using the older
10850        // version of the application while the new one gets installed.
10851        final long token = Binder.clearCallingIdentity();
10852        try {
10853            IActivityManager am = ActivityManager.getService();
10854            if (am != null) {
10855                try {
10856                    am.killApplication(pkgName, appId, userId, reason);
10857                } catch (RemoteException e) {
10858                }
10859            }
10860        } finally {
10861            Binder.restoreCallingIdentity(token);
10862        }
10863    }
10864
10865    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10866        // Remove the parent package setting
10867        PackageSetting ps = (PackageSetting) pkg.mExtras;
10868        if (ps != null) {
10869            removePackageLI(ps, chatty);
10870        }
10871        // Remove the child package setting
10872        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10873        for (int i = 0; i < childCount; i++) {
10874            PackageParser.Package childPkg = pkg.childPackages.get(i);
10875            ps = (PackageSetting) childPkg.mExtras;
10876            if (ps != null) {
10877                removePackageLI(ps, chatty);
10878            }
10879        }
10880    }
10881
10882    void removePackageLI(PackageSetting ps, boolean chatty) {
10883        if (DEBUG_INSTALL) {
10884            if (chatty)
10885                Log.d(TAG, "Removing package " + ps.name);
10886        }
10887
10888        // writer
10889        synchronized (mPackages) {
10890            mPackages.remove(ps.name);
10891            final PackageParser.Package pkg = ps.pkg;
10892            if (pkg != null) {
10893                cleanPackageDataStructuresLILPw(pkg, chatty);
10894            }
10895        }
10896    }
10897
10898    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10899        if (DEBUG_INSTALL) {
10900            if (chatty)
10901                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10902        }
10903
10904        // writer
10905        synchronized (mPackages) {
10906            // Remove the parent package
10907            mPackages.remove(pkg.applicationInfo.packageName);
10908            cleanPackageDataStructuresLILPw(pkg, chatty);
10909
10910            // Remove the child packages
10911            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10912            for (int i = 0; i < childCount; i++) {
10913                PackageParser.Package childPkg = pkg.childPackages.get(i);
10914                mPackages.remove(childPkg.applicationInfo.packageName);
10915                cleanPackageDataStructuresLILPw(childPkg, chatty);
10916            }
10917        }
10918    }
10919
10920    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10921        int N = pkg.providers.size();
10922        StringBuilder r = null;
10923        int i;
10924        for (i=0; i<N; i++) {
10925            PackageParser.Provider p = pkg.providers.get(i);
10926            mProviders.removeProvider(p);
10927            if (p.info.authority == null) {
10928
10929                /* There was another ContentProvider with this authority when
10930                 * this app was installed so this authority is null,
10931                 * Ignore it as we don't have to unregister the provider.
10932                 */
10933                continue;
10934            }
10935            String names[] = p.info.authority.split(";");
10936            for (int j = 0; j < names.length; j++) {
10937                if (mProvidersByAuthority.get(names[j]) == p) {
10938                    mProvidersByAuthority.remove(names[j]);
10939                    if (DEBUG_REMOVE) {
10940                        if (chatty)
10941                            Log.d(TAG, "Unregistered content provider: " + names[j]
10942                                    + ", className = " + p.info.name + ", isSyncable = "
10943                                    + p.info.isSyncable);
10944                    }
10945                }
10946            }
10947            if (DEBUG_REMOVE && chatty) {
10948                if (r == null) {
10949                    r = new StringBuilder(256);
10950                } else {
10951                    r.append(' ');
10952                }
10953                r.append(p.info.name);
10954            }
10955        }
10956        if (r != null) {
10957            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10958        }
10959
10960        N = pkg.services.size();
10961        r = null;
10962        for (i=0; i<N; i++) {
10963            PackageParser.Service s = pkg.services.get(i);
10964            mServices.removeService(s);
10965            if (chatty) {
10966                if (r == null) {
10967                    r = new StringBuilder(256);
10968                } else {
10969                    r.append(' ');
10970                }
10971                r.append(s.info.name);
10972            }
10973        }
10974        if (r != null) {
10975            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10976        }
10977
10978        N = pkg.receivers.size();
10979        r = null;
10980        for (i=0; i<N; i++) {
10981            PackageParser.Activity a = pkg.receivers.get(i);
10982            mReceivers.removeActivity(a, "receiver");
10983            if (DEBUG_REMOVE && chatty) {
10984                if (r == null) {
10985                    r = new StringBuilder(256);
10986                } else {
10987                    r.append(' ');
10988                }
10989                r.append(a.info.name);
10990            }
10991        }
10992        if (r != null) {
10993            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10994        }
10995
10996        N = pkg.activities.size();
10997        r = null;
10998        for (i=0; i<N; i++) {
10999            PackageParser.Activity a = pkg.activities.get(i);
11000            mActivities.removeActivity(a, "activity");
11001            if (DEBUG_REMOVE && chatty) {
11002                if (r == null) {
11003                    r = new StringBuilder(256);
11004                } else {
11005                    r.append(' ');
11006                }
11007                r.append(a.info.name);
11008            }
11009        }
11010        if (r != null) {
11011            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11012        }
11013
11014        N = pkg.permissions.size();
11015        r = null;
11016        for (i=0; i<N; i++) {
11017            PackageParser.Permission p = pkg.permissions.get(i);
11018            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11019            if (bp == null) {
11020                bp = mSettings.mPermissionTrees.get(p.info.name);
11021            }
11022            if (bp != null && bp.perm == p) {
11023                bp.perm = null;
11024                if (DEBUG_REMOVE && chatty) {
11025                    if (r == null) {
11026                        r = new StringBuilder(256);
11027                    } else {
11028                        r.append(' ');
11029                    }
11030                    r.append(p.info.name);
11031                }
11032            }
11033            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11034                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11035                if (appOpPkgs != null) {
11036                    appOpPkgs.remove(pkg.packageName);
11037                }
11038            }
11039        }
11040        if (r != null) {
11041            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11042        }
11043
11044        N = pkg.requestedPermissions.size();
11045        r = null;
11046        for (i=0; i<N; i++) {
11047            String perm = pkg.requestedPermissions.get(i);
11048            BasePermission bp = mSettings.mPermissions.get(perm);
11049            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11050                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11051                if (appOpPkgs != null) {
11052                    appOpPkgs.remove(pkg.packageName);
11053                    if (appOpPkgs.isEmpty()) {
11054                        mAppOpPermissionPackages.remove(perm);
11055                    }
11056                }
11057            }
11058        }
11059        if (r != null) {
11060            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11061        }
11062
11063        N = pkg.instrumentation.size();
11064        r = null;
11065        for (i=0; i<N; i++) {
11066            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11067            mInstrumentation.remove(a.getComponentName());
11068            if (DEBUG_REMOVE && chatty) {
11069                if (r == null) {
11070                    r = new StringBuilder(256);
11071                } else {
11072                    r.append(' ');
11073                }
11074                r.append(a.info.name);
11075            }
11076        }
11077        if (r != null) {
11078            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11079        }
11080
11081        r = null;
11082        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11083            // Only system apps can hold shared libraries.
11084            if (pkg.libraryNames != null) {
11085                for (i = 0; i < pkg.libraryNames.size(); i++) {
11086                    String name = pkg.libraryNames.get(i);
11087                    if (removeSharedLibraryLPw(name, 0)) {
11088                        if (DEBUG_REMOVE && chatty) {
11089                            if (r == null) {
11090                                r = new StringBuilder(256);
11091                            } else {
11092                                r.append(' ');
11093                            }
11094                            r.append(name);
11095                        }
11096                    }
11097                }
11098            }
11099        }
11100
11101        r = null;
11102
11103        // Any package can hold static shared libraries.
11104        if (pkg.staticSharedLibName != null) {
11105            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11106                if (DEBUG_REMOVE && chatty) {
11107                    if (r == null) {
11108                        r = new StringBuilder(256);
11109                    } else {
11110                        r.append(' ');
11111                    }
11112                    r.append(pkg.staticSharedLibName);
11113                }
11114            }
11115        }
11116
11117        if (r != null) {
11118            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11119        }
11120    }
11121
11122    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11123        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11124            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11125                return true;
11126            }
11127        }
11128        return false;
11129    }
11130
11131    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11132    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11133    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11134
11135    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11136        // Update the parent permissions
11137        updatePermissionsLPw(pkg.packageName, pkg, flags);
11138        // Update the child permissions
11139        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11140        for (int i = 0; i < childCount; i++) {
11141            PackageParser.Package childPkg = pkg.childPackages.get(i);
11142            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11143        }
11144    }
11145
11146    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11147            int flags) {
11148        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11149        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11150    }
11151
11152    private void updatePermissionsLPw(String changingPkg,
11153            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11154        // Make sure there are no dangling permission trees.
11155        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11156        while (it.hasNext()) {
11157            final BasePermission bp = it.next();
11158            if (bp.packageSetting == null) {
11159                // We may not yet have parsed the package, so just see if
11160                // we still know about its settings.
11161                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11162            }
11163            if (bp.packageSetting == null) {
11164                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11165                        + " from package " + bp.sourcePackage);
11166                it.remove();
11167            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11168                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11169                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11170                            + " from package " + bp.sourcePackage);
11171                    flags |= UPDATE_PERMISSIONS_ALL;
11172                    it.remove();
11173                }
11174            }
11175        }
11176
11177        // Make sure all dynamic permissions have been assigned to a package,
11178        // and make sure there are no dangling permissions.
11179        it = mSettings.mPermissions.values().iterator();
11180        while (it.hasNext()) {
11181            final BasePermission bp = it.next();
11182            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11183                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11184                        + bp.name + " pkg=" + bp.sourcePackage
11185                        + " info=" + bp.pendingInfo);
11186                if (bp.packageSetting == null && bp.pendingInfo != null) {
11187                    final BasePermission tree = findPermissionTreeLP(bp.name);
11188                    if (tree != null && tree.perm != null) {
11189                        bp.packageSetting = tree.packageSetting;
11190                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11191                                new PermissionInfo(bp.pendingInfo));
11192                        bp.perm.info.packageName = tree.perm.info.packageName;
11193                        bp.perm.info.name = bp.name;
11194                        bp.uid = tree.uid;
11195                    }
11196                }
11197            }
11198            if (bp.packageSetting == null) {
11199                // We may not yet have parsed the package, so just see if
11200                // we still know about its settings.
11201                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11202            }
11203            if (bp.packageSetting == null) {
11204                Slog.w(TAG, "Removing dangling permission: " + bp.name
11205                        + " from package " + bp.sourcePackage);
11206                it.remove();
11207            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11208                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11209                    Slog.i(TAG, "Removing old permission: " + bp.name
11210                            + " from package " + bp.sourcePackage);
11211                    flags |= UPDATE_PERMISSIONS_ALL;
11212                    it.remove();
11213                }
11214            }
11215        }
11216
11217        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11218        // Now update the permissions for all packages, in particular
11219        // replace the granted permissions of the system packages.
11220        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11221            for (PackageParser.Package pkg : mPackages.values()) {
11222                if (pkg != pkgInfo) {
11223                    // Only replace for packages on requested volume
11224                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11225                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11226                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11227                    grantPermissionsLPw(pkg, replace, changingPkg);
11228                }
11229            }
11230        }
11231
11232        if (pkgInfo != null) {
11233            // Only replace for packages on requested volume
11234            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11235            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11236                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11237            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11238        }
11239        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11240    }
11241
11242    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11243            String packageOfInterest) {
11244        // IMPORTANT: There are two types of permissions: install and runtime.
11245        // Install time permissions are granted when the app is installed to
11246        // all device users and users added in the future. Runtime permissions
11247        // are granted at runtime explicitly to specific users. Normal and signature
11248        // protected permissions are install time permissions. Dangerous permissions
11249        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11250        // otherwise they are runtime permissions. This function does not manage
11251        // runtime permissions except for the case an app targeting Lollipop MR1
11252        // being upgraded to target a newer SDK, in which case dangerous permissions
11253        // are transformed from install time to runtime ones.
11254
11255        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11256        if (ps == null) {
11257            return;
11258        }
11259
11260        PermissionsState permissionsState = ps.getPermissionsState();
11261        PermissionsState origPermissions = permissionsState;
11262
11263        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11264
11265        boolean runtimePermissionsRevoked = false;
11266        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11267
11268        boolean changedInstallPermission = false;
11269
11270        if (replace) {
11271            ps.installPermissionsFixed = false;
11272            if (!ps.isSharedUser()) {
11273                origPermissions = new PermissionsState(permissionsState);
11274                permissionsState.reset();
11275            } else {
11276                // We need to know only about runtime permission changes since the
11277                // calling code always writes the install permissions state but
11278                // the runtime ones are written only if changed. The only cases of
11279                // changed runtime permissions here are promotion of an install to
11280                // runtime and revocation of a runtime from a shared user.
11281                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11282                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11283                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11284                    runtimePermissionsRevoked = true;
11285                }
11286            }
11287        }
11288
11289        permissionsState.setGlobalGids(mGlobalGids);
11290
11291        final int N = pkg.requestedPermissions.size();
11292        for (int i=0; i<N; i++) {
11293            final String name = pkg.requestedPermissions.get(i);
11294            final BasePermission bp = mSettings.mPermissions.get(name);
11295
11296            if (DEBUG_INSTALL) {
11297                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11298            }
11299
11300            if (bp == null || bp.packageSetting == null) {
11301                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11302                    Slog.w(TAG, "Unknown permission " + name
11303                            + " in package " + pkg.packageName);
11304                }
11305                continue;
11306            }
11307
11308
11309            // Limit ephemeral apps to ephemeral allowed permissions.
11310            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11311                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11312                        + pkg.packageName);
11313                continue;
11314            }
11315
11316            final String perm = bp.name;
11317            boolean allowedSig = false;
11318            int grant = GRANT_DENIED;
11319
11320            // Keep track of app op permissions.
11321            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11322                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11323                if (pkgs == null) {
11324                    pkgs = new ArraySet<>();
11325                    mAppOpPermissionPackages.put(bp.name, pkgs);
11326                }
11327                pkgs.add(pkg.packageName);
11328            }
11329
11330            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11331            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11332                    >= Build.VERSION_CODES.M;
11333            switch (level) {
11334                case PermissionInfo.PROTECTION_NORMAL: {
11335                    // For all apps normal permissions are install time ones.
11336                    grant = GRANT_INSTALL;
11337                } break;
11338
11339                case PermissionInfo.PROTECTION_DANGEROUS: {
11340                    // If a permission review is required for legacy apps we represent
11341                    // their permissions as always granted runtime ones since we need
11342                    // to keep the review required permission flag per user while an
11343                    // install permission's state is shared across all users.
11344                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11345                        // For legacy apps dangerous permissions are install time ones.
11346                        grant = GRANT_INSTALL;
11347                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11348                        // For legacy apps that became modern, install becomes runtime.
11349                        grant = GRANT_UPGRADE;
11350                    } else if (mPromoteSystemApps
11351                            && isSystemApp(ps)
11352                            && mExistingSystemPackages.contains(ps.name)) {
11353                        // For legacy system apps, install becomes runtime.
11354                        // We cannot check hasInstallPermission() for system apps since those
11355                        // permissions were granted implicitly and not persisted pre-M.
11356                        grant = GRANT_UPGRADE;
11357                    } else {
11358                        // For modern apps keep runtime permissions unchanged.
11359                        grant = GRANT_RUNTIME;
11360                    }
11361                } break;
11362
11363                case PermissionInfo.PROTECTION_SIGNATURE: {
11364                    // For all apps signature permissions are install time ones.
11365                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11366                    if (allowedSig) {
11367                        grant = GRANT_INSTALL;
11368                    }
11369                } break;
11370            }
11371
11372            if (DEBUG_INSTALL) {
11373                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11374            }
11375
11376            if (grant != GRANT_DENIED) {
11377                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11378                    // If this is an existing, non-system package, then
11379                    // we can't add any new permissions to it.
11380                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11381                        // Except...  if this is a permission that was added
11382                        // to the platform (note: need to only do this when
11383                        // updating the platform).
11384                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11385                            grant = GRANT_DENIED;
11386                        }
11387                    }
11388                }
11389
11390                switch (grant) {
11391                    case GRANT_INSTALL: {
11392                        // Revoke this as runtime permission to handle the case of
11393                        // a runtime permission being downgraded to an install one.
11394                        // Also in permission review mode we keep dangerous permissions
11395                        // for legacy apps
11396                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11397                            if (origPermissions.getRuntimePermissionState(
11398                                    bp.name, userId) != null) {
11399                                // Revoke the runtime permission and clear the flags.
11400                                origPermissions.revokeRuntimePermission(bp, userId);
11401                                origPermissions.updatePermissionFlags(bp, userId,
11402                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11403                                // If we revoked a permission permission, we have to write.
11404                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11405                                        changedRuntimePermissionUserIds, userId);
11406                            }
11407                        }
11408                        // Grant an install permission.
11409                        if (permissionsState.grantInstallPermission(bp) !=
11410                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11411                            changedInstallPermission = true;
11412                        }
11413                    } break;
11414
11415                    case GRANT_RUNTIME: {
11416                        // Grant previously granted runtime permissions.
11417                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11418                            PermissionState permissionState = origPermissions
11419                                    .getRuntimePermissionState(bp.name, userId);
11420                            int flags = permissionState != null
11421                                    ? permissionState.getFlags() : 0;
11422                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11423                                // Don't propagate the permission in a permission review mode if
11424                                // the former was revoked, i.e. marked to not propagate on upgrade.
11425                                // Note that in a permission review mode install permissions are
11426                                // represented as constantly granted runtime ones since we need to
11427                                // keep a per user state associated with the permission. Also the
11428                                // revoke on upgrade flag is no longer applicable and is reset.
11429                                final boolean revokeOnUpgrade = (flags & PackageManager
11430                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11431                                if (revokeOnUpgrade) {
11432                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11433                                    // Since we changed the flags, we have to write.
11434                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11435                                            changedRuntimePermissionUserIds, userId);
11436                                }
11437                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11438                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11439                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11440                                        // If we cannot put the permission as it was,
11441                                        // we have to write.
11442                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11443                                                changedRuntimePermissionUserIds, userId);
11444                                    }
11445                                }
11446
11447                                // If the app supports runtime permissions no need for a review.
11448                                if (mPermissionReviewRequired
11449                                        && appSupportsRuntimePermissions
11450                                        && (flags & PackageManager
11451                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11452                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11453                                    // Since we changed the flags, we have to write.
11454                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11455                                            changedRuntimePermissionUserIds, userId);
11456                                }
11457                            } else if (mPermissionReviewRequired
11458                                    && !appSupportsRuntimePermissions) {
11459                                // For legacy apps that need a permission review, every new
11460                                // runtime permission is granted but it is pending a review.
11461                                // We also need to review only platform defined runtime
11462                                // permissions as these are the only ones the platform knows
11463                                // how to disable the API to simulate revocation as legacy
11464                                // apps don't expect to run with revoked permissions.
11465                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11466                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11467                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11468                                        // We changed the flags, hence have to write.
11469                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11470                                                changedRuntimePermissionUserIds, userId);
11471                                    }
11472                                }
11473                                if (permissionsState.grantRuntimePermission(bp, userId)
11474                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11475                                    // We changed the permission, hence have to write.
11476                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11477                                            changedRuntimePermissionUserIds, userId);
11478                                }
11479                            }
11480                            // Propagate the permission flags.
11481                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11482                        }
11483                    } break;
11484
11485                    case GRANT_UPGRADE: {
11486                        // Grant runtime permissions for a previously held install permission.
11487                        PermissionState permissionState = origPermissions
11488                                .getInstallPermissionState(bp.name);
11489                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11490
11491                        if (origPermissions.revokeInstallPermission(bp)
11492                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11493                            // We will be transferring the permission flags, so clear them.
11494                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11495                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11496                            changedInstallPermission = true;
11497                        }
11498
11499                        // If the permission is not to be promoted to runtime we ignore it and
11500                        // also its other flags as they are not applicable to install permissions.
11501                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11502                            for (int userId : currentUserIds) {
11503                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11504                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11505                                    // Transfer the permission flags.
11506                                    permissionsState.updatePermissionFlags(bp, userId,
11507                                            flags, flags);
11508                                    // If we granted the permission, we have to write.
11509                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11510                                            changedRuntimePermissionUserIds, userId);
11511                                }
11512                            }
11513                        }
11514                    } break;
11515
11516                    default: {
11517                        if (packageOfInterest == null
11518                                || packageOfInterest.equals(pkg.packageName)) {
11519                            Slog.w(TAG, "Not granting permission " + perm
11520                                    + " to package " + pkg.packageName
11521                                    + " because it was previously installed without");
11522                        }
11523                    } break;
11524                }
11525            } else {
11526                if (permissionsState.revokeInstallPermission(bp) !=
11527                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11528                    // Also drop the permission flags.
11529                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11530                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11531                    changedInstallPermission = true;
11532                    Slog.i(TAG, "Un-granting permission " + perm
11533                            + " from package " + pkg.packageName
11534                            + " (protectionLevel=" + bp.protectionLevel
11535                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11536                            + ")");
11537                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11538                    // Don't print warning for app op permissions, since it is fine for them
11539                    // not to be granted, there is a UI for the user to decide.
11540                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11541                        Slog.w(TAG, "Not granting permission " + perm
11542                                + " to package " + pkg.packageName
11543                                + " (protectionLevel=" + bp.protectionLevel
11544                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11545                                + ")");
11546                    }
11547                }
11548            }
11549        }
11550
11551        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11552                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11553            // This is the first that we have heard about this package, so the
11554            // permissions we have now selected are fixed until explicitly
11555            // changed.
11556            ps.installPermissionsFixed = true;
11557        }
11558
11559        // Persist the runtime permissions state for users with changes. If permissions
11560        // were revoked because no app in the shared user declares them we have to
11561        // write synchronously to avoid losing runtime permissions state.
11562        for (int userId : changedRuntimePermissionUserIds) {
11563            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11564        }
11565    }
11566
11567    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11568        boolean allowed = false;
11569        final int NP = PackageParser.NEW_PERMISSIONS.length;
11570        for (int ip=0; ip<NP; ip++) {
11571            final PackageParser.NewPermissionInfo npi
11572                    = PackageParser.NEW_PERMISSIONS[ip];
11573            if (npi.name.equals(perm)
11574                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11575                allowed = true;
11576                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11577                        + pkg.packageName);
11578                break;
11579            }
11580        }
11581        return allowed;
11582    }
11583
11584    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11585            BasePermission bp, PermissionsState origPermissions) {
11586        boolean privilegedPermission = (bp.protectionLevel
11587                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11588        boolean privappPermissionsDisable =
11589                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11590        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11591        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11592        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11593                && !platformPackage && platformPermission) {
11594            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11595                    .getPrivAppPermissions(pkg.packageName);
11596            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11597            if (!whitelisted) {
11598                Slog.w(TAG, "Privileged permission " + perm + " for package "
11599                        + pkg.packageName + " - not in privapp-permissions whitelist");
11600                // Only report violations for apps on system image
11601                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11602                    if (mPrivappPermissionsViolations == null) {
11603                        mPrivappPermissionsViolations = new ArraySet<>();
11604                    }
11605                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11606                }
11607                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11608                    return false;
11609                }
11610            }
11611        }
11612        boolean allowed = (compareSignatures(
11613                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11614                        == PackageManager.SIGNATURE_MATCH)
11615                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11616                        == PackageManager.SIGNATURE_MATCH);
11617        if (!allowed && privilegedPermission) {
11618            if (isSystemApp(pkg)) {
11619                // For updated system applications, a system permission
11620                // is granted only if it had been defined by the original application.
11621                if (pkg.isUpdatedSystemApp()) {
11622                    final PackageSetting sysPs = mSettings
11623                            .getDisabledSystemPkgLPr(pkg.packageName);
11624                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11625                        // If the original was granted this permission, we take
11626                        // that grant decision as read and propagate it to the
11627                        // update.
11628                        if (sysPs.isPrivileged()) {
11629                            allowed = true;
11630                        }
11631                    } else {
11632                        // The system apk may have been updated with an older
11633                        // version of the one on the data partition, but which
11634                        // granted a new system permission that it didn't have
11635                        // before.  In this case we do want to allow the app to
11636                        // now get the new permission if the ancestral apk is
11637                        // privileged to get it.
11638                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11639                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11640                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11641                                    allowed = true;
11642                                    break;
11643                                }
11644                            }
11645                        }
11646                        // Also if a privileged parent package on the system image or any of
11647                        // its children requested a privileged permission, the updated child
11648                        // packages can also get the permission.
11649                        if (pkg.parentPackage != null) {
11650                            final PackageSetting disabledSysParentPs = mSettings
11651                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11652                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11653                                    && disabledSysParentPs.isPrivileged()) {
11654                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11655                                    allowed = true;
11656                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11657                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11658                                    for (int i = 0; i < count; i++) {
11659                                        PackageParser.Package disabledSysChildPkg =
11660                                                disabledSysParentPs.pkg.childPackages.get(i);
11661                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11662                                                perm)) {
11663                                            allowed = true;
11664                                            break;
11665                                        }
11666                                    }
11667                                }
11668                            }
11669                        }
11670                    }
11671                } else {
11672                    allowed = isPrivilegedApp(pkg);
11673                }
11674            }
11675        }
11676        if (!allowed) {
11677            if (!allowed && (bp.protectionLevel
11678                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11679                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11680                // If this was a previously normal/dangerous permission that got moved
11681                // to a system permission as part of the runtime permission redesign, then
11682                // we still want to blindly grant it to old apps.
11683                allowed = true;
11684            }
11685            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11686                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11687                // If this permission is to be granted to the system installer and
11688                // this app is an installer, then it gets the permission.
11689                allowed = true;
11690            }
11691            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11692                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11693                // If this permission is to be granted to the system verifier and
11694                // this app is a verifier, then it gets the permission.
11695                allowed = true;
11696            }
11697            if (!allowed && (bp.protectionLevel
11698                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11699                    && isSystemApp(pkg)) {
11700                // Any pre-installed system app is allowed to get this permission.
11701                allowed = true;
11702            }
11703            if (!allowed && (bp.protectionLevel
11704                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11705                // For development permissions, a development permission
11706                // is granted only if it was already granted.
11707                allowed = origPermissions.hasInstallPermission(perm);
11708            }
11709            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11710                    && pkg.packageName.equals(mSetupWizardPackage)) {
11711                // If this permission is to be granted to the system setup wizard and
11712                // this app is a setup wizard, then it gets the permission.
11713                allowed = true;
11714            }
11715        }
11716        return allowed;
11717    }
11718
11719    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11720        final int permCount = pkg.requestedPermissions.size();
11721        for (int j = 0; j < permCount; j++) {
11722            String requestedPermission = pkg.requestedPermissions.get(j);
11723            if (permission.equals(requestedPermission)) {
11724                return true;
11725            }
11726        }
11727        return false;
11728    }
11729
11730    final class ActivityIntentResolver
11731            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11732        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11733                boolean defaultOnly, int userId) {
11734            if (!sUserManager.exists(userId)) return null;
11735            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11736            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11737        }
11738
11739        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11740                int userId) {
11741            if (!sUserManager.exists(userId)) return null;
11742            mFlags = flags;
11743            return super.queryIntent(intent, resolvedType,
11744                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11745                    userId);
11746        }
11747
11748        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11749                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11750            if (!sUserManager.exists(userId)) return null;
11751            if (packageActivities == null) {
11752                return null;
11753            }
11754            mFlags = flags;
11755            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11756            final int N = packageActivities.size();
11757            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11758                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11759
11760            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11761            for (int i = 0; i < N; ++i) {
11762                intentFilters = packageActivities.get(i).intents;
11763                if (intentFilters != null && intentFilters.size() > 0) {
11764                    PackageParser.ActivityIntentInfo[] array =
11765                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11766                    intentFilters.toArray(array);
11767                    listCut.add(array);
11768                }
11769            }
11770            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11771        }
11772
11773        /**
11774         * Finds a privileged activity that matches the specified activity names.
11775         */
11776        private PackageParser.Activity findMatchingActivity(
11777                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11778            for (PackageParser.Activity sysActivity : activityList) {
11779                if (sysActivity.info.name.equals(activityInfo.name)) {
11780                    return sysActivity;
11781                }
11782                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11783                    return sysActivity;
11784                }
11785                if (sysActivity.info.targetActivity != null) {
11786                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11787                        return sysActivity;
11788                    }
11789                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11790                        return sysActivity;
11791                    }
11792                }
11793            }
11794            return null;
11795        }
11796
11797        public class IterGenerator<E> {
11798            public Iterator<E> generate(ActivityIntentInfo info) {
11799                return null;
11800            }
11801        }
11802
11803        public class ActionIterGenerator extends IterGenerator<String> {
11804            @Override
11805            public Iterator<String> generate(ActivityIntentInfo info) {
11806                return info.actionsIterator();
11807            }
11808        }
11809
11810        public class CategoriesIterGenerator extends IterGenerator<String> {
11811            @Override
11812            public Iterator<String> generate(ActivityIntentInfo info) {
11813                return info.categoriesIterator();
11814            }
11815        }
11816
11817        public class SchemesIterGenerator extends IterGenerator<String> {
11818            @Override
11819            public Iterator<String> generate(ActivityIntentInfo info) {
11820                return info.schemesIterator();
11821            }
11822        }
11823
11824        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11825            @Override
11826            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11827                return info.authoritiesIterator();
11828            }
11829        }
11830
11831        /**
11832         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11833         * MODIFIED. Do not pass in a list that should not be changed.
11834         */
11835        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11836                IterGenerator<T> generator, Iterator<T> searchIterator) {
11837            // loop through the set of actions; every one must be found in the intent filter
11838            while (searchIterator.hasNext()) {
11839                // we must have at least one filter in the list to consider a match
11840                if (intentList.size() == 0) {
11841                    break;
11842                }
11843
11844                final T searchAction = searchIterator.next();
11845
11846                // loop through the set of intent filters
11847                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11848                while (intentIter.hasNext()) {
11849                    final ActivityIntentInfo intentInfo = intentIter.next();
11850                    boolean selectionFound = false;
11851
11852                    // loop through the intent filter's selection criteria; at least one
11853                    // of them must match the searched criteria
11854                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11855                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11856                        final T intentSelection = intentSelectionIter.next();
11857                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11858                            selectionFound = true;
11859                            break;
11860                        }
11861                    }
11862
11863                    // the selection criteria wasn't found in this filter's set; this filter
11864                    // is not a potential match
11865                    if (!selectionFound) {
11866                        intentIter.remove();
11867                    }
11868                }
11869            }
11870        }
11871
11872        private boolean isProtectedAction(ActivityIntentInfo filter) {
11873            final Iterator<String> actionsIter = filter.actionsIterator();
11874            while (actionsIter != null && actionsIter.hasNext()) {
11875                final String filterAction = actionsIter.next();
11876                if (PROTECTED_ACTIONS.contains(filterAction)) {
11877                    return true;
11878                }
11879            }
11880            return false;
11881        }
11882
11883        /**
11884         * Adjusts the priority of the given intent filter according to policy.
11885         * <p>
11886         * <ul>
11887         * <li>The priority for non privileged applications is capped to '0'</li>
11888         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11889         * <li>The priority for unbundled updates to privileged applications is capped to the
11890         *      priority defined on the system partition</li>
11891         * </ul>
11892         * <p>
11893         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11894         * allowed to obtain any priority on any action.
11895         */
11896        private void adjustPriority(
11897                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11898            // nothing to do; priority is fine as-is
11899            if (intent.getPriority() <= 0) {
11900                return;
11901            }
11902
11903            final ActivityInfo activityInfo = intent.activity.info;
11904            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11905
11906            final boolean privilegedApp =
11907                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11908            if (!privilegedApp) {
11909                // non-privileged applications can never define a priority >0
11910                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11911                        + " package: " + applicationInfo.packageName
11912                        + " activity: " + intent.activity.className
11913                        + " origPrio: " + intent.getPriority());
11914                intent.setPriority(0);
11915                return;
11916            }
11917
11918            if (systemActivities == null) {
11919                // the system package is not disabled; we're parsing the system partition
11920                if (isProtectedAction(intent)) {
11921                    if (mDeferProtectedFilters) {
11922                        // We can't deal with these just yet. No component should ever obtain a
11923                        // >0 priority for a protected actions, with ONE exception -- the setup
11924                        // wizard. The setup wizard, however, cannot be known until we're able to
11925                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11926                        // until all intent filters have been processed. Chicken, meet egg.
11927                        // Let the filter temporarily have a high priority and rectify the
11928                        // priorities after all system packages have been scanned.
11929                        mProtectedFilters.add(intent);
11930                        if (DEBUG_FILTERS) {
11931                            Slog.i(TAG, "Protected action; save for later;"
11932                                    + " package: " + applicationInfo.packageName
11933                                    + " activity: " + intent.activity.className
11934                                    + " origPrio: " + intent.getPriority());
11935                        }
11936                        return;
11937                    } else {
11938                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11939                            Slog.i(TAG, "No setup wizard;"
11940                                + " All protected intents capped to priority 0");
11941                        }
11942                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11943                            if (DEBUG_FILTERS) {
11944                                Slog.i(TAG, "Found setup wizard;"
11945                                    + " allow priority " + intent.getPriority() + ";"
11946                                    + " package: " + intent.activity.info.packageName
11947                                    + " activity: " + intent.activity.className
11948                                    + " priority: " + intent.getPriority());
11949                            }
11950                            // setup wizard gets whatever it wants
11951                            return;
11952                        }
11953                        Slog.w(TAG, "Protected action; cap priority to 0;"
11954                                + " package: " + intent.activity.info.packageName
11955                                + " activity: " + intent.activity.className
11956                                + " origPrio: " + intent.getPriority());
11957                        intent.setPriority(0);
11958                        return;
11959                    }
11960                }
11961                // privileged apps on the system image get whatever priority they request
11962                return;
11963            }
11964
11965            // privileged app unbundled update ... try to find the same activity
11966            final PackageParser.Activity foundActivity =
11967                    findMatchingActivity(systemActivities, activityInfo);
11968            if (foundActivity == null) {
11969                // this is a new activity; it cannot obtain >0 priority
11970                if (DEBUG_FILTERS) {
11971                    Slog.i(TAG, "New activity; cap priority to 0;"
11972                            + " package: " + applicationInfo.packageName
11973                            + " activity: " + intent.activity.className
11974                            + " origPrio: " + intent.getPriority());
11975                }
11976                intent.setPriority(0);
11977                return;
11978            }
11979
11980            // found activity, now check for filter equivalence
11981
11982            // a shallow copy is enough; we modify the list, not its contents
11983            final List<ActivityIntentInfo> intentListCopy =
11984                    new ArrayList<>(foundActivity.intents);
11985            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11986
11987            // find matching action subsets
11988            final Iterator<String> actionsIterator = intent.actionsIterator();
11989            if (actionsIterator != null) {
11990                getIntentListSubset(
11991                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11992                if (intentListCopy.size() == 0) {
11993                    // no more intents to match; we're not equivalent
11994                    if (DEBUG_FILTERS) {
11995                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11996                                + " package: " + applicationInfo.packageName
11997                                + " activity: " + intent.activity.className
11998                                + " origPrio: " + intent.getPriority());
11999                    }
12000                    intent.setPriority(0);
12001                    return;
12002                }
12003            }
12004
12005            // find matching category subsets
12006            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12007            if (categoriesIterator != null) {
12008                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12009                        categoriesIterator);
12010                if (intentListCopy.size() == 0) {
12011                    // no more intents to match; we're not equivalent
12012                    if (DEBUG_FILTERS) {
12013                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12014                                + " package: " + applicationInfo.packageName
12015                                + " activity: " + intent.activity.className
12016                                + " origPrio: " + intent.getPriority());
12017                    }
12018                    intent.setPriority(0);
12019                    return;
12020                }
12021            }
12022
12023            // find matching schemes subsets
12024            final Iterator<String> schemesIterator = intent.schemesIterator();
12025            if (schemesIterator != null) {
12026                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12027                        schemesIterator);
12028                if (intentListCopy.size() == 0) {
12029                    // no more intents to match; we're not equivalent
12030                    if (DEBUG_FILTERS) {
12031                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12032                                + " package: " + applicationInfo.packageName
12033                                + " activity: " + intent.activity.className
12034                                + " origPrio: " + intent.getPriority());
12035                    }
12036                    intent.setPriority(0);
12037                    return;
12038                }
12039            }
12040
12041            // find matching authorities subsets
12042            final Iterator<IntentFilter.AuthorityEntry>
12043                    authoritiesIterator = intent.authoritiesIterator();
12044            if (authoritiesIterator != null) {
12045                getIntentListSubset(intentListCopy,
12046                        new AuthoritiesIterGenerator(),
12047                        authoritiesIterator);
12048                if (intentListCopy.size() == 0) {
12049                    // no more intents to match; we're not equivalent
12050                    if (DEBUG_FILTERS) {
12051                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12052                                + " package: " + applicationInfo.packageName
12053                                + " activity: " + intent.activity.className
12054                                + " origPrio: " + intent.getPriority());
12055                    }
12056                    intent.setPriority(0);
12057                    return;
12058                }
12059            }
12060
12061            // we found matching filter(s); app gets the max priority of all intents
12062            int cappedPriority = 0;
12063            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12064                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12065            }
12066            if (intent.getPriority() > cappedPriority) {
12067                if (DEBUG_FILTERS) {
12068                    Slog.i(TAG, "Found matching filter(s);"
12069                            + " cap priority to " + cappedPriority + ";"
12070                            + " package: " + applicationInfo.packageName
12071                            + " activity: " + intent.activity.className
12072                            + " origPrio: " + intent.getPriority());
12073                }
12074                intent.setPriority(cappedPriority);
12075                return;
12076            }
12077            // all this for nothing; the requested priority was <= what was on the system
12078        }
12079
12080        public final void addActivity(PackageParser.Activity a, String type) {
12081            mActivities.put(a.getComponentName(), a);
12082            if (DEBUG_SHOW_INFO)
12083                Log.v(
12084                TAG, "  " + type + " " +
12085                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12086            if (DEBUG_SHOW_INFO)
12087                Log.v(TAG, "    Class=" + a.info.name);
12088            final int NI = a.intents.size();
12089            for (int j=0; j<NI; j++) {
12090                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12091                if ("activity".equals(type)) {
12092                    final PackageSetting ps =
12093                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12094                    final List<PackageParser.Activity> systemActivities =
12095                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12096                    adjustPriority(systemActivities, intent);
12097                }
12098                if (DEBUG_SHOW_INFO) {
12099                    Log.v(TAG, "    IntentFilter:");
12100                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12101                }
12102                if (!intent.debugCheck()) {
12103                    Log.w(TAG, "==> For Activity " + a.info.name);
12104                }
12105                addFilter(intent);
12106            }
12107        }
12108
12109        public final void removeActivity(PackageParser.Activity a, String type) {
12110            mActivities.remove(a.getComponentName());
12111            if (DEBUG_SHOW_INFO) {
12112                Log.v(TAG, "  " + type + " "
12113                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12114                                : a.info.name) + ":");
12115                Log.v(TAG, "    Class=" + a.info.name);
12116            }
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 (DEBUG_SHOW_INFO) {
12121                    Log.v(TAG, "    IntentFilter:");
12122                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12123                }
12124                removeFilter(intent);
12125            }
12126        }
12127
12128        @Override
12129        protected boolean allowFilterResult(
12130                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12131            ActivityInfo filterAi = filter.activity.info;
12132            for (int i=dest.size()-1; i>=0; i--) {
12133                ActivityInfo destAi = dest.get(i).activityInfo;
12134                if (destAi.name == filterAi.name
12135                        && destAi.packageName == filterAi.packageName) {
12136                    return false;
12137                }
12138            }
12139            return true;
12140        }
12141
12142        @Override
12143        protected ActivityIntentInfo[] newArray(int size) {
12144            return new ActivityIntentInfo[size];
12145        }
12146
12147        @Override
12148        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12149            if (!sUserManager.exists(userId)) return true;
12150            PackageParser.Package p = filter.activity.owner;
12151            if (p != null) {
12152                PackageSetting ps = (PackageSetting)p.mExtras;
12153                if (ps != null) {
12154                    // System apps are never considered stopped for purposes of
12155                    // filtering, because there may be no way for the user to
12156                    // actually re-launch them.
12157                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12158                            && ps.getStopped(userId);
12159                }
12160            }
12161            return false;
12162        }
12163
12164        @Override
12165        protected boolean isPackageForFilter(String packageName,
12166                PackageParser.ActivityIntentInfo info) {
12167            return packageName.equals(info.activity.owner.packageName);
12168        }
12169
12170        @Override
12171        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12172                int match, int userId) {
12173            if (!sUserManager.exists(userId)) return null;
12174            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12175                return null;
12176            }
12177            final PackageParser.Activity activity = info.activity;
12178            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12179            if (ps == null) {
12180                return null;
12181            }
12182            final PackageUserState userState = ps.readUserState(userId);
12183            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12184                    userState, userId);
12185            if (ai == null) {
12186                return null;
12187            }
12188            final boolean matchVisibleToInstantApp =
12189                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12190            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12191            // throw out filters that aren't visible to ephemeral apps
12192            if (matchVisibleToInstantApp
12193                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12194                return null;
12195            }
12196            // throw out ephemeral filters if we're not explicitly requesting them
12197            if (!isInstantApp && userState.instantApp) {
12198                return null;
12199            }
12200            // throw out instant app filters if updates are available; will trigger
12201            // instant app resolution
12202            if (userState.instantApp && ps.isUpdateAvailable()) {
12203                return null;
12204            }
12205            final ResolveInfo res = new ResolveInfo();
12206            res.activityInfo = ai;
12207            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12208                res.filter = info;
12209            }
12210            if (info != null) {
12211                res.handleAllWebDataURI = info.handleAllWebDataURI();
12212            }
12213            res.priority = info.getPriority();
12214            res.preferredOrder = activity.owner.mPreferredOrder;
12215            //System.out.println("Result: " + res.activityInfo.className +
12216            //                   " = " + res.priority);
12217            res.match = match;
12218            res.isDefault = info.hasDefault;
12219            res.labelRes = info.labelRes;
12220            res.nonLocalizedLabel = info.nonLocalizedLabel;
12221            if (userNeedsBadging(userId)) {
12222                res.noResourceId = true;
12223            } else {
12224                res.icon = info.icon;
12225            }
12226            res.iconResourceId = info.icon;
12227            res.system = res.activityInfo.applicationInfo.isSystemApp();
12228            res.instantAppAvailable = userState.instantApp;
12229            return res;
12230        }
12231
12232        @Override
12233        protected void sortResults(List<ResolveInfo> results) {
12234            Collections.sort(results, mResolvePrioritySorter);
12235        }
12236
12237        @Override
12238        protected void dumpFilter(PrintWriter out, String prefix,
12239                PackageParser.ActivityIntentInfo filter) {
12240            out.print(prefix); out.print(
12241                    Integer.toHexString(System.identityHashCode(filter.activity)));
12242                    out.print(' ');
12243                    filter.activity.printComponentShortName(out);
12244                    out.print(" filter ");
12245                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12246        }
12247
12248        @Override
12249        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12250            return filter.activity;
12251        }
12252
12253        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12254            PackageParser.Activity activity = (PackageParser.Activity)label;
12255            out.print(prefix); out.print(
12256                    Integer.toHexString(System.identityHashCode(activity)));
12257                    out.print(' ');
12258                    activity.printComponentShortName(out);
12259            if (count > 1) {
12260                out.print(" ("); out.print(count); out.print(" filters)");
12261            }
12262            out.println();
12263        }
12264
12265        // Keys are String (activity class name), values are Activity.
12266        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12267                = new ArrayMap<ComponentName, PackageParser.Activity>();
12268        private int mFlags;
12269    }
12270
12271    private final class ServiceIntentResolver
12272            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12273        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12274                boolean defaultOnly, int userId) {
12275            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12276            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12277        }
12278
12279        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12280                int userId) {
12281            if (!sUserManager.exists(userId)) return null;
12282            mFlags = flags;
12283            return super.queryIntent(intent, resolvedType,
12284                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12285                    userId);
12286        }
12287
12288        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12289                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12290            if (!sUserManager.exists(userId)) return null;
12291            if (packageServices == null) {
12292                return null;
12293            }
12294            mFlags = flags;
12295            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12296            final int N = packageServices.size();
12297            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12298                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12299
12300            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12301            for (int i = 0; i < N; ++i) {
12302                intentFilters = packageServices.get(i).intents;
12303                if (intentFilters != null && intentFilters.size() > 0) {
12304                    PackageParser.ServiceIntentInfo[] array =
12305                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12306                    intentFilters.toArray(array);
12307                    listCut.add(array);
12308                }
12309            }
12310            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12311        }
12312
12313        public final void addService(PackageParser.Service s) {
12314            mServices.put(s.getComponentName(), s);
12315            if (DEBUG_SHOW_INFO) {
12316                Log.v(TAG, "  "
12317                        + (s.info.nonLocalizedLabel != null
12318                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12319                Log.v(TAG, "    Class=" + s.info.name);
12320            }
12321            final int NI = s.intents.size();
12322            int j;
12323            for (j=0; j<NI; j++) {
12324                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12325                if (DEBUG_SHOW_INFO) {
12326                    Log.v(TAG, "    IntentFilter:");
12327                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12328                }
12329                if (!intent.debugCheck()) {
12330                    Log.w(TAG, "==> For Service " + s.info.name);
12331                }
12332                addFilter(intent);
12333            }
12334        }
12335
12336        public final void removeService(PackageParser.Service s) {
12337            mServices.remove(s.getComponentName());
12338            if (DEBUG_SHOW_INFO) {
12339                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12340                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12341                Log.v(TAG, "    Class=" + s.info.name);
12342            }
12343            final int NI = s.intents.size();
12344            int j;
12345            for (j=0; j<NI; j++) {
12346                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12347                if (DEBUG_SHOW_INFO) {
12348                    Log.v(TAG, "    IntentFilter:");
12349                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12350                }
12351                removeFilter(intent);
12352            }
12353        }
12354
12355        @Override
12356        protected boolean allowFilterResult(
12357                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12358            ServiceInfo filterSi = filter.service.info;
12359            for (int i=dest.size()-1; i>=0; i--) {
12360                ServiceInfo destAi = dest.get(i).serviceInfo;
12361                if (destAi.name == filterSi.name
12362                        && destAi.packageName == filterSi.packageName) {
12363                    return false;
12364                }
12365            }
12366            return true;
12367        }
12368
12369        @Override
12370        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12371            return new PackageParser.ServiceIntentInfo[size];
12372        }
12373
12374        @Override
12375        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12376            if (!sUserManager.exists(userId)) return true;
12377            PackageParser.Package p = filter.service.owner;
12378            if (p != null) {
12379                PackageSetting ps = (PackageSetting)p.mExtras;
12380                if (ps != null) {
12381                    // System apps are never considered stopped for purposes of
12382                    // filtering, because there may be no way for the user to
12383                    // actually re-launch them.
12384                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12385                            && ps.getStopped(userId);
12386                }
12387            }
12388            return false;
12389        }
12390
12391        @Override
12392        protected boolean isPackageForFilter(String packageName,
12393                PackageParser.ServiceIntentInfo info) {
12394            return packageName.equals(info.service.owner.packageName);
12395        }
12396
12397        @Override
12398        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12399                int match, int userId) {
12400            if (!sUserManager.exists(userId)) return null;
12401            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12402            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12403                return null;
12404            }
12405            final PackageParser.Service service = info.service;
12406            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12407            if (ps == null) {
12408                return null;
12409            }
12410            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12411                    ps.readUserState(userId), userId);
12412            if (si == null) {
12413                return null;
12414            }
12415            final ResolveInfo res = new ResolveInfo();
12416            res.serviceInfo = si;
12417            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12418                res.filter = filter;
12419            }
12420            res.priority = info.getPriority();
12421            res.preferredOrder = service.owner.mPreferredOrder;
12422            res.match = match;
12423            res.isDefault = info.hasDefault;
12424            res.labelRes = info.labelRes;
12425            res.nonLocalizedLabel = info.nonLocalizedLabel;
12426            res.icon = info.icon;
12427            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12428            return res;
12429        }
12430
12431        @Override
12432        protected void sortResults(List<ResolveInfo> results) {
12433            Collections.sort(results, mResolvePrioritySorter);
12434        }
12435
12436        @Override
12437        protected void dumpFilter(PrintWriter out, String prefix,
12438                PackageParser.ServiceIntentInfo filter) {
12439            out.print(prefix); out.print(
12440                    Integer.toHexString(System.identityHashCode(filter.service)));
12441                    out.print(' ');
12442                    filter.service.printComponentShortName(out);
12443                    out.print(" filter ");
12444                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12445        }
12446
12447        @Override
12448        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12449            return filter.service;
12450        }
12451
12452        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12453            PackageParser.Service service = (PackageParser.Service)label;
12454            out.print(prefix); out.print(
12455                    Integer.toHexString(System.identityHashCode(service)));
12456                    out.print(' ');
12457                    service.printComponentShortName(out);
12458            if (count > 1) {
12459                out.print(" ("); out.print(count); out.print(" filters)");
12460            }
12461            out.println();
12462        }
12463
12464//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12465//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12466//            final List<ResolveInfo> retList = Lists.newArrayList();
12467//            while (i.hasNext()) {
12468//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12469//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12470//                    retList.add(resolveInfo);
12471//                }
12472//            }
12473//            return retList;
12474//        }
12475
12476        // Keys are String (activity class name), values are Activity.
12477        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12478                = new ArrayMap<ComponentName, PackageParser.Service>();
12479        private int mFlags;
12480    }
12481
12482    private final class ProviderIntentResolver
12483            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12484        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12485                boolean defaultOnly, int userId) {
12486            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12487            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12488        }
12489
12490        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12491                int userId) {
12492            if (!sUserManager.exists(userId))
12493                return null;
12494            mFlags = flags;
12495            return super.queryIntent(intent, resolvedType,
12496                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12497                    userId);
12498        }
12499
12500        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12501                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12502            if (!sUserManager.exists(userId))
12503                return null;
12504            if (packageProviders == null) {
12505                return null;
12506            }
12507            mFlags = flags;
12508            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12509            final int N = packageProviders.size();
12510            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12511                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12512
12513            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12514            for (int i = 0; i < N; ++i) {
12515                intentFilters = packageProviders.get(i).intents;
12516                if (intentFilters != null && intentFilters.size() > 0) {
12517                    PackageParser.ProviderIntentInfo[] array =
12518                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12519                    intentFilters.toArray(array);
12520                    listCut.add(array);
12521                }
12522            }
12523            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12524        }
12525
12526        public final void addProvider(PackageParser.Provider p) {
12527            if (mProviders.containsKey(p.getComponentName())) {
12528                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12529                return;
12530            }
12531
12532            mProviders.put(p.getComponentName(), p);
12533            if (DEBUG_SHOW_INFO) {
12534                Log.v(TAG, "  "
12535                        + (p.info.nonLocalizedLabel != null
12536                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12537                Log.v(TAG, "    Class=" + p.info.name);
12538            }
12539            final int NI = p.intents.size();
12540            int j;
12541            for (j = 0; j < NI; j++) {
12542                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12543                if (DEBUG_SHOW_INFO) {
12544                    Log.v(TAG, "    IntentFilter:");
12545                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12546                }
12547                if (!intent.debugCheck()) {
12548                    Log.w(TAG, "==> For Provider " + p.info.name);
12549                }
12550                addFilter(intent);
12551            }
12552        }
12553
12554        public final void removeProvider(PackageParser.Provider p) {
12555            mProviders.remove(p.getComponentName());
12556            if (DEBUG_SHOW_INFO) {
12557                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12558                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12559                Log.v(TAG, "    Class=" + p.info.name);
12560            }
12561            final int NI = p.intents.size();
12562            int j;
12563            for (j = 0; j < NI; j++) {
12564                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12565                if (DEBUG_SHOW_INFO) {
12566                    Log.v(TAG, "    IntentFilter:");
12567                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12568                }
12569                removeFilter(intent);
12570            }
12571        }
12572
12573        @Override
12574        protected boolean allowFilterResult(
12575                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12576            ProviderInfo filterPi = filter.provider.info;
12577            for (int i = dest.size() - 1; i >= 0; i--) {
12578                ProviderInfo destPi = dest.get(i).providerInfo;
12579                if (destPi.name == filterPi.name
12580                        && destPi.packageName == filterPi.packageName) {
12581                    return false;
12582                }
12583            }
12584            return true;
12585        }
12586
12587        @Override
12588        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12589            return new PackageParser.ProviderIntentInfo[size];
12590        }
12591
12592        @Override
12593        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12594            if (!sUserManager.exists(userId))
12595                return true;
12596            PackageParser.Package p = filter.provider.owner;
12597            if (p != null) {
12598                PackageSetting ps = (PackageSetting) p.mExtras;
12599                if (ps != null) {
12600                    // System apps are never considered stopped for purposes of
12601                    // filtering, because there may be no way for the user to
12602                    // actually re-launch them.
12603                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12604                            && ps.getStopped(userId);
12605                }
12606            }
12607            return false;
12608        }
12609
12610        @Override
12611        protected boolean isPackageForFilter(String packageName,
12612                PackageParser.ProviderIntentInfo info) {
12613            return packageName.equals(info.provider.owner.packageName);
12614        }
12615
12616        @Override
12617        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12618                int match, int userId) {
12619            if (!sUserManager.exists(userId))
12620                return null;
12621            final PackageParser.ProviderIntentInfo info = filter;
12622            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12623                return null;
12624            }
12625            final PackageParser.Provider provider = info.provider;
12626            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12627            if (ps == null) {
12628                return null;
12629            }
12630            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12631                    ps.readUserState(userId), userId);
12632            if (pi == null) {
12633                return null;
12634            }
12635            final ResolveInfo res = new ResolveInfo();
12636            res.providerInfo = pi;
12637            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12638                res.filter = filter;
12639            }
12640            res.priority = info.getPriority();
12641            res.preferredOrder = provider.owner.mPreferredOrder;
12642            res.match = match;
12643            res.isDefault = info.hasDefault;
12644            res.labelRes = info.labelRes;
12645            res.nonLocalizedLabel = info.nonLocalizedLabel;
12646            res.icon = info.icon;
12647            res.system = res.providerInfo.applicationInfo.isSystemApp();
12648            return res;
12649        }
12650
12651        @Override
12652        protected void sortResults(List<ResolveInfo> results) {
12653            Collections.sort(results, mResolvePrioritySorter);
12654        }
12655
12656        @Override
12657        protected void dumpFilter(PrintWriter out, String prefix,
12658                PackageParser.ProviderIntentInfo filter) {
12659            out.print(prefix);
12660            out.print(
12661                    Integer.toHexString(System.identityHashCode(filter.provider)));
12662            out.print(' ');
12663            filter.provider.printComponentShortName(out);
12664            out.print(" filter ");
12665            out.println(Integer.toHexString(System.identityHashCode(filter)));
12666        }
12667
12668        @Override
12669        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12670            return filter.provider;
12671        }
12672
12673        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12674            PackageParser.Provider provider = (PackageParser.Provider)label;
12675            out.print(prefix); out.print(
12676                    Integer.toHexString(System.identityHashCode(provider)));
12677                    out.print(' ');
12678                    provider.printComponentShortName(out);
12679            if (count > 1) {
12680                out.print(" ("); out.print(count); out.print(" filters)");
12681            }
12682            out.println();
12683        }
12684
12685        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12686                = new ArrayMap<ComponentName, PackageParser.Provider>();
12687        private int mFlags;
12688    }
12689
12690    static final class EphemeralIntentResolver
12691            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12692        /**
12693         * The result that has the highest defined order. Ordering applies on a
12694         * per-package basis. Mapping is from package name to Pair of order and
12695         * EphemeralResolveInfo.
12696         * <p>
12697         * NOTE: This is implemented as a field variable for convenience and efficiency.
12698         * By having a field variable, we're able to track filter ordering as soon as
12699         * a non-zero order is defined. Otherwise, multiple loops across the result set
12700         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12701         * this needs to be contained entirely within {@link #filterResults}.
12702         */
12703        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12704
12705        @Override
12706        protected AuxiliaryResolveInfo[] newArray(int size) {
12707            return new AuxiliaryResolveInfo[size];
12708        }
12709
12710        @Override
12711        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12712            return true;
12713        }
12714
12715        @Override
12716        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12717                int userId) {
12718            if (!sUserManager.exists(userId)) {
12719                return null;
12720            }
12721            final String packageName = responseObj.resolveInfo.getPackageName();
12722            final Integer order = responseObj.getOrder();
12723            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12724                    mOrderResult.get(packageName);
12725            // ordering is enabled and this item's order isn't high enough
12726            if (lastOrderResult != null && lastOrderResult.first >= order) {
12727                return null;
12728            }
12729            final InstantAppResolveInfo res = responseObj.resolveInfo;
12730            if (order > 0) {
12731                // non-zero order, enable ordering
12732                mOrderResult.put(packageName, new Pair<>(order, res));
12733            }
12734            return responseObj;
12735        }
12736
12737        @Override
12738        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12739            // only do work if ordering is enabled [most of the time it won't be]
12740            if (mOrderResult.size() == 0) {
12741                return;
12742            }
12743            int resultSize = results.size();
12744            for (int i = 0; i < resultSize; i++) {
12745                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12746                final String packageName = info.getPackageName();
12747                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12748                if (savedInfo == null) {
12749                    // package doesn't having ordering
12750                    continue;
12751                }
12752                if (savedInfo.second == info) {
12753                    // circled back to the highest ordered item; remove from order list
12754                    mOrderResult.remove(savedInfo);
12755                    if (mOrderResult.size() == 0) {
12756                        // no more ordered items
12757                        break;
12758                    }
12759                    continue;
12760                }
12761                // item has a worse order, remove it from the result list
12762                results.remove(i);
12763                resultSize--;
12764                i--;
12765            }
12766        }
12767    }
12768
12769    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12770            new Comparator<ResolveInfo>() {
12771        public int compare(ResolveInfo r1, ResolveInfo r2) {
12772            int v1 = r1.priority;
12773            int v2 = r2.priority;
12774            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12775            if (v1 != v2) {
12776                return (v1 > v2) ? -1 : 1;
12777            }
12778            v1 = r1.preferredOrder;
12779            v2 = r2.preferredOrder;
12780            if (v1 != v2) {
12781                return (v1 > v2) ? -1 : 1;
12782            }
12783            if (r1.isDefault != r2.isDefault) {
12784                return r1.isDefault ? -1 : 1;
12785            }
12786            v1 = r1.match;
12787            v2 = r2.match;
12788            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12789            if (v1 != v2) {
12790                return (v1 > v2) ? -1 : 1;
12791            }
12792            if (r1.system != r2.system) {
12793                return r1.system ? -1 : 1;
12794            }
12795            if (r1.activityInfo != null) {
12796                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12797            }
12798            if (r1.serviceInfo != null) {
12799                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12800            }
12801            if (r1.providerInfo != null) {
12802                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12803            }
12804            return 0;
12805        }
12806    };
12807
12808    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12809            new Comparator<ProviderInfo>() {
12810        public int compare(ProviderInfo p1, ProviderInfo p2) {
12811            final int v1 = p1.initOrder;
12812            final int v2 = p2.initOrder;
12813            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12814        }
12815    };
12816
12817    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12818            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12819            final int[] userIds) {
12820        mHandler.post(new Runnable() {
12821            @Override
12822            public void run() {
12823                try {
12824                    final IActivityManager am = ActivityManager.getService();
12825                    if (am == null) return;
12826                    final int[] resolvedUserIds;
12827                    if (userIds == null) {
12828                        resolvedUserIds = am.getRunningUserIds();
12829                    } else {
12830                        resolvedUserIds = userIds;
12831                    }
12832                    for (int id : resolvedUserIds) {
12833                        final Intent intent = new Intent(action,
12834                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12835                        if (extras != null) {
12836                            intent.putExtras(extras);
12837                        }
12838                        if (targetPkg != null) {
12839                            intent.setPackage(targetPkg);
12840                        }
12841                        // Modify the UID when posting to other users
12842                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12843                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12844                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12845                            intent.putExtra(Intent.EXTRA_UID, uid);
12846                        }
12847                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12848                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12849                        if (DEBUG_BROADCASTS) {
12850                            RuntimeException here = new RuntimeException("here");
12851                            here.fillInStackTrace();
12852                            Slog.d(TAG, "Sending to user " + id + ": "
12853                                    + intent.toShortString(false, true, false, false)
12854                                    + " " + intent.getExtras(), here);
12855                        }
12856                        am.broadcastIntent(null, intent, null, finishedReceiver,
12857                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12858                                null, finishedReceiver != null, false, id);
12859                    }
12860                } catch (RemoteException ex) {
12861                }
12862            }
12863        });
12864    }
12865
12866    /**
12867     * Check if the external storage media is available. This is true if there
12868     * is a mounted external storage medium or if the external storage is
12869     * emulated.
12870     */
12871    private boolean isExternalMediaAvailable() {
12872        return mMediaMounted || Environment.isExternalStorageEmulated();
12873    }
12874
12875    @Override
12876    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12877        // writer
12878        synchronized (mPackages) {
12879            if (!isExternalMediaAvailable()) {
12880                // If the external storage is no longer mounted at this point,
12881                // the caller may not have been able to delete all of this
12882                // packages files and can not delete any more.  Bail.
12883                return null;
12884            }
12885            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12886            if (lastPackage != null) {
12887                pkgs.remove(lastPackage);
12888            }
12889            if (pkgs.size() > 0) {
12890                return pkgs.get(0);
12891            }
12892        }
12893        return null;
12894    }
12895
12896    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12897        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12898                userId, andCode ? 1 : 0, packageName);
12899        if (mSystemReady) {
12900            msg.sendToTarget();
12901        } else {
12902            if (mPostSystemReadyMessages == null) {
12903                mPostSystemReadyMessages = new ArrayList<>();
12904            }
12905            mPostSystemReadyMessages.add(msg);
12906        }
12907    }
12908
12909    void startCleaningPackages() {
12910        // reader
12911        if (!isExternalMediaAvailable()) {
12912            return;
12913        }
12914        synchronized (mPackages) {
12915            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12916                return;
12917            }
12918        }
12919        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12920        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12921        IActivityManager am = ActivityManager.getService();
12922        if (am != null) {
12923            try {
12924                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12925                        UserHandle.USER_SYSTEM);
12926            } catch (RemoteException e) {
12927            }
12928        }
12929    }
12930
12931    @Override
12932    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12933            int installFlags, String installerPackageName, int userId) {
12934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12935
12936        final int callingUid = Binder.getCallingUid();
12937        enforceCrossUserPermission(callingUid, userId,
12938                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12939
12940        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12941            try {
12942                if (observer != null) {
12943                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12944                }
12945            } catch (RemoteException re) {
12946            }
12947            return;
12948        }
12949
12950        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12951            installFlags |= PackageManager.INSTALL_FROM_ADB;
12952
12953        } else {
12954            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12955            // about installerPackageName.
12956
12957            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12958            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12959        }
12960
12961        UserHandle user;
12962        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12963            user = UserHandle.ALL;
12964        } else {
12965            user = new UserHandle(userId);
12966        }
12967
12968        // Only system components can circumvent runtime permissions when installing.
12969        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12970                && mContext.checkCallingOrSelfPermission(Manifest.permission
12971                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12972            throw new SecurityException("You need the "
12973                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12974                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12975        }
12976
12977        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12978                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12979            throw new IllegalArgumentException(
12980                    "New installs into ASEC containers no longer supported");
12981        }
12982
12983        final File originFile = new File(originPath);
12984        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12985
12986        final Message msg = mHandler.obtainMessage(INIT_COPY);
12987        final VerificationInfo verificationInfo = new VerificationInfo(
12988                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12989        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12990                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12991                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12992                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12993        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12994        msg.obj = params;
12995
12996        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12997                System.identityHashCode(msg.obj));
12998        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12999                System.identityHashCode(msg.obj));
13000
13001        mHandler.sendMessage(msg);
13002    }
13003
13004
13005    /**
13006     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13007     * it is acting on behalf on an enterprise or the user).
13008     *
13009     * Note that the ordering of the conditionals in this method is important. The checks we perform
13010     * are as follows, in this order:
13011     *
13012     * 1) If the install is being performed by a system app, we can trust the app to have set the
13013     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13014     *    what it is.
13015     * 2) If the install is being performed by a device or profile owner app, the install reason
13016     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13017     *    set the install reason correctly. If the app targets an older SDK version where install
13018     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13019     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13020     * 3) In all other cases, the install is being performed by a regular app that is neither part
13021     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13022     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13023     *    set to enterprise policy and if so, change it to unknown instead.
13024     */
13025    private int fixUpInstallReason(String installerPackageName, int installerUid,
13026            int installReason) {
13027        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13028                == PERMISSION_GRANTED) {
13029            // If the install is being performed by a system app, we trust that app to have set the
13030            // install reason correctly.
13031            return installReason;
13032        }
13033
13034        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13035            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13036        if (dpm != null) {
13037            ComponentName owner = null;
13038            try {
13039                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13040                if (owner == null) {
13041                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13042                }
13043            } catch (RemoteException e) {
13044            }
13045            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13046                // If the install is being performed by a device or profile owner, the install
13047                // reason should be enterprise policy.
13048                return PackageManager.INSTALL_REASON_POLICY;
13049            }
13050        }
13051
13052        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13053            // If the install is being performed by a regular app (i.e. neither system app nor
13054            // device or profile owner), we have no reason to believe that the app is acting on
13055            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13056            // change it to unknown instead.
13057            return PackageManager.INSTALL_REASON_UNKNOWN;
13058        }
13059
13060        // If the install is being performed by a regular app and the install reason was set to any
13061        // value but enterprise policy, leave the install reason unchanged.
13062        return installReason;
13063    }
13064
13065    void installStage(String packageName, File stagedDir, String stagedCid,
13066            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13067            String installerPackageName, int installerUid, UserHandle user,
13068            Certificate[][] certificates) {
13069        if (DEBUG_EPHEMERAL) {
13070            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13071                Slog.d(TAG, "Ephemeral install of " + packageName);
13072            }
13073        }
13074        final VerificationInfo verificationInfo = new VerificationInfo(
13075                sessionParams.originatingUri, sessionParams.referrerUri,
13076                sessionParams.originatingUid, installerUid);
13077
13078        final OriginInfo origin;
13079        if (stagedDir != null) {
13080            origin = OriginInfo.fromStagedFile(stagedDir);
13081        } else {
13082            origin = OriginInfo.fromStagedContainer(stagedCid);
13083        }
13084
13085        final Message msg = mHandler.obtainMessage(INIT_COPY);
13086        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13087                sessionParams.installReason);
13088        final InstallParams params = new InstallParams(origin, null, observer,
13089                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13090                verificationInfo, user, sessionParams.abiOverride,
13091                sessionParams.grantedRuntimePermissions, certificates, installReason);
13092        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13093        msg.obj = params;
13094
13095        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13096                System.identityHashCode(msg.obj));
13097        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13098                System.identityHashCode(msg.obj));
13099
13100        mHandler.sendMessage(msg);
13101    }
13102
13103    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13104            int userId) {
13105        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13106        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13107    }
13108
13109    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13110            int appId, int... userIds) {
13111        if (ArrayUtils.isEmpty(userIds)) {
13112            return;
13113        }
13114        Bundle extras = new Bundle(1);
13115        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13116        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13117
13118        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13119                packageName, extras, 0, null, null, userIds);
13120        if (isSystem) {
13121            mHandler.post(() -> {
13122                        for (int userId : userIds) {
13123                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13124                        }
13125                    }
13126            );
13127        }
13128    }
13129
13130    /**
13131     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13132     * automatically without needing an explicit launch.
13133     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13134     */
13135    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13136        // If user is not running, the app didn't miss any broadcast
13137        if (!mUserManagerInternal.isUserRunning(userId)) {
13138            return;
13139        }
13140        final IActivityManager am = ActivityManager.getService();
13141        try {
13142            // Deliver LOCKED_BOOT_COMPLETED first
13143            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13144                    .setPackage(packageName);
13145            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13146            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13147                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13148
13149            // Deliver BOOT_COMPLETED only if user is unlocked
13150            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13151                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13152                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13153                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13154            }
13155        } catch (RemoteException e) {
13156            throw e.rethrowFromSystemServer();
13157        }
13158    }
13159
13160    @Override
13161    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13162            int userId) {
13163        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13164        PackageSetting pkgSetting;
13165        final int uid = Binder.getCallingUid();
13166        enforceCrossUserPermission(uid, userId,
13167                true /* requireFullPermission */, true /* checkShell */,
13168                "setApplicationHiddenSetting for user " + userId);
13169
13170        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13171            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13172            return false;
13173        }
13174
13175        long callingId = Binder.clearCallingIdentity();
13176        try {
13177            boolean sendAdded = false;
13178            boolean sendRemoved = false;
13179            // writer
13180            synchronized (mPackages) {
13181                pkgSetting = mSettings.mPackages.get(packageName);
13182                if (pkgSetting == null) {
13183                    return false;
13184                }
13185                // Do not allow "android" is being disabled
13186                if ("android".equals(packageName)) {
13187                    Slog.w(TAG, "Cannot hide package: android");
13188                    return false;
13189                }
13190                // Cannot hide static shared libs as they are considered
13191                // a part of the using app (emulating static linking). Also
13192                // static libs are installed always on internal storage.
13193                PackageParser.Package pkg = mPackages.get(packageName);
13194                if (pkg != null && pkg.staticSharedLibName != null) {
13195                    Slog.w(TAG, "Cannot hide package: " + packageName
13196                            + " providing static shared library: "
13197                            + pkg.staticSharedLibName);
13198                    return false;
13199                }
13200                // Only allow protected packages to hide themselves.
13201                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13202                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13203                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13204                    return false;
13205                }
13206
13207                if (pkgSetting.getHidden(userId) != hidden) {
13208                    pkgSetting.setHidden(hidden, userId);
13209                    mSettings.writePackageRestrictionsLPr(userId);
13210                    if (hidden) {
13211                        sendRemoved = true;
13212                    } else {
13213                        sendAdded = true;
13214                    }
13215                }
13216            }
13217            if (sendAdded) {
13218                sendPackageAddedForUser(packageName, pkgSetting, userId);
13219                return true;
13220            }
13221            if (sendRemoved) {
13222                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13223                        "hiding pkg");
13224                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13225                return true;
13226            }
13227        } finally {
13228            Binder.restoreCallingIdentity(callingId);
13229        }
13230        return false;
13231    }
13232
13233    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13234            int userId) {
13235        final PackageRemovedInfo info = new PackageRemovedInfo();
13236        info.removedPackage = packageName;
13237        info.removedUsers = new int[] {userId};
13238        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13239        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13240    }
13241
13242    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13243        if (pkgList.length > 0) {
13244            Bundle extras = new Bundle(1);
13245            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13246
13247            sendPackageBroadcast(
13248                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13249                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13250                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13251                    new int[] {userId});
13252        }
13253    }
13254
13255    /**
13256     * Returns true if application is not found or there was an error. Otherwise it returns
13257     * the hidden state of the package for the given user.
13258     */
13259    @Override
13260    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13261        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13263                true /* requireFullPermission */, false /* checkShell */,
13264                "getApplicationHidden for user " + userId);
13265        PackageSetting pkgSetting;
13266        long callingId = Binder.clearCallingIdentity();
13267        try {
13268            // writer
13269            synchronized (mPackages) {
13270                pkgSetting = mSettings.mPackages.get(packageName);
13271                if (pkgSetting == null) {
13272                    return true;
13273                }
13274                return pkgSetting.getHidden(userId);
13275            }
13276        } finally {
13277            Binder.restoreCallingIdentity(callingId);
13278        }
13279    }
13280
13281    /**
13282     * @hide
13283     */
13284    @Override
13285    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13286            int installReason) {
13287        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13288                null);
13289        PackageSetting pkgSetting;
13290        final int uid = Binder.getCallingUid();
13291        enforceCrossUserPermission(uid, userId,
13292                true /* requireFullPermission */, true /* checkShell */,
13293                "installExistingPackage for user " + userId);
13294        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13295            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13296        }
13297
13298        long callingId = Binder.clearCallingIdentity();
13299        try {
13300            boolean installed = false;
13301            final boolean instantApp =
13302                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13303            final boolean fullApp =
13304                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13305
13306            // writer
13307            synchronized (mPackages) {
13308                pkgSetting = mSettings.mPackages.get(packageName);
13309                if (pkgSetting == null) {
13310                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13311                }
13312                if (!pkgSetting.getInstalled(userId)) {
13313                    pkgSetting.setInstalled(true, userId);
13314                    pkgSetting.setHidden(false, userId);
13315                    pkgSetting.setInstallReason(installReason, userId);
13316                    mSettings.writePackageRestrictionsLPr(userId);
13317                    mSettings.writeKernelMappingLPr(pkgSetting);
13318                    installed = true;
13319                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13320                    // upgrade app from instant to full; we don't allow app downgrade
13321                    installed = true;
13322                }
13323                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13324            }
13325
13326            if (installed) {
13327                if (pkgSetting.pkg != null) {
13328                    synchronized (mInstallLock) {
13329                        // We don't need to freeze for a brand new install
13330                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13331                    }
13332                }
13333                sendPackageAddedForUser(packageName, pkgSetting, userId);
13334                synchronized (mPackages) {
13335                    updateSequenceNumberLP(packageName, new int[]{ userId });
13336                }
13337            }
13338        } finally {
13339            Binder.restoreCallingIdentity(callingId);
13340        }
13341
13342        return PackageManager.INSTALL_SUCCEEDED;
13343    }
13344
13345    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13346            boolean instantApp, boolean fullApp) {
13347        // no state specified; do nothing
13348        if (!instantApp && !fullApp) {
13349            return;
13350        }
13351        if (userId != UserHandle.USER_ALL) {
13352            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13353                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13354            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13355                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13356            }
13357        } else {
13358            for (int currentUserId : sUserManager.getUserIds()) {
13359                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13360                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13361                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13362                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13363                }
13364            }
13365        }
13366    }
13367
13368    boolean isUserRestricted(int userId, String restrictionKey) {
13369        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13370        if (restrictions.getBoolean(restrictionKey, false)) {
13371            Log.w(TAG, "User is restricted: " + restrictionKey);
13372            return true;
13373        }
13374        return false;
13375    }
13376
13377    @Override
13378    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13379            int userId) {
13380        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13381        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13382                true /* requireFullPermission */, true /* checkShell */,
13383                "setPackagesSuspended for user " + userId);
13384
13385        if (ArrayUtils.isEmpty(packageNames)) {
13386            return packageNames;
13387        }
13388
13389        // List of package names for whom the suspended state has changed.
13390        List<String> changedPackages = new ArrayList<>(packageNames.length);
13391        // List of package names for whom the suspended state is not set as requested in this
13392        // method.
13393        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13394        long callingId = Binder.clearCallingIdentity();
13395        try {
13396            for (int i = 0; i < packageNames.length; i++) {
13397                String packageName = packageNames[i];
13398                boolean changed = false;
13399                final int appId;
13400                synchronized (mPackages) {
13401                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13402                    if (pkgSetting == null) {
13403                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13404                                + "\". Skipping suspending/un-suspending.");
13405                        unactionedPackages.add(packageName);
13406                        continue;
13407                    }
13408                    appId = pkgSetting.appId;
13409                    if (pkgSetting.getSuspended(userId) != suspended) {
13410                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13411                            unactionedPackages.add(packageName);
13412                            continue;
13413                        }
13414                        pkgSetting.setSuspended(suspended, userId);
13415                        mSettings.writePackageRestrictionsLPr(userId);
13416                        changed = true;
13417                        changedPackages.add(packageName);
13418                    }
13419                }
13420
13421                if (changed && suspended) {
13422                    killApplication(packageName, UserHandle.getUid(userId, appId),
13423                            "suspending package");
13424                }
13425            }
13426        } finally {
13427            Binder.restoreCallingIdentity(callingId);
13428        }
13429
13430        if (!changedPackages.isEmpty()) {
13431            sendPackagesSuspendedForUser(changedPackages.toArray(
13432                    new String[changedPackages.size()]), userId, suspended);
13433        }
13434
13435        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13436    }
13437
13438    @Override
13439    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13441                true /* requireFullPermission */, false /* checkShell */,
13442                "isPackageSuspendedForUser for user " + userId);
13443        synchronized (mPackages) {
13444            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13445            if (pkgSetting == null) {
13446                throw new IllegalArgumentException("Unknown target package: " + packageName);
13447            }
13448            return pkgSetting.getSuspended(userId);
13449        }
13450    }
13451
13452    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13453        if (isPackageDeviceAdmin(packageName, userId)) {
13454            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13455                    + "\": has an active device admin");
13456            return false;
13457        }
13458
13459        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13460        if (packageName.equals(activeLauncherPackageName)) {
13461            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13462                    + "\": contains the active launcher");
13463            return false;
13464        }
13465
13466        if (packageName.equals(mRequiredInstallerPackage)) {
13467            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13468                    + "\": required for package installation");
13469            return false;
13470        }
13471
13472        if (packageName.equals(mRequiredUninstallerPackage)) {
13473            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13474                    + "\": required for package uninstallation");
13475            return false;
13476        }
13477
13478        if (packageName.equals(mRequiredVerifierPackage)) {
13479            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13480                    + "\": required for package verification");
13481            return false;
13482        }
13483
13484        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13485            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13486                    + "\": is the default dialer");
13487            return false;
13488        }
13489
13490        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13491            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13492                    + "\": protected package");
13493            return false;
13494        }
13495
13496        // Cannot suspend static shared libs as they are considered
13497        // a part of the using app (emulating static linking). Also
13498        // static libs are installed always on internal storage.
13499        PackageParser.Package pkg = mPackages.get(packageName);
13500        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13501            Slog.w(TAG, "Cannot suspend package: " + packageName
13502                    + " providing static shared library: "
13503                    + pkg.staticSharedLibName);
13504            return false;
13505        }
13506
13507        return true;
13508    }
13509
13510    private String getActiveLauncherPackageName(int userId) {
13511        Intent intent = new Intent(Intent.ACTION_MAIN);
13512        intent.addCategory(Intent.CATEGORY_HOME);
13513        ResolveInfo resolveInfo = resolveIntent(
13514                intent,
13515                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13516                PackageManager.MATCH_DEFAULT_ONLY,
13517                userId);
13518
13519        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13520    }
13521
13522    private String getDefaultDialerPackageName(int userId) {
13523        synchronized (mPackages) {
13524            return mSettings.getDefaultDialerPackageNameLPw(userId);
13525        }
13526    }
13527
13528    @Override
13529    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13530        mContext.enforceCallingOrSelfPermission(
13531                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13532                "Only package verification agents can verify applications");
13533
13534        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13535        final PackageVerificationResponse response = new PackageVerificationResponse(
13536                verificationCode, Binder.getCallingUid());
13537        msg.arg1 = id;
13538        msg.obj = response;
13539        mHandler.sendMessage(msg);
13540    }
13541
13542    @Override
13543    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13544            long millisecondsToDelay) {
13545        mContext.enforceCallingOrSelfPermission(
13546                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13547                "Only package verification agents can extend verification timeouts");
13548
13549        final PackageVerificationState state = mPendingVerification.get(id);
13550        final PackageVerificationResponse response = new PackageVerificationResponse(
13551                verificationCodeAtTimeout, Binder.getCallingUid());
13552
13553        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13554            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13555        }
13556        if (millisecondsToDelay < 0) {
13557            millisecondsToDelay = 0;
13558        }
13559        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13560                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13561            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13562        }
13563
13564        if ((state != null) && !state.timeoutExtended()) {
13565            state.extendTimeout();
13566
13567            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13568            msg.arg1 = id;
13569            msg.obj = response;
13570            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13571        }
13572    }
13573
13574    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13575            int verificationCode, UserHandle user) {
13576        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13577        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13578        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13579        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13580        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13581
13582        mContext.sendBroadcastAsUser(intent, user,
13583                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13584    }
13585
13586    private ComponentName matchComponentForVerifier(String packageName,
13587            List<ResolveInfo> receivers) {
13588        ActivityInfo targetReceiver = null;
13589
13590        final int NR = receivers.size();
13591        for (int i = 0; i < NR; i++) {
13592            final ResolveInfo info = receivers.get(i);
13593            if (info.activityInfo == null) {
13594                continue;
13595            }
13596
13597            if (packageName.equals(info.activityInfo.packageName)) {
13598                targetReceiver = info.activityInfo;
13599                break;
13600            }
13601        }
13602
13603        if (targetReceiver == null) {
13604            return null;
13605        }
13606
13607        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13608    }
13609
13610    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13611            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13612        if (pkgInfo.verifiers.length == 0) {
13613            return null;
13614        }
13615
13616        final int N = pkgInfo.verifiers.length;
13617        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13618        for (int i = 0; i < N; i++) {
13619            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13620
13621            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13622                    receivers);
13623            if (comp == null) {
13624                continue;
13625            }
13626
13627            final int verifierUid = getUidForVerifier(verifierInfo);
13628            if (verifierUid == -1) {
13629                continue;
13630            }
13631
13632            if (DEBUG_VERIFY) {
13633                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13634                        + " with the correct signature");
13635            }
13636            sufficientVerifiers.add(comp);
13637            verificationState.addSufficientVerifier(verifierUid);
13638        }
13639
13640        return sufficientVerifiers;
13641    }
13642
13643    private int getUidForVerifier(VerifierInfo verifierInfo) {
13644        synchronized (mPackages) {
13645            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13646            if (pkg == null) {
13647                return -1;
13648            } else if (pkg.mSignatures.length != 1) {
13649                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13650                        + " has more than one signature; ignoring");
13651                return -1;
13652            }
13653
13654            /*
13655             * If the public key of the package's signature does not match
13656             * our expected public key, then this is a different package and
13657             * we should skip.
13658             */
13659
13660            final byte[] expectedPublicKey;
13661            try {
13662                final Signature verifierSig = pkg.mSignatures[0];
13663                final PublicKey publicKey = verifierSig.getPublicKey();
13664                expectedPublicKey = publicKey.getEncoded();
13665            } catch (CertificateException e) {
13666                return -1;
13667            }
13668
13669            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13670
13671            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13672                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13673                        + " does not have the expected public key; ignoring");
13674                return -1;
13675            }
13676
13677            return pkg.applicationInfo.uid;
13678        }
13679    }
13680
13681    @Override
13682    public void finishPackageInstall(int token, boolean didLaunch) {
13683        enforceSystemOrRoot("Only the system is allowed to finish installs");
13684
13685        if (DEBUG_INSTALL) {
13686            Slog.v(TAG, "BM finishing package install for " + token);
13687        }
13688        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13689
13690        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13691        mHandler.sendMessage(msg);
13692    }
13693
13694    /**
13695     * Get the verification agent timeout.
13696     *
13697     * @return verification timeout in milliseconds
13698     */
13699    private long getVerificationTimeout() {
13700        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13701                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13702                DEFAULT_VERIFICATION_TIMEOUT);
13703    }
13704
13705    /**
13706     * Get the default verification agent response code.
13707     *
13708     * @return default verification response code
13709     */
13710    private int getDefaultVerificationResponse() {
13711        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13712                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13713                DEFAULT_VERIFICATION_RESPONSE);
13714    }
13715
13716    /**
13717     * Check whether or not package verification has been enabled.
13718     *
13719     * @return true if verification should be performed
13720     */
13721    private boolean isVerificationEnabled(int userId, int installFlags) {
13722        if (!DEFAULT_VERIFY_ENABLE) {
13723            return false;
13724        }
13725
13726        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13727
13728        // Check if installing from ADB
13729        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13730            // Do not run verification in a test harness environment
13731            if (ActivityManager.isRunningInTestHarness()) {
13732                return false;
13733            }
13734            if (ensureVerifyAppsEnabled) {
13735                return true;
13736            }
13737            // Check if the developer does not want package verification for ADB installs
13738            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13739                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13740                return false;
13741            }
13742        }
13743
13744        if (ensureVerifyAppsEnabled) {
13745            return true;
13746        }
13747
13748        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13749                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13750    }
13751
13752    @Override
13753    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13754            throws RemoteException {
13755        mContext.enforceCallingOrSelfPermission(
13756                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13757                "Only intentfilter verification agents can verify applications");
13758
13759        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13760        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13761                Binder.getCallingUid(), verificationCode, failedDomains);
13762        msg.arg1 = id;
13763        msg.obj = response;
13764        mHandler.sendMessage(msg);
13765    }
13766
13767    @Override
13768    public int getIntentVerificationStatus(String packageName, int userId) {
13769        synchronized (mPackages) {
13770            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13771        }
13772    }
13773
13774    @Override
13775    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13776        mContext.enforceCallingOrSelfPermission(
13777                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13778
13779        boolean result = false;
13780        synchronized (mPackages) {
13781            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13782        }
13783        if (result) {
13784            scheduleWritePackageRestrictionsLocked(userId);
13785        }
13786        return result;
13787    }
13788
13789    @Override
13790    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13791            String packageName) {
13792        synchronized (mPackages) {
13793            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13794        }
13795    }
13796
13797    @Override
13798    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13799        if (TextUtils.isEmpty(packageName)) {
13800            return ParceledListSlice.emptyList();
13801        }
13802        synchronized (mPackages) {
13803            PackageParser.Package pkg = mPackages.get(packageName);
13804            if (pkg == null || pkg.activities == null) {
13805                return ParceledListSlice.emptyList();
13806            }
13807            final int count = pkg.activities.size();
13808            ArrayList<IntentFilter> result = new ArrayList<>();
13809            for (int n=0; n<count; n++) {
13810                PackageParser.Activity activity = pkg.activities.get(n);
13811                if (activity.intents != null && activity.intents.size() > 0) {
13812                    result.addAll(activity.intents);
13813                }
13814            }
13815            return new ParceledListSlice<>(result);
13816        }
13817    }
13818
13819    @Override
13820    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13821        mContext.enforceCallingOrSelfPermission(
13822                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13823
13824        synchronized (mPackages) {
13825            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13826            if (packageName != null) {
13827                result |= updateIntentVerificationStatus(packageName,
13828                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13829                        userId);
13830                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13831                        packageName, userId);
13832            }
13833            return result;
13834        }
13835    }
13836
13837    @Override
13838    public String getDefaultBrowserPackageName(int userId) {
13839        synchronized (mPackages) {
13840            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13841        }
13842    }
13843
13844    /**
13845     * Get the "allow unknown sources" setting.
13846     *
13847     * @return the current "allow unknown sources" setting
13848     */
13849    private int getUnknownSourcesSettings() {
13850        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13851                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13852                -1);
13853    }
13854
13855    @Override
13856    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13857        final int uid = Binder.getCallingUid();
13858        // writer
13859        synchronized (mPackages) {
13860            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13861            if (targetPackageSetting == null) {
13862                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13863            }
13864
13865            PackageSetting installerPackageSetting;
13866            if (installerPackageName != null) {
13867                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13868                if (installerPackageSetting == null) {
13869                    throw new IllegalArgumentException("Unknown installer package: "
13870                            + installerPackageName);
13871                }
13872            } else {
13873                installerPackageSetting = null;
13874            }
13875
13876            Signature[] callerSignature;
13877            Object obj = mSettings.getUserIdLPr(uid);
13878            if (obj != null) {
13879                if (obj instanceof SharedUserSetting) {
13880                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13881                } else if (obj instanceof PackageSetting) {
13882                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13883                } else {
13884                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13885                }
13886            } else {
13887                throw new SecurityException("Unknown calling UID: " + uid);
13888            }
13889
13890            // Verify: can't set installerPackageName to a package that is
13891            // not signed with the same cert as the caller.
13892            if (installerPackageSetting != null) {
13893                if (compareSignatures(callerSignature,
13894                        installerPackageSetting.signatures.mSignatures)
13895                        != PackageManager.SIGNATURE_MATCH) {
13896                    throw new SecurityException(
13897                            "Caller does not have same cert as new installer package "
13898                            + installerPackageName);
13899                }
13900            }
13901
13902            // Verify: if target already has an installer package, it must
13903            // be signed with the same cert as the caller.
13904            if (targetPackageSetting.installerPackageName != null) {
13905                PackageSetting setting = mSettings.mPackages.get(
13906                        targetPackageSetting.installerPackageName);
13907                // If the currently set package isn't valid, then it's always
13908                // okay to change it.
13909                if (setting != null) {
13910                    if (compareSignatures(callerSignature,
13911                            setting.signatures.mSignatures)
13912                            != PackageManager.SIGNATURE_MATCH) {
13913                        throw new SecurityException(
13914                                "Caller does not have same cert as old installer package "
13915                                + targetPackageSetting.installerPackageName);
13916                    }
13917                }
13918            }
13919
13920            // Okay!
13921            targetPackageSetting.installerPackageName = installerPackageName;
13922            if (installerPackageName != null) {
13923                mSettings.mInstallerPackages.add(installerPackageName);
13924            }
13925            scheduleWriteSettingsLocked();
13926        }
13927    }
13928
13929    @Override
13930    public void setApplicationCategoryHint(String packageName, int categoryHint,
13931            String callerPackageName) {
13932        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13933                callerPackageName);
13934        synchronized (mPackages) {
13935            PackageSetting ps = mSettings.mPackages.get(packageName);
13936            if (ps == null) {
13937                throw new IllegalArgumentException("Unknown target package " + packageName);
13938            }
13939
13940            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13941                throw new IllegalArgumentException("Calling package " + callerPackageName
13942                        + " is not installer for " + packageName);
13943            }
13944
13945            if (ps.categoryHint != categoryHint) {
13946                ps.categoryHint = categoryHint;
13947                scheduleWriteSettingsLocked();
13948            }
13949        }
13950    }
13951
13952    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13953        // Queue up an async operation since the package installation may take a little while.
13954        mHandler.post(new Runnable() {
13955            public void run() {
13956                mHandler.removeCallbacks(this);
13957                 // Result object to be returned
13958                PackageInstalledInfo res = new PackageInstalledInfo();
13959                res.setReturnCode(currentStatus);
13960                res.uid = -1;
13961                res.pkg = null;
13962                res.removedInfo = null;
13963                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13964                    args.doPreInstall(res.returnCode);
13965                    synchronized (mInstallLock) {
13966                        installPackageTracedLI(args, res);
13967                    }
13968                    args.doPostInstall(res.returnCode, res.uid);
13969                }
13970
13971                // A restore should be performed at this point if (a) the install
13972                // succeeded, (b) the operation is not an update, and (c) the new
13973                // package has not opted out of backup participation.
13974                final boolean update = res.removedInfo != null
13975                        && res.removedInfo.removedPackage != null;
13976                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13977                boolean doRestore = !update
13978                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13979
13980                // Set up the post-install work request bookkeeping.  This will be used
13981                // and cleaned up by the post-install event handling regardless of whether
13982                // there's a restore pass performed.  Token values are >= 1.
13983                int token;
13984                if (mNextInstallToken < 0) mNextInstallToken = 1;
13985                token = mNextInstallToken++;
13986
13987                PostInstallData data = new PostInstallData(args, res);
13988                mRunningInstalls.put(token, data);
13989                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13990
13991                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13992                    // Pass responsibility to the Backup Manager.  It will perform a
13993                    // restore if appropriate, then pass responsibility back to the
13994                    // Package Manager to run the post-install observer callbacks
13995                    // and broadcasts.
13996                    IBackupManager bm = IBackupManager.Stub.asInterface(
13997                            ServiceManager.getService(Context.BACKUP_SERVICE));
13998                    if (bm != null) {
13999                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14000                                + " to BM for possible restore");
14001                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14002                        try {
14003                            // TODO: http://b/22388012
14004                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14005                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14006                            } else {
14007                                doRestore = false;
14008                            }
14009                        } catch (RemoteException e) {
14010                            // can't happen; the backup manager is local
14011                        } catch (Exception e) {
14012                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14013                            doRestore = false;
14014                        }
14015                    } else {
14016                        Slog.e(TAG, "Backup Manager not found!");
14017                        doRestore = false;
14018                    }
14019                }
14020
14021                if (!doRestore) {
14022                    // No restore possible, or the Backup Manager was mysteriously not
14023                    // available -- just fire the post-install work request directly.
14024                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14025
14026                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14027
14028                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14029                    mHandler.sendMessage(msg);
14030                }
14031            }
14032        });
14033    }
14034
14035    /**
14036     * Callback from PackageSettings whenever an app is first transitioned out of the
14037     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14038     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14039     * here whether the app is the target of an ongoing install, and only send the
14040     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14041     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14042     * handling.
14043     */
14044    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14045        // Serialize this with the rest of the install-process message chain.  In the
14046        // restore-at-install case, this Runnable will necessarily run before the
14047        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14048        // are coherent.  In the non-restore case, the app has already completed install
14049        // and been launched through some other means, so it is not in a problematic
14050        // state for observers to see the FIRST_LAUNCH signal.
14051        mHandler.post(new Runnable() {
14052            @Override
14053            public void run() {
14054                for (int i = 0; i < mRunningInstalls.size(); i++) {
14055                    final PostInstallData data = mRunningInstalls.valueAt(i);
14056                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14057                        continue;
14058                    }
14059                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14060                        // right package; but is it for the right user?
14061                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14062                            if (userId == data.res.newUsers[uIndex]) {
14063                                if (DEBUG_BACKUP) {
14064                                    Slog.i(TAG, "Package " + pkgName
14065                                            + " being restored so deferring FIRST_LAUNCH");
14066                                }
14067                                return;
14068                            }
14069                        }
14070                    }
14071                }
14072                // didn't find it, so not being restored
14073                if (DEBUG_BACKUP) {
14074                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14075                }
14076                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14077            }
14078        });
14079    }
14080
14081    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14082        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14083                installerPkg, null, userIds);
14084    }
14085
14086    private abstract class HandlerParams {
14087        private static final int MAX_RETRIES = 4;
14088
14089        /**
14090         * Number of times startCopy() has been attempted and had a non-fatal
14091         * error.
14092         */
14093        private int mRetries = 0;
14094
14095        /** User handle for the user requesting the information or installation. */
14096        private final UserHandle mUser;
14097        String traceMethod;
14098        int traceCookie;
14099
14100        HandlerParams(UserHandle user) {
14101            mUser = user;
14102        }
14103
14104        UserHandle getUser() {
14105            return mUser;
14106        }
14107
14108        HandlerParams setTraceMethod(String traceMethod) {
14109            this.traceMethod = traceMethod;
14110            return this;
14111        }
14112
14113        HandlerParams setTraceCookie(int traceCookie) {
14114            this.traceCookie = traceCookie;
14115            return this;
14116        }
14117
14118        final boolean startCopy() {
14119            boolean res;
14120            try {
14121                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14122
14123                if (++mRetries > MAX_RETRIES) {
14124                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14125                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14126                    handleServiceError();
14127                    return false;
14128                } else {
14129                    handleStartCopy();
14130                    res = true;
14131                }
14132            } catch (RemoteException e) {
14133                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14134                mHandler.sendEmptyMessage(MCS_RECONNECT);
14135                res = false;
14136            }
14137            handleReturnCode();
14138            return res;
14139        }
14140
14141        final void serviceError() {
14142            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14143            handleServiceError();
14144            handleReturnCode();
14145        }
14146
14147        abstract void handleStartCopy() throws RemoteException;
14148        abstract void handleServiceError();
14149        abstract void handleReturnCode();
14150    }
14151
14152    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14153        for (File path : paths) {
14154            try {
14155                mcs.clearDirectory(path.getAbsolutePath());
14156            } catch (RemoteException e) {
14157            }
14158        }
14159    }
14160
14161    static class OriginInfo {
14162        /**
14163         * Location where install is coming from, before it has been
14164         * copied/renamed into place. This could be a single monolithic APK
14165         * file, or a cluster directory. This location may be untrusted.
14166         */
14167        final File file;
14168        final String cid;
14169
14170        /**
14171         * Flag indicating that {@link #file} or {@link #cid} has already been
14172         * staged, meaning downstream users don't need to defensively copy the
14173         * contents.
14174         */
14175        final boolean staged;
14176
14177        /**
14178         * Flag indicating that {@link #file} or {@link #cid} is an already
14179         * installed app that is being moved.
14180         */
14181        final boolean existing;
14182
14183        final String resolvedPath;
14184        final File resolvedFile;
14185
14186        static OriginInfo fromNothing() {
14187            return new OriginInfo(null, null, false, false);
14188        }
14189
14190        static OriginInfo fromUntrustedFile(File file) {
14191            return new OriginInfo(file, null, false, false);
14192        }
14193
14194        static OriginInfo fromExistingFile(File file) {
14195            return new OriginInfo(file, null, false, true);
14196        }
14197
14198        static OriginInfo fromStagedFile(File file) {
14199            return new OriginInfo(file, null, true, false);
14200        }
14201
14202        static OriginInfo fromStagedContainer(String cid) {
14203            return new OriginInfo(null, cid, true, false);
14204        }
14205
14206        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14207            this.file = file;
14208            this.cid = cid;
14209            this.staged = staged;
14210            this.existing = existing;
14211
14212            if (cid != null) {
14213                resolvedPath = PackageHelper.getSdDir(cid);
14214                resolvedFile = new File(resolvedPath);
14215            } else if (file != null) {
14216                resolvedPath = file.getAbsolutePath();
14217                resolvedFile = file;
14218            } else {
14219                resolvedPath = null;
14220                resolvedFile = null;
14221            }
14222        }
14223    }
14224
14225    static class MoveInfo {
14226        final int moveId;
14227        final String fromUuid;
14228        final String toUuid;
14229        final String packageName;
14230        final String dataAppName;
14231        final int appId;
14232        final String seinfo;
14233        final int targetSdkVersion;
14234
14235        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14236                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14237            this.moveId = moveId;
14238            this.fromUuid = fromUuid;
14239            this.toUuid = toUuid;
14240            this.packageName = packageName;
14241            this.dataAppName = dataAppName;
14242            this.appId = appId;
14243            this.seinfo = seinfo;
14244            this.targetSdkVersion = targetSdkVersion;
14245        }
14246    }
14247
14248    static class VerificationInfo {
14249        /** A constant used to indicate that a uid value is not present. */
14250        public static final int NO_UID = -1;
14251
14252        /** URI referencing where the package was downloaded from. */
14253        final Uri originatingUri;
14254
14255        /** HTTP referrer URI associated with the originatingURI. */
14256        final Uri referrer;
14257
14258        /** UID of the application that the install request originated from. */
14259        final int originatingUid;
14260
14261        /** UID of application requesting the install */
14262        final int installerUid;
14263
14264        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14265            this.originatingUri = originatingUri;
14266            this.referrer = referrer;
14267            this.originatingUid = originatingUid;
14268            this.installerUid = installerUid;
14269        }
14270    }
14271
14272    class InstallParams extends HandlerParams {
14273        final OriginInfo origin;
14274        final MoveInfo move;
14275        final IPackageInstallObserver2 observer;
14276        int installFlags;
14277        final String installerPackageName;
14278        final String volumeUuid;
14279        private InstallArgs mArgs;
14280        private int mRet;
14281        final String packageAbiOverride;
14282        final String[] grantedRuntimePermissions;
14283        final VerificationInfo verificationInfo;
14284        final Certificate[][] certificates;
14285        final int installReason;
14286
14287        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14288                int installFlags, String installerPackageName, String volumeUuid,
14289                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14290                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14291            super(user);
14292            this.origin = origin;
14293            this.move = move;
14294            this.observer = observer;
14295            this.installFlags = installFlags;
14296            this.installerPackageName = installerPackageName;
14297            this.volumeUuid = volumeUuid;
14298            this.verificationInfo = verificationInfo;
14299            this.packageAbiOverride = packageAbiOverride;
14300            this.grantedRuntimePermissions = grantedPermissions;
14301            this.certificates = certificates;
14302            this.installReason = installReason;
14303        }
14304
14305        @Override
14306        public String toString() {
14307            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14308                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14309        }
14310
14311        private int installLocationPolicy(PackageInfoLite pkgLite) {
14312            String packageName = pkgLite.packageName;
14313            int installLocation = pkgLite.installLocation;
14314            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14315            // reader
14316            synchronized (mPackages) {
14317                // Currently installed package which the new package is attempting to replace or
14318                // null if no such package is installed.
14319                PackageParser.Package installedPkg = mPackages.get(packageName);
14320                // Package which currently owns the data which the new package will own if installed.
14321                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14322                // will be null whereas dataOwnerPkg will contain information about the package
14323                // which was uninstalled while keeping its data.
14324                PackageParser.Package dataOwnerPkg = installedPkg;
14325                if (dataOwnerPkg  == null) {
14326                    PackageSetting ps = mSettings.mPackages.get(packageName);
14327                    if (ps != null) {
14328                        dataOwnerPkg = ps.pkg;
14329                    }
14330                }
14331
14332                if (dataOwnerPkg != null) {
14333                    // If installed, the package will get access to data left on the device by its
14334                    // predecessor. As a security measure, this is permited only if this is not a
14335                    // version downgrade or if the predecessor package is marked as debuggable and
14336                    // a downgrade is explicitly requested.
14337                    //
14338                    // On debuggable platform builds, downgrades are permitted even for
14339                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14340                    // not offer security guarantees and thus it's OK to disable some security
14341                    // mechanisms to make debugging/testing easier on those builds. However, even on
14342                    // debuggable builds downgrades of packages are permitted only if requested via
14343                    // installFlags. This is because we aim to keep the behavior of debuggable
14344                    // platform builds as close as possible to the behavior of non-debuggable
14345                    // platform builds.
14346                    final boolean downgradeRequested =
14347                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14348                    final boolean packageDebuggable =
14349                                (dataOwnerPkg.applicationInfo.flags
14350                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14351                    final boolean downgradePermitted =
14352                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14353                    if (!downgradePermitted) {
14354                        try {
14355                            checkDowngrade(dataOwnerPkg, pkgLite);
14356                        } catch (PackageManagerException e) {
14357                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14358                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14359                        }
14360                    }
14361                }
14362
14363                if (installedPkg != null) {
14364                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14365                        // Check for updated system application.
14366                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14367                            if (onSd) {
14368                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14369                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14370                            }
14371                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14372                        } else {
14373                            if (onSd) {
14374                                // Install flag overrides everything.
14375                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14376                            }
14377                            // If current upgrade specifies particular preference
14378                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14379                                // Application explicitly specified internal.
14380                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14381                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14382                                // App explictly prefers external. Let policy decide
14383                            } else {
14384                                // Prefer previous location
14385                                if (isExternal(installedPkg)) {
14386                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14387                                }
14388                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14389                            }
14390                        }
14391                    } else {
14392                        // Invalid install. Return error code
14393                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14394                    }
14395                }
14396            }
14397            // All the special cases have been taken care of.
14398            // Return result based on recommended install location.
14399            if (onSd) {
14400                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14401            }
14402            return pkgLite.recommendedInstallLocation;
14403        }
14404
14405        /*
14406         * Invoke remote method to get package information and install
14407         * location values. Override install location based on default
14408         * policy if needed and then create install arguments based
14409         * on the install location.
14410         */
14411        public void handleStartCopy() throws RemoteException {
14412            int ret = PackageManager.INSTALL_SUCCEEDED;
14413
14414            // If we're already staged, we've firmly committed to an install location
14415            if (origin.staged) {
14416                if (origin.file != null) {
14417                    installFlags |= PackageManager.INSTALL_INTERNAL;
14418                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14419                } else if (origin.cid != null) {
14420                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14421                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14422                } else {
14423                    throw new IllegalStateException("Invalid stage location");
14424                }
14425            }
14426
14427            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14428            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14429            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14430            PackageInfoLite pkgLite = null;
14431
14432            if (onInt && onSd) {
14433                // Check if both bits are set.
14434                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14435                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14436            } else if (onSd && ephemeral) {
14437                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14438                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14439            } else {
14440                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14441                        packageAbiOverride);
14442
14443                if (DEBUG_EPHEMERAL && ephemeral) {
14444                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14445                }
14446
14447                /*
14448                 * If we have too little free space, try to free cache
14449                 * before giving up.
14450                 */
14451                if (!origin.staged && pkgLite.recommendedInstallLocation
14452                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14453                    // TODO: focus freeing disk space on the target device
14454                    final StorageManager storage = StorageManager.from(mContext);
14455                    final long lowThreshold = storage.getStorageLowBytes(
14456                            Environment.getDataDirectory());
14457
14458                    final long sizeBytes = mContainerService.calculateInstalledSize(
14459                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14460
14461                    try {
14462                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14463                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14464                                installFlags, packageAbiOverride);
14465                    } catch (InstallerException e) {
14466                        Slog.w(TAG, "Failed to free cache", e);
14467                    }
14468
14469                    /*
14470                     * The cache free must have deleted the file we
14471                     * downloaded to install.
14472                     *
14473                     * TODO: fix the "freeCache" call to not delete
14474                     *       the file we care about.
14475                     */
14476                    if (pkgLite.recommendedInstallLocation
14477                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14478                        pkgLite.recommendedInstallLocation
14479                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14480                    }
14481                }
14482            }
14483
14484            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14485                int loc = pkgLite.recommendedInstallLocation;
14486                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14487                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14488                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14489                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14490                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14491                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14492                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14493                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14494                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14495                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14496                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14497                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14498                } else {
14499                    // Override with defaults if needed.
14500                    loc = installLocationPolicy(pkgLite);
14501                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14502                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14503                    } else if (!onSd && !onInt) {
14504                        // Override install location with flags
14505                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14506                            // Set the flag to install on external media.
14507                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14508                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14509                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14510                            if (DEBUG_EPHEMERAL) {
14511                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14512                            }
14513                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14514                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14515                                    |PackageManager.INSTALL_INTERNAL);
14516                        } else {
14517                            // Make sure the flag for installing on external
14518                            // media is unset
14519                            installFlags |= PackageManager.INSTALL_INTERNAL;
14520                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14521                        }
14522                    }
14523                }
14524            }
14525
14526            final InstallArgs args = createInstallArgs(this);
14527            mArgs = args;
14528
14529            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14530                // TODO: http://b/22976637
14531                // Apps installed for "all" users use the device owner to verify the app
14532                UserHandle verifierUser = getUser();
14533                if (verifierUser == UserHandle.ALL) {
14534                    verifierUser = UserHandle.SYSTEM;
14535                }
14536
14537                /*
14538                 * Determine if we have any installed package verifiers. If we
14539                 * do, then we'll defer to them to verify the packages.
14540                 */
14541                final int requiredUid = mRequiredVerifierPackage == null ? -1
14542                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14543                                verifierUser.getIdentifier());
14544                if (!origin.existing && requiredUid != -1
14545                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14546                    final Intent verification = new Intent(
14547                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14548                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14549                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14550                            PACKAGE_MIME_TYPE);
14551                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14552
14553                    // Query all live verifiers based on current user state
14554                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14555                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14556
14557                    if (DEBUG_VERIFY) {
14558                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14559                                + verification.toString() + " with " + pkgLite.verifiers.length
14560                                + " optional verifiers");
14561                    }
14562
14563                    final int verificationId = mPendingVerificationToken++;
14564
14565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14566
14567                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14568                            installerPackageName);
14569
14570                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14571                            installFlags);
14572
14573                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14574                            pkgLite.packageName);
14575
14576                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14577                            pkgLite.versionCode);
14578
14579                    if (verificationInfo != null) {
14580                        if (verificationInfo.originatingUri != null) {
14581                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14582                                    verificationInfo.originatingUri);
14583                        }
14584                        if (verificationInfo.referrer != null) {
14585                            verification.putExtra(Intent.EXTRA_REFERRER,
14586                                    verificationInfo.referrer);
14587                        }
14588                        if (verificationInfo.originatingUid >= 0) {
14589                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14590                                    verificationInfo.originatingUid);
14591                        }
14592                        if (verificationInfo.installerUid >= 0) {
14593                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14594                                    verificationInfo.installerUid);
14595                        }
14596                    }
14597
14598                    final PackageVerificationState verificationState = new PackageVerificationState(
14599                            requiredUid, args);
14600
14601                    mPendingVerification.append(verificationId, verificationState);
14602
14603                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14604                            receivers, verificationState);
14605
14606                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14607                    final long idleDuration = getVerificationTimeout();
14608
14609                    /*
14610                     * If any sufficient verifiers were listed in the package
14611                     * manifest, attempt to ask them.
14612                     */
14613                    if (sufficientVerifiers != null) {
14614                        final int N = sufficientVerifiers.size();
14615                        if (N == 0) {
14616                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14617                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14618                        } else {
14619                            for (int i = 0; i < N; i++) {
14620                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14621                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14622                                        verifierComponent.getPackageName(), idleDuration,
14623                                        verifierUser.getIdentifier(), false, "package verifier");
14624
14625                                final Intent sufficientIntent = new Intent(verification);
14626                                sufficientIntent.setComponent(verifierComponent);
14627                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14628                            }
14629                        }
14630                    }
14631
14632                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14633                            mRequiredVerifierPackage, receivers);
14634                    if (ret == PackageManager.INSTALL_SUCCEEDED
14635                            && mRequiredVerifierPackage != null) {
14636                        Trace.asyncTraceBegin(
14637                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14638                        /*
14639                         * Send the intent to the required verification agent,
14640                         * but only start the verification timeout after the
14641                         * target BroadcastReceivers have run.
14642                         */
14643                        verification.setComponent(requiredVerifierComponent);
14644                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14645                                mRequiredVerifierPackage, idleDuration,
14646                                verifierUser.getIdentifier(), false, "package verifier");
14647                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14648                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14649                                new BroadcastReceiver() {
14650                                    @Override
14651                                    public void onReceive(Context context, Intent intent) {
14652                                        final Message msg = mHandler
14653                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14654                                        msg.arg1 = verificationId;
14655                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14656                                    }
14657                                }, null, 0, null, null);
14658
14659                        /*
14660                         * We don't want the copy to proceed until verification
14661                         * succeeds, so null out this field.
14662                         */
14663                        mArgs = null;
14664                    }
14665                } else {
14666                    /*
14667                     * No package verification is enabled, so immediately start
14668                     * the remote call to initiate copy using temporary file.
14669                     */
14670                    ret = args.copyApk(mContainerService, true);
14671                }
14672            }
14673
14674            mRet = ret;
14675        }
14676
14677        @Override
14678        void handleReturnCode() {
14679            // If mArgs is null, then MCS couldn't be reached. When it
14680            // reconnects, it will try again to install. At that point, this
14681            // will succeed.
14682            if (mArgs != null) {
14683                processPendingInstall(mArgs, mRet);
14684            }
14685        }
14686
14687        @Override
14688        void handleServiceError() {
14689            mArgs = createInstallArgs(this);
14690            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14691        }
14692
14693        public boolean isForwardLocked() {
14694            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14695        }
14696    }
14697
14698    /**
14699     * Used during creation of InstallArgs
14700     *
14701     * @param installFlags package installation flags
14702     * @return true if should be installed on external storage
14703     */
14704    private static boolean installOnExternalAsec(int installFlags) {
14705        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14706            return false;
14707        }
14708        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14709            return true;
14710        }
14711        return false;
14712    }
14713
14714    /**
14715     * Used during creation of InstallArgs
14716     *
14717     * @param installFlags package installation flags
14718     * @return true if should be installed as forward locked
14719     */
14720    private static boolean installForwardLocked(int installFlags) {
14721        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14722    }
14723
14724    private InstallArgs createInstallArgs(InstallParams params) {
14725        if (params.move != null) {
14726            return new MoveInstallArgs(params);
14727        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14728            return new AsecInstallArgs(params);
14729        } else {
14730            return new FileInstallArgs(params);
14731        }
14732    }
14733
14734    /**
14735     * Create args that describe an existing installed package. Typically used
14736     * when cleaning up old installs, or used as a move source.
14737     */
14738    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14739            String resourcePath, String[] instructionSets) {
14740        final boolean isInAsec;
14741        if (installOnExternalAsec(installFlags)) {
14742            /* Apps on SD card are always in ASEC containers. */
14743            isInAsec = true;
14744        } else if (installForwardLocked(installFlags)
14745                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14746            /*
14747             * Forward-locked apps are only in ASEC containers if they're the
14748             * new style
14749             */
14750            isInAsec = true;
14751        } else {
14752            isInAsec = false;
14753        }
14754
14755        if (isInAsec) {
14756            return new AsecInstallArgs(codePath, instructionSets,
14757                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14758        } else {
14759            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14760        }
14761    }
14762
14763    static abstract class InstallArgs {
14764        /** @see InstallParams#origin */
14765        final OriginInfo origin;
14766        /** @see InstallParams#move */
14767        final MoveInfo move;
14768
14769        final IPackageInstallObserver2 observer;
14770        // Always refers to PackageManager flags only
14771        final int installFlags;
14772        final String installerPackageName;
14773        final String volumeUuid;
14774        final UserHandle user;
14775        final String abiOverride;
14776        final String[] installGrantPermissions;
14777        /** If non-null, drop an async trace when the install completes */
14778        final String traceMethod;
14779        final int traceCookie;
14780        final Certificate[][] certificates;
14781        final int installReason;
14782
14783        // The list of instruction sets supported by this app. This is currently
14784        // only used during the rmdex() phase to clean up resources. We can get rid of this
14785        // if we move dex files under the common app path.
14786        /* nullable */ String[] instructionSets;
14787
14788        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14789                int installFlags, String installerPackageName, String volumeUuid,
14790                UserHandle user, String[] instructionSets,
14791                String abiOverride, String[] installGrantPermissions,
14792                String traceMethod, int traceCookie, Certificate[][] certificates,
14793                int installReason) {
14794            this.origin = origin;
14795            this.move = move;
14796            this.installFlags = installFlags;
14797            this.observer = observer;
14798            this.installerPackageName = installerPackageName;
14799            this.volumeUuid = volumeUuid;
14800            this.user = user;
14801            this.instructionSets = instructionSets;
14802            this.abiOverride = abiOverride;
14803            this.installGrantPermissions = installGrantPermissions;
14804            this.traceMethod = traceMethod;
14805            this.traceCookie = traceCookie;
14806            this.certificates = certificates;
14807            this.installReason = installReason;
14808        }
14809
14810        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14811        abstract int doPreInstall(int status);
14812
14813        /**
14814         * Rename package into final resting place. All paths on the given
14815         * scanned package should be updated to reflect the rename.
14816         */
14817        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14818        abstract int doPostInstall(int status, int uid);
14819
14820        /** @see PackageSettingBase#codePathString */
14821        abstract String getCodePath();
14822        /** @see PackageSettingBase#resourcePathString */
14823        abstract String getResourcePath();
14824
14825        // Need installer lock especially for dex file removal.
14826        abstract void cleanUpResourcesLI();
14827        abstract boolean doPostDeleteLI(boolean delete);
14828
14829        /**
14830         * Called before the source arguments are copied. This is used mostly
14831         * for MoveParams when it needs to read the source file to put it in the
14832         * destination.
14833         */
14834        int doPreCopy() {
14835            return PackageManager.INSTALL_SUCCEEDED;
14836        }
14837
14838        /**
14839         * Called after the source arguments are copied. This is used mostly for
14840         * MoveParams when it needs to read the source file to put it in the
14841         * destination.
14842         */
14843        int doPostCopy(int uid) {
14844            return PackageManager.INSTALL_SUCCEEDED;
14845        }
14846
14847        protected boolean isFwdLocked() {
14848            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14849        }
14850
14851        protected boolean isExternalAsec() {
14852            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14853        }
14854
14855        protected boolean isEphemeral() {
14856            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14857        }
14858
14859        UserHandle getUser() {
14860            return user;
14861        }
14862    }
14863
14864    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14865        if (!allCodePaths.isEmpty()) {
14866            if (instructionSets == null) {
14867                throw new IllegalStateException("instructionSet == null");
14868            }
14869            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14870            for (String codePath : allCodePaths) {
14871                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14872                    try {
14873                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14874                    } catch (InstallerException ignored) {
14875                    }
14876                }
14877            }
14878        }
14879    }
14880
14881    /**
14882     * Logic to handle installation of non-ASEC applications, including copying
14883     * and renaming logic.
14884     */
14885    class FileInstallArgs extends InstallArgs {
14886        private File codeFile;
14887        private File resourceFile;
14888
14889        // Example topology:
14890        // /data/app/com.example/base.apk
14891        // /data/app/com.example/split_foo.apk
14892        // /data/app/com.example/lib/arm/libfoo.so
14893        // /data/app/com.example/lib/arm64/libfoo.so
14894        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14895
14896        /** New install */
14897        FileInstallArgs(InstallParams params) {
14898            super(params.origin, params.move, params.observer, params.installFlags,
14899                    params.installerPackageName, params.volumeUuid,
14900                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14901                    params.grantedRuntimePermissions,
14902                    params.traceMethod, params.traceCookie, params.certificates,
14903                    params.installReason);
14904            if (isFwdLocked()) {
14905                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14906            }
14907        }
14908
14909        /** Existing install */
14910        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14911            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14912                    null, null, null, 0, null /*certificates*/,
14913                    PackageManager.INSTALL_REASON_UNKNOWN);
14914            this.codeFile = (codePath != null) ? new File(codePath) : null;
14915            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14916        }
14917
14918        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14919            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14920            try {
14921                return doCopyApk(imcs, temp);
14922            } finally {
14923                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14924            }
14925        }
14926
14927        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14928            if (origin.staged) {
14929                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14930                codeFile = origin.file;
14931                resourceFile = origin.file;
14932                return PackageManager.INSTALL_SUCCEEDED;
14933            }
14934
14935            try {
14936                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14937                final File tempDir =
14938                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14939                codeFile = tempDir;
14940                resourceFile = tempDir;
14941            } catch (IOException e) {
14942                Slog.w(TAG, "Failed to create copy file: " + e);
14943                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14944            }
14945
14946            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14947                @Override
14948                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14949                    if (!FileUtils.isValidExtFilename(name)) {
14950                        throw new IllegalArgumentException("Invalid filename: " + name);
14951                    }
14952                    try {
14953                        final File file = new File(codeFile, name);
14954                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14955                                O_RDWR | O_CREAT, 0644);
14956                        Os.chmod(file.getAbsolutePath(), 0644);
14957                        return new ParcelFileDescriptor(fd);
14958                    } catch (ErrnoException e) {
14959                        throw new RemoteException("Failed to open: " + e.getMessage());
14960                    }
14961                }
14962            };
14963
14964            int ret = PackageManager.INSTALL_SUCCEEDED;
14965            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14966            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14967                Slog.e(TAG, "Failed to copy package");
14968                return ret;
14969            }
14970
14971            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14972            NativeLibraryHelper.Handle handle = null;
14973            try {
14974                handle = NativeLibraryHelper.Handle.create(codeFile);
14975                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14976                        abiOverride);
14977            } catch (IOException e) {
14978                Slog.e(TAG, "Copying native libraries failed", e);
14979                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14980            } finally {
14981                IoUtils.closeQuietly(handle);
14982            }
14983
14984            return ret;
14985        }
14986
14987        int doPreInstall(int status) {
14988            if (status != PackageManager.INSTALL_SUCCEEDED) {
14989                cleanUp();
14990            }
14991            return status;
14992        }
14993
14994        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14995            if (status != PackageManager.INSTALL_SUCCEEDED) {
14996                cleanUp();
14997                return false;
14998            }
14999
15000            final File targetDir = codeFile.getParentFile();
15001            final File beforeCodeFile = codeFile;
15002            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15003
15004            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15005            try {
15006                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15007            } catch (ErrnoException e) {
15008                Slog.w(TAG, "Failed to rename", e);
15009                return false;
15010            }
15011
15012            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15013                Slog.w(TAG, "Failed to restorecon");
15014                return false;
15015            }
15016
15017            // Reflect the rename internally
15018            codeFile = afterCodeFile;
15019            resourceFile = afterCodeFile;
15020
15021            // Reflect the rename in scanned details
15022            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15023            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15024                    afterCodeFile, pkg.baseCodePath));
15025            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15026                    afterCodeFile, pkg.splitCodePaths));
15027
15028            // Reflect the rename in app info
15029            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15030            pkg.setApplicationInfoCodePath(pkg.codePath);
15031            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15032            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15033            pkg.setApplicationInfoResourcePath(pkg.codePath);
15034            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15035            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15036
15037            return true;
15038        }
15039
15040        int doPostInstall(int status, int uid) {
15041            if (status != PackageManager.INSTALL_SUCCEEDED) {
15042                cleanUp();
15043            }
15044            return status;
15045        }
15046
15047        @Override
15048        String getCodePath() {
15049            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15050        }
15051
15052        @Override
15053        String getResourcePath() {
15054            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15055        }
15056
15057        private boolean cleanUp() {
15058            if (codeFile == null || !codeFile.exists()) {
15059                return false;
15060            }
15061
15062            removeCodePathLI(codeFile);
15063
15064            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15065                resourceFile.delete();
15066            }
15067
15068            return true;
15069        }
15070
15071        void cleanUpResourcesLI() {
15072            // Try enumerating all code paths before deleting
15073            List<String> allCodePaths = Collections.EMPTY_LIST;
15074            if (codeFile != null && codeFile.exists()) {
15075                try {
15076                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15077                    allCodePaths = pkg.getAllCodePaths();
15078                } catch (PackageParserException e) {
15079                    // Ignored; we tried our best
15080                }
15081            }
15082
15083            cleanUp();
15084            removeDexFiles(allCodePaths, instructionSets);
15085        }
15086
15087        boolean doPostDeleteLI(boolean delete) {
15088            // XXX err, shouldn't we respect the delete flag?
15089            cleanUpResourcesLI();
15090            return true;
15091        }
15092    }
15093
15094    private boolean isAsecExternal(String cid) {
15095        final String asecPath = PackageHelper.getSdFilesystem(cid);
15096        return !asecPath.startsWith(mAsecInternalPath);
15097    }
15098
15099    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15100            PackageManagerException {
15101        if (copyRet < 0) {
15102            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15103                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15104                throw new PackageManagerException(copyRet, message);
15105            }
15106        }
15107    }
15108
15109    /**
15110     * Extract the StorageManagerService "container ID" from the full code path of an
15111     * .apk.
15112     */
15113    static String cidFromCodePath(String fullCodePath) {
15114        int eidx = fullCodePath.lastIndexOf("/");
15115        String subStr1 = fullCodePath.substring(0, eidx);
15116        int sidx = subStr1.lastIndexOf("/");
15117        return subStr1.substring(sidx+1, eidx);
15118    }
15119
15120    /**
15121     * Logic to handle installation of ASEC applications, including copying and
15122     * renaming logic.
15123     */
15124    class AsecInstallArgs extends InstallArgs {
15125        static final String RES_FILE_NAME = "pkg.apk";
15126        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15127
15128        String cid;
15129        String packagePath;
15130        String resourcePath;
15131
15132        /** New install */
15133        AsecInstallArgs(InstallParams params) {
15134            super(params.origin, params.move, params.observer, params.installFlags,
15135                    params.installerPackageName, params.volumeUuid,
15136                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15137                    params.grantedRuntimePermissions,
15138                    params.traceMethod, params.traceCookie, params.certificates,
15139                    params.installReason);
15140        }
15141
15142        /** Existing install */
15143        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15144                        boolean isExternal, boolean isForwardLocked) {
15145            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15146                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15147                    instructionSets, null, null, null, 0, null /*certificates*/,
15148                    PackageManager.INSTALL_REASON_UNKNOWN);
15149            // Hackily pretend we're still looking at a full code path
15150            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15151                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15152            }
15153
15154            // Extract cid from fullCodePath
15155            int eidx = fullCodePath.lastIndexOf("/");
15156            String subStr1 = fullCodePath.substring(0, eidx);
15157            int sidx = subStr1.lastIndexOf("/");
15158            cid = subStr1.substring(sidx+1, eidx);
15159            setMountPath(subStr1);
15160        }
15161
15162        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15163            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15164                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15165                    instructionSets, null, null, null, 0, null /*certificates*/,
15166                    PackageManager.INSTALL_REASON_UNKNOWN);
15167            this.cid = cid;
15168            setMountPath(PackageHelper.getSdDir(cid));
15169        }
15170
15171        void createCopyFile() {
15172            cid = mInstallerService.allocateExternalStageCidLegacy();
15173        }
15174
15175        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15176            if (origin.staged && origin.cid != null) {
15177                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15178                cid = origin.cid;
15179                setMountPath(PackageHelper.getSdDir(cid));
15180                return PackageManager.INSTALL_SUCCEEDED;
15181            }
15182
15183            if (temp) {
15184                createCopyFile();
15185            } else {
15186                /*
15187                 * Pre-emptively destroy the container since it's destroyed if
15188                 * copying fails due to it existing anyway.
15189                 */
15190                PackageHelper.destroySdDir(cid);
15191            }
15192
15193            final String newMountPath = imcs.copyPackageToContainer(
15194                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15195                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15196
15197            if (newMountPath != null) {
15198                setMountPath(newMountPath);
15199                return PackageManager.INSTALL_SUCCEEDED;
15200            } else {
15201                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15202            }
15203        }
15204
15205        @Override
15206        String getCodePath() {
15207            return packagePath;
15208        }
15209
15210        @Override
15211        String getResourcePath() {
15212            return resourcePath;
15213        }
15214
15215        int doPreInstall(int status) {
15216            if (status != PackageManager.INSTALL_SUCCEEDED) {
15217                // Destroy container
15218                PackageHelper.destroySdDir(cid);
15219            } else {
15220                boolean mounted = PackageHelper.isContainerMounted(cid);
15221                if (!mounted) {
15222                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15223                            Process.SYSTEM_UID);
15224                    if (newMountPath != null) {
15225                        setMountPath(newMountPath);
15226                    } else {
15227                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15228                    }
15229                }
15230            }
15231            return status;
15232        }
15233
15234        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15235            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15236            String newMountPath = null;
15237            if (PackageHelper.isContainerMounted(cid)) {
15238                // Unmount the container
15239                if (!PackageHelper.unMountSdDir(cid)) {
15240                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15241                    return false;
15242                }
15243            }
15244            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15245                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15246                        " which might be stale. Will try to clean up.");
15247                // Clean up the stale container and proceed to recreate.
15248                if (!PackageHelper.destroySdDir(newCacheId)) {
15249                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15250                    return false;
15251                }
15252                // Successfully cleaned up stale container. Try to rename again.
15253                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15254                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15255                            + " inspite of cleaning it up.");
15256                    return false;
15257                }
15258            }
15259            if (!PackageHelper.isContainerMounted(newCacheId)) {
15260                Slog.w(TAG, "Mounting container " + newCacheId);
15261                newMountPath = PackageHelper.mountSdDir(newCacheId,
15262                        getEncryptKey(), Process.SYSTEM_UID);
15263            } else {
15264                newMountPath = PackageHelper.getSdDir(newCacheId);
15265            }
15266            if (newMountPath == null) {
15267                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15268                return false;
15269            }
15270            Log.i(TAG, "Succesfully renamed " + cid +
15271                    " to " + newCacheId +
15272                    " at new path: " + newMountPath);
15273            cid = newCacheId;
15274
15275            final File beforeCodeFile = new File(packagePath);
15276            setMountPath(newMountPath);
15277            final File afterCodeFile = new File(packagePath);
15278
15279            // Reflect the rename in scanned details
15280            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15281            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15282                    afterCodeFile, pkg.baseCodePath));
15283            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15284                    afterCodeFile, pkg.splitCodePaths));
15285
15286            // Reflect the rename in app info
15287            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15288            pkg.setApplicationInfoCodePath(pkg.codePath);
15289            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15290            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15291            pkg.setApplicationInfoResourcePath(pkg.codePath);
15292            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15293            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15294
15295            return true;
15296        }
15297
15298        private void setMountPath(String mountPath) {
15299            final File mountFile = new File(mountPath);
15300
15301            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15302            if (monolithicFile.exists()) {
15303                packagePath = monolithicFile.getAbsolutePath();
15304                if (isFwdLocked()) {
15305                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15306                } else {
15307                    resourcePath = packagePath;
15308                }
15309            } else {
15310                packagePath = mountFile.getAbsolutePath();
15311                resourcePath = packagePath;
15312            }
15313        }
15314
15315        int doPostInstall(int status, int uid) {
15316            if (status != PackageManager.INSTALL_SUCCEEDED) {
15317                cleanUp();
15318            } else {
15319                final int groupOwner;
15320                final String protectedFile;
15321                if (isFwdLocked()) {
15322                    groupOwner = UserHandle.getSharedAppGid(uid);
15323                    protectedFile = RES_FILE_NAME;
15324                } else {
15325                    groupOwner = -1;
15326                    protectedFile = null;
15327                }
15328
15329                if (uid < Process.FIRST_APPLICATION_UID
15330                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15331                    Slog.e(TAG, "Failed to finalize " + cid);
15332                    PackageHelper.destroySdDir(cid);
15333                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15334                }
15335
15336                boolean mounted = PackageHelper.isContainerMounted(cid);
15337                if (!mounted) {
15338                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15339                }
15340            }
15341            return status;
15342        }
15343
15344        private void cleanUp() {
15345            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15346
15347            // Destroy secure container
15348            PackageHelper.destroySdDir(cid);
15349        }
15350
15351        private List<String> getAllCodePaths() {
15352            final File codeFile = new File(getCodePath());
15353            if (codeFile != null && codeFile.exists()) {
15354                try {
15355                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15356                    return pkg.getAllCodePaths();
15357                } catch (PackageParserException e) {
15358                    // Ignored; we tried our best
15359                }
15360            }
15361            return Collections.EMPTY_LIST;
15362        }
15363
15364        void cleanUpResourcesLI() {
15365            // Enumerate all code paths before deleting
15366            cleanUpResourcesLI(getAllCodePaths());
15367        }
15368
15369        private void cleanUpResourcesLI(List<String> allCodePaths) {
15370            cleanUp();
15371            removeDexFiles(allCodePaths, instructionSets);
15372        }
15373
15374        String getPackageName() {
15375            return getAsecPackageName(cid);
15376        }
15377
15378        boolean doPostDeleteLI(boolean delete) {
15379            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15380            final List<String> allCodePaths = getAllCodePaths();
15381            boolean mounted = PackageHelper.isContainerMounted(cid);
15382            if (mounted) {
15383                // Unmount first
15384                if (PackageHelper.unMountSdDir(cid)) {
15385                    mounted = false;
15386                }
15387            }
15388            if (!mounted && delete) {
15389                cleanUpResourcesLI(allCodePaths);
15390            }
15391            return !mounted;
15392        }
15393
15394        @Override
15395        int doPreCopy() {
15396            if (isFwdLocked()) {
15397                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15398                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15399                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15400                }
15401            }
15402
15403            return PackageManager.INSTALL_SUCCEEDED;
15404        }
15405
15406        @Override
15407        int doPostCopy(int uid) {
15408            if (isFwdLocked()) {
15409                if (uid < Process.FIRST_APPLICATION_UID
15410                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15411                                RES_FILE_NAME)) {
15412                    Slog.e(TAG, "Failed to finalize " + cid);
15413                    PackageHelper.destroySdDir(cid);
15414                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15415                }
15416            }
15417
15418            return PackageManager.INSTALL_SUCCEEDED;
15419        }
15420    }
15421
15422    /**
15423     * Logic to handle movement of existing installed applications.
15424     */
15425    class MoveInstallArgs extends InstallArgs {
15426        private File codeFile;
15427        private File resourceFile;
15428
15429        /** New install */
15430        MoveInstallArgs(InstallParams params) {
15431            super(params.origin, params.move, params.observer, params.installFlags,
15432                    params.installerPackageName, params.volumeUuid,
15433                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15434                    params.grantedRuntimePermissions,
15435                    params.traceMethod, params.traceCookie, params.certificates,
15436                    params.installReason);
15437        }
15438
15439        int copyApk(IMediaContainerService imcs, boolean temp) {
15440            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15441                    + move.fromUuid + " to " + move.toUuid);
15442            synchronized (mInstaller) {
15443                try {
15444                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15445                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15446                } catch (InstallerException e) {
15447                    Slog.w(TAG, "Failed to move app", e);
15448                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15449                }
15450            }
15451
15452            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15453            resourceFile = codeFile;
15454            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15455
15456            return PackageManager.INSTALL_SUCCEEDED;
15457        }
15458
15459        int doPreInstall(int status) {
15460            if (status != PackageManager.INSTALL_SUCCEEDED) {
15461                cleanUp(move.toUuid);
15462            }
15463            return status;
15464        }
15465
15466        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15467            if (status != PackageManager.INSTALL_SUCCEEDED) {
15468                cleanUp(move.toUuid);
15469                return false;
15470            }
15471
15472            // Reflect the move in app info
15473            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15474            pkg.setApplicationInfoCodePath(pkg.codePath);
15475            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15476            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15477            pkg.setApplicationInfoResourcePath(pkg.codePath);
15478            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15479            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15480
15481            return true;
15482        }
15483
15484        int doPostInstall(int status, int uid) {
15485            if (status == PackageManager.INSTALL_SUCCEEDED) {
15486                cleanUp(move.fromUuid);
15487            } else {
15488                cleanUp(move.toUuid);
15489            }
15490            return status;
15491        }
15492
15493        @Override
15494        String getCodePath() {
15495            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15496        }
15497
15498        @Override
15499        String getResourcePath() {
15500            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15501        }
15502
15503        private boolean cleanUp(String volumeUuid) {
15504            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15505                    move.dataAppName);
15506            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15507            final int[] userIds = sUserManager.getUserIds();
15508            synchronized (mInstallLock) {
15509                // Clean up both app data and code
15510                // All package moves are frozen until finished
15511                for (int userId : userIds) {
15512                    try {
15513                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15514                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15515                    } catch (InstallerException e) {
15516                        Slog.w(TAG, String.valueOf(e));
15517                    }
15518                }
15519                removeCodePathLI(codeFile);
15520            }
15521            return true;
15522        }
15523
15524        void cleanUpResourcesLI() {
15525            throw new UnsupportedOperationException();
15526        }
15527
15528        boolean doPostDeleteLI(boolean delete) {
15529            throw new UnsupportedOperationException();
15530        }
15531    }
15532
15533    static String getAsecPackageName(String packageCid) {
15534        int idx = packageCid.lastIndexOf("-");
15535        if (idx == -1) {
15536            return packageCid;
15537        }
15538        return packageCid.substring(0, idx);
15539    }
15540
15541    // Utility method used to create code paths based on package name and available index.
15542    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15543        String idxStr = "";
15544        int idx = 1;
15545        // Fall back to default value of idx=1 if prefix is not
15546        // part of oldCodePath
15547        if (oldCodePath != null) {
15548            String subStr = oldCodePath;
15549            // Drop the suffix right away
15550            if (suffix != null && subStr.endsWith(suffix)) {
15551                subStr = subStr.substring(0, subStr.length() - suffix.length());
15552            }
15553            // If oldCodePath already contains prefix find out the
15554            // ending index to either increment or decrement.
15555            int sidx = subStr.lastIndexOf(prefix);
15556            if (sidx != -1) {
15557                subStr = subStr.substring(sidx + prefix.length());
15558                if (subStr != null) {
15559                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15560                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15561                    }
15562                    try {
15563                        idx = Integer.parseInt(subStr);
15564                        if (idx <= 1) {
15565                            idx++;
15566                        } else {
15567                            idx--;
15568                        }
15569                    } catch(NumberFormatException e) {
15570                    }
15571                }
15572            }
15573        }
15574        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15575        return prefix + idxStr;
15576    }
15577
15578    private File getNextCodePath(File targetDir, String packageName) {
15579        File result;
15580        SecureRandom random = new SecureRandom();
15581        byte[] bytes = new byte[16];
15582        do {
15583            random.nextBytes(bytes);
15584            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15585            result = new File(targetDir, packageName + "-" + suffix);
15586        } while (result.exists());
15587        return result;
15588    }
15589
15590    // Utility method that returns the relative package path with respect
15591    // to the installation directory. Like say for /data/data/com.test-1.apk
15592    // string com.test-1 is returned.
15593    static String deriveCodePathName(String codePath) {
15594        if (codePath == null) {
15595            return null;
15596        }
15597        final File codeFile = new File(codePath);
15598        final String name = codeFile.getName();
15599        if (codeFile.isDirectory()) {
15600            return name;
15601        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15602            final int lastDot = name.lastIndexOf('.');
15603            return name.substring(0, lastDot);
15604        } else {
15605            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15606            return null;
15607        }
15608    }
15609
15610    static class PackageInstalledInfo {
15611        String name;
15612        int uid;
15613        // The set of users that originally had this package installed.
15614        int[] origUsers;
15615        // The set of users that now have this package installed.
15616        int[] newUsers;
15617        PackageParser.Package pkg;
15618        int returnCode;
15619        String returnMsg;
15620        PackageRemovedInfo removedInfo;
15621        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15622
15623        public void setError(int code, String msg) {
15624            setReturnCode(code);
15625            setReturnMessage(msg);
15626            Slog.w(TAG, msg);
15627        }
15628
15629        public void setError(String msg, PackageParserException e) {
15630            setReturnCode(e.error);
15631            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15632            Slog.w(TAG, msg, e);
15633        }
15634
15635        public void setError(String msg, PackageManagerException e) {
15636            returnCode = e.error;
15637            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15638            Slog.w(TAG, msg, e);
15639        }
15640
15641        public void setReturnCode(int returnCode) {
15642            this.returnCode = returnCode;
15643            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15644            for (int i = 0; i < childCount; i++) {
15645                addedChildPackages.valueAt(i).returnCode = returnCode;
15646            }
15647        }
15648
15649        private void setReturnMessage(String returnMsg) {
15650            this.returnMsg = returnMsg;
15651            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15652            for (int i = 0; i < childCount; i++) {
15653                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15654            }
15655        }
15656
15657        // In some error cases we want to convey more info back to the observer
15658        String origPackage;
15659        String origPermission;
15660    }
15661
15662    /*
15663     * Install a non-existing package.
15664     */
15665    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15666            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15667            PackageInstalledInfo res, int installReason) {
15668        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15669
15670        // Remember this for later, in case we need to rollback this install
15671        String pkgName = pkg.packageName;
15672
15673        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15674
15675        synchronized(mPackages) {
15676            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15677            if (renamedPackage != null) {
15678                // A package with the same name is already installed, though
15679                // it has been renamed to an older name.  The package we
15680                // are trying to install should be installed as an update to
15681                // the existing one, but that has not been requested, so bail.
15682                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15683                        + " without first uninstalling package running as "
15684                        + renamedPackage);
15685                return;
15686            }
15687            if (mPackages.containsKey(pkgName)) {
15688                // Don't allow installation over an existing package with the same name.
15689                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15690                        + " without first uninstalling.");
15691                return;
15692            }
15693        }
15694
15695        try {
15696            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15697                    System.currentTimeMillis(), user);
15698
15699            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15700
15701            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15702                prepareAppDataAfterInstallLIF(newPackage);
15703
15704            } else {
15705                // Remove package from internal structures, but keep around any
15706                // data that might have already existed
15707                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15708                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15709            }
15710        } catch (PackageManagerException e) {
15711            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15712        }
15713
15714        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15715    }
15716
15717    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15718        // Can't rotate keys during boot or if sharedUser.
15719        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15720                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15721            return false;
15722        }
15723        // app is using upgradeKeySets; make sure all are valid
15724        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15725        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15726        for (int i = 0; i < upgradeKeySets.length; i++) {
15727            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15728                Slog.wtf(TAG, "Package "
15729                         + (oldPs.name != null ? oldPs.name : "<null>")
15730                         + " contains upgrade-key-set reference to unknown key-set: "
15731                         + upgradeKeySets[i]
15732                         + " reverting to signatures check.");
15733                return false;
15734            }
15735        }
15736        return true;
15737    }
15738
15739    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15740        // Upgrade keysets are being used.  Determine if new package has a superset of the
15741        // required keys.
15742        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15743        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15744        for (int i = 0; i < upgradeKeySets.length; i++) {
15745            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15746            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15747                return true;
15748            }
15749        }
15750        return false;
15751    }
15752
15753    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15754        try (DigestInputStream digestStream =
15755                new DigestInputStream(new FileInputStream(file), digest)) {
15756            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15757        }
15758    }
15759
15760    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15761            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15762            int installReason) {
15763        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15764
15765        final PackageParser.Package oldPackage;
15766        final String pkgName = pkg.packageName;
15767        final int[] allUsers;
15768        final int[] installedUsers;
15769
15770        synchronized(mPackages) {
15771            oldPackage = mPackages.get(pkgName);
15772            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15773
15774            // don't allow upgrade to target a release SDK from a pre-release SDK
15775            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15776                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15777            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15778                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15779            if (oldTargetsPreRelease
15780                    && !newTargetsPreRelease
15781                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15782                Slog.w(TAG, "Can't install package targeting released sdk");
15783                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15784                return;
15785            }
15786
15787            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15788
15789            // verify signatures are valid
15790            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15791                if (!checkUpgradeKeySetLP(ps, pkg)) {
15792                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15793                            "New package not signed by keys specified by upgrade-keysets: "
15794                                    + pkgName);
15795                    return;
15796                }
15797            } else {
15798                // default to original signature matching
15799                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15800                        != PackageManager.SIGNATURE_MATCH) {
15801                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15802                            "New package has a different signature: " + pkgName);
15803                    return;
15804                }
15805            }
15806
15807            // don't allow a system upgrade unless the upgrade hash matches
15808            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15809                byte[] digestBytes = null;
15810                try {
15811                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15812                    updateDigest(digest, new File(pkg.baseCodePath));
15813                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15814                        for (String path : pkg.splitCodePaths) {
15815                            updateDigest(digest, new File(path));
15816                        }
15817                    }
15818                    digestBytes = digest.digest();
15819                } catch (NoSuchAlgorithmException | IOException e) {
15820                    res.setError(INSTALL_FAILED_INVALID_APK,
15821                            "Could not compute hash: " + pkgName);
15822                    return;
15823                }
15824                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15825                    res.setError(INSTALL_FAILED_INVALID_APK,
15826                            "New package fails restrict-update check: " + pkgName);
15827                    return;
15828                }
15829                // retain upgrade restriction
15830                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15831            }
15832
15833            // Check for shared user id changes
15834            String invalidPackageName =
15835                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15836            if (invalidPackageName != null) {
15837                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15838                        "Package " + invalidPackageName + " tried to change user "
15839                                + oldPackage.mSharedUserId);
15840                return;
15841            }
15842
15843            // In case of rollback, remember per-user/profile install state
15844            allUsers = sUserManager.getUserIds();
15845            installedUsers = ps.queryInstalledUsers(allUsers, true);
15846
15847            // don't allow an upgrade from full to ephemeral
15848            if (isInstantApp) {
15849                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15850                    for (int currentUser : allUsers) {
15851                        if (!ps.getInstantApp(currentUser)) {
15852                            // can't downgrade from full to instant
15853                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15854                                    + " for user: " + currentUser);
15855                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15856                            return;
15857                        }
15858                    }
15859                } else if (!ps.getInstantApp(user.getIdentifier())) {
15860                    // can't downgrade from full to instant
15861                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15862                            + " for user: " + user.getIdentifier());
15863                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15864                    return;
15865                }
15866            }
15867        }
15868
15869        // Update what is removed
15870        res.removedInfo = new PackageRemovedInfo();
15871        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15872        res.removedInfo.removedPackage = oldPackage.packageName;
15873        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15874        res.removedInfo.isUpdate = true;
15875        res.removedInfo.origUsers = installedUsers;
15876        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15877        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15878        for (int i = 0; i < installedUsers.length; i++) {
15879            final int userId = installedUsers[i];
15880            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15881        }
15882
15883        final int childCount = (oldPackage.childPackages != null)
15884                ? oldPackage.childPackages.size() : 0;
15885        for (int i = 0; i < childCount; i++) {
15886            boolean childPackageUpdated = false;
15887            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15888            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15889            if (res.addedChildPackages != null) {
15890                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15891                if (childRes != null) {
15892                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15893                    childRes.removedInfo.removedPackage = childPkg.packageName;
15894                    childRes.removedInfo.isUpdate = true;
15895                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15896                    childPackageUpdated = true;
15897                }
15898            }
15899            if (!childPackageUpdated) {
15900                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15901                childRemovedRes.removedPackage = childPkg.packageName;
15902                childRemovedRes.isUpdate = false;
15903                childRemovedRes.dataRemoved = true;
15904                synchronized (mPackages) {
15905                    if (childPs != null) {
15906                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15907                    }
15908                }
15909                if (res.removedInfo.removedChildPackages == null) {
15910                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15911                }
15912                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15913            }
15914        }
15915
15916        boolean sysPkg = (isSystemApp(oldPackage));
15917        if (sysPkg) {
15918            // Set the system/privileged flags as needed
15919            final boolean privileged =
15920                    (oldPackage.applicationInfo.privateFlags
15921                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15922            final int systemPolicyFlags = policyFlags
15923                    | PackageParser.PARSE_IS_SYSTEM
15924                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15925
15926            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15927                    user, allUsers, installerPackageName, res, installReason);
15928        } else {
15929            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15930                    user, allUsers, installerPackageName, res, installReason);
15931        }
15932    }
15933
15934    public List<String> getPreviousCodePaths(String packageName) {
15935        final PackageSetting ps = mSettings.mPackages.get(packageName);
15936        final List<String> result = new ArrayList<String>();
15937        if (ps != null && ps.oldCodePaths != null) {
15938            result.addAll(ps.oldCodePaths);
15939        }
15940        return result;
15941    }
15942
15943    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15944            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15945            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15946            int installReason) {
15947        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15948                + deletedPackage);
15949
15950        String pkgName = deletedPackage.packageName;
15951        boolean deletedPkg = true;
15952        boolean addedPkg = false;
15953        boolean updatedSettings = false;
15954        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15955        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15956                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15957
15958        final long origUpdateTime = (pkg.mExtras != null)
15959                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15960
15961        // First delete the existing package while retaining the data directory
15962        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15963                res.removedInfo, true, pkg)) {
15964            // If the existing package wasn't successfully deleted
15965            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15966            deletedPkg = false;
15967        } else {
15968            // Successfully deleted the old package; proceed with replace.
15969
15970            // If deleted package lived in a container, give users a chance to
15971            // relinquish resources before killing.
15972            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15973                if (DEBUG_INSTALL) {
15974                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15975                }
15976                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15977                final ArrayList<String> pkgList = new ArrayList<String>(1);
15978                pkgList.add(deletedPackage.applicationInfo.packageName);
15979                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15980            }
15981
15982            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15983                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15984            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15985
15986            try {
15987                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15988                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15989                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15990                        installReason);
15991
15992                // Update the in-memory copy of the previous code paths.
15993                PackageSetting ps = mSettings.mPackages.get(pkgName);
15994                if (!killApp) {
15995                    if (ps.oldCodePaths == null) {
15996                        ps.oldCodePaths = new ArraySet<>();
15997                    }
15998                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15999                    if (deletedPackage.splitCodePaths != null) {
16000                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16001                    }
16002                } else {
16003                    ps.oldCodePaths = null;
16004                }
16005                if (ps.childPackageNames != null) {
16006                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16007                        final String childPkgName = ps.childPackageNames.get(i);
16008                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16009                        childPs.oldCodePaths = ps.oldCodePaths;
16010                    }
16011                }
16012                // set instant app status, but, only if it's explicitly specified
16013                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16014                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16015                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16016                prepareAppDataAfterInstallLIF(newPackage);
16017                addedPkg = true;
16018                mDexManager.notifyPackageUpdated(newPackage.packageName,
16019                        newPackage.baseCodePath, newPackage.splitCodePaths);
16020            } catch (PackageManagerException e) {
16021                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16022            }
16023        }
16024
16025        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16026            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16027
16028            // Revert all internal state mutations and added folders for the failed install
16029            if (addedPkg) {
16030                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16031                        res.removedInfo, true, null);
16032            }
16033
16034            // Restore the old package
16035            if (deletedPkg) {
16036                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16037                File restoreFile = new File(deletedPackage.codePath);
16038                // Parse old package
16039                boolean oldExternal = isExternal(deletedPackage);
16040                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16041                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16042                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16043                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16044                try {
16045                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16046                            null);
16047                } catch (PackageManagerException e) {
16048                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16049                            + e.getMessage());
16050                    return;
16051                }
16052
16053                synchronized (mPackages) {
16054                    // Ensure the installer package name up to date
16055                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16056
16057                    // Update permissions for restored package
16058                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16059
16060                    mSettings.writeLPr();
16061                }
16062
16063                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16064            }
16065        } else {
16066            synchronized (mPackages) {
16067                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16068                if (ps != null) {
16069                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16070                    if (res.removedInfo.removedChildPackages != null) {
16071                        final int childCount = res.removedInfo.removedChildPackages.size();
16072                        // Iterate in reverse as we may modify the collection
16073                        for (int i = childCount - 1; i >= 0; i--) {
16074                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16075                            if (res.addedChildPackages.containsKey(childPackageName)) {
16076                                res.removedInfo.removedChildPackages.removeAt(i);
16077                            } else {
16078                                PackageRemovedInfo childInfo = res.removedInfo
16079                                        .removedChildPackages.valueAt(i);
16080                                childInfo.removedForAllUsers = mPackages.get(
16081                                        childInfo.removedPackage) == null;
16082                            }
16083                        }
16084                    }
16085                }
16086            }
16087        }
16088    }
16089
16090    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16091            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16092            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16093            int installReason) {
16094        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16095                + ", old=" + deletedPackage);
16096
16097        final boolean disabledSystem;
16098
16099        // Remove existing system package
16100        removePackageLI(deletedPackage, true);
16101
16102        synchronized (mPackages) {
16103            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16104        }
16105        if (!disabledSystem) {
16106            // We didn't need to disable the .apk as a current system package,
16107            // which means we are replacing another update that is already
16108            // installed.  We need to make sure to delete the older one's .apk.
16109            res.removedInfo.args = createInstallArgsForExisting(0,
16110                    deletedPackage.applicationInfo.getCodePath(),
16111                    deletedPackage.applicationInfo.getResourcePath(),
16112                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16113        } else {
16114            res.removedInfo.args = null;
16115        }
16116
16117        // Successfully disabled the old package. Now proceed with re-installation
16118        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16119                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16120        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16121
16122        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16123        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16124                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16125
16126        PackageParser.Package newPackage = null;
16127        try {
16128            // Add the package to the internal data structures
16129            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16130
16131            // Set the update and install times
16132            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16133            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16134                    System.currentTimeMillis());
16135
16136            // Update the package dynamic state if succeeded
16137            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16138                // Now that the install succeeded make sure we remove data
16139                // directories for any child package the update removed.
16140                final int deletedChildCount = (deletedPackage.childPackages != null)
16141                        ? deletedPackage.childPackages.size() : 0;
16142                final int newChildCount = (newPackage.childPackages != null)
16143                        ? newPackage.childPackages.size() : 0;
16144                for (int i = 0; i < deletedChildCount; i++) {
16145                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16146                    boolean childPackageDeleted = true;
16147                    for (int j = 0; j < newChildCount; j++) {
16148                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16149                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16150                            childPackageDeleted = false;
16151                            break;
16152                        }
16153                    }
16154                    if (childPackageDeleted) {
16155                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16156                                deletedChildPkg.packageName);
16157                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16158                            PackageRemovedInfo removedChildRes = res.removedInfo
16159                                    .removedChildPackages.get(deletedChildPkg.packageName);
16160                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16161                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16162                        }
16163                    }
16164                }
16165
16166                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16167                        installReason);
16168                prepareAppDataAfterInstallLIF(newPackage);
16169
16170                mDexManager.notifyPackageUpdated(newPackage.packageName,
16171                            newPackage.baseCodePath, newPackage.splitCodePaths);
16172            }
16173        } catch (PackageManagerException e) {
16174            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16175            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16176        }
16177
16178        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16179            // Re installation failed. Restore old information
16180            // Remove new pkg information
16181            if (newPackage != null) {
16182                removeInstalledPackageLI(newPackage, true);
16183            }
16184            // Add back the old system package
16185            try {
16186                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16187            } catch (PackageManagerException e) {
16188                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16189            }
16190
16191            synchronized (mPackages) {
16192                if (disabledSystem) {
16193                    enableSystemPackageLPw(deletedPackage);
16194                }
16195
16196                // Ensure the installer package name up to date
16197                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16198
16199                // Update permissions for restored package
16200                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16201
16202                mSettings.writeLPr();
16203            }
16204
16205            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16206                    + " after failed upgrade");
16207        }
16208    }
16209
16210    /**
16211     * Checks whether the parent or any of the child packages have a change shared
16212     * user. For a package to be a valid update the shred users of the parent and
16213     * the children should match. We may later support changing child shared users.
16214     * @param oldPkg The updated package.
16215     * @param newPkg The update package.
16216     * @return The shared user that change between the versions.
16217     */
16218    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16219            PackageParser.Package newPkg) {
16220        // Check parent shared user
16221        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16222            return newPkg.packageName;
16223        }
16224        // Check child shared users
16225        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16226        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16227        for (int i = 0; i < newChildCount; i++) {
16228            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16229            // If this child was present, did it have the same shared user?
16230            for (int j = 0; j < oldChildCount; j++) {
16231                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16232                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16233                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16234                    return newChildPkg.packageName;
16235                }
16236            }
16237        }
16238        return null;
16239    }
16240
16241    private void removeNativeBinariesLI(PackageSetting ps) {
16242        // Remove the lib path for the parent package
16243        if (ps != null) {
16244            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16245            // Remove the lib path for the child packages
16246            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16247            for (int i = 0; i < childCount; i++) {
16248                PackageSetting childPs = null;
16249                synchronized (mPackages) {
16250                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16251                }
16252                if (childPs != null) {
16253                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16254                            .legacyNativeLibraryPathString);
16255                }
16256            }
16257        }
16258    }
16259
16260    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16261        // Enable the parent package
16262        mSettings.enableSystemPackageLPw(pkg.packageName);
16263        // Enable the child packages
16264        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16265        for (int i = 0; i < childCount; i++) {
16266            PackageParser.Package childPkg = pkg.childPackages.get(i);
16267            mSettings.enableSystemPackageLPw(childPkg.packageName);
16268        }
16269    }
16270
16271    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16272            PackageParser.Package newPkg) {
16273        // Disable the parent package (parent always replaced)
16274        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16275        // Disable the child packages
16276        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16277        for (int i = 0; i < childCount; i++) {
16278            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16279            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16280            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16281        }
16282        return disabled;
16283    }
16284
16285    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16286            String installerPackageName) {
16287        // Enable the parent package
16288        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16289        // Enable the child packages
16290        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16291        for (int i = 0; i < childCount; i++) {
16292            PackageParser.Package childPkg = pkg.childPackages.get(i);
16293            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16294        }
16295    }
16296
16297    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16298        // Collect all used permissions in the UID
16299        ArraySet<String> usedPermissions = new ArraySet<>();
16300        final int packageCount = su.packages.size();
16301        for (int i = 0; i < packageCount; i++) {
16302            PackageSetting ps = su.packages.valueAt(i);
16303            if (ps.pkg == null) {
16304                continue;
16305            }
16306            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16307            for (int j = 0; j < requestedPermCount; j++) {
16308                String permission = ps.pkg.requestedPermissions.get(j);
16309                BasePermission bp = mSettings.mPermissions.get(permission);
16310                if (bp != null) {
16311                    usedPermissions.add(permission);
16312                }
16313            }
16314        }
16315
16316        PermissionsState permissionsState = su.getPermissionsState();
16317        // Prune install permissions
16318        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16319        final int installPermCount = installPermStates.size();
16320        for (int i = installPermCount - 1; i >= 0;  i--) {
16321            PermissionState permissionState = installPermStates.get(i);
16322            if (!usedPermissions.contains(permissionState.getName())) {
16323                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16324                if (bp != null) {
16325                    permissionsState.revokeInstallPermission(bp);
16326                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16327                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16328                }
16329            }
16330        }
16331
16332        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16333
16334        // Prune runtime permissions
16335        for (int userId : allUserIds) {
16336            List<PermissionState> runtimePermStates = permissionsState
16337                    .getRuntimePermissionStates(userId);
16338            final int runtimePermCount = runtimePermStates.size();
16339            for (int i = runtimePermCount - 1; i >= 0; i--) {
16340                PermissionState permissionState = runtimePermStates.get(i);
16341                if (!usedPermissions.contains(permissionState.getName())) {
16342                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16343                    if (bp != null) {
16344                        permissionsState.revokeRuntimePermission(bp, userId);
16345                        permissionsState.updatePermissionFlags(bp, userId,
16346                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16347                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16348                                runtimePermissionChangedUserIds, userId);
16349                    }
16350                }
16351            }
16352        }
16353
16354        return runtimePermissionChangedUserIds;
16355    }
16356
16357    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16358            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16359        // Update the parent package setting
16360        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16361                res, user, installReason);
16362        // Update the child packages setting
16363        final int childCount = (newPackage.childPackages != null)
16364                ? newPackage.childPackages.size() : 0;
16365        for (int i = 0; i < childCount; i++) {
16366            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16367            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16368            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16369                    childRes.origUsers, childRes, user, installReason);
16370        }
16371    }
16372
16373    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16374            String installerPackageName, int[] allUsers, int[] installedForUsers,
16375            PackageInstalledInfo res, UserHandle user, int installReason) {
16376        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16377
16378        String pkgName = newPackage.packageName;
16379        synchronized (mPackages) {
16380            //write settings. the installStatus will be incomplete at this stage.
16381            //note that the new package setting would have already been
16382            //added to mPackages. It hasn't been persisted yet.
16383            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16384            // TODO: Remove this write? It's also written at the end of this method
16385            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16386            mSettings.writeLPr();
16387            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16388        }
16389
16390        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16391        synchronized (mPackages) {
16392            updatePermissionsLPw(newPackage.packageName, newPackage,
16393                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16394                            ? UPDATE_PERMISSIONS_ALL : 0));
16395            // For system-bundled packages, we assume that installing an upgraded version
16396            // of the package implies that the user actually wants to run that new code,
16397            // so we enable the package.
16398            PackageSetting ps = mSettings.mPackages.get(pkgName);
16399            final int userId = user.getIdentifier();
16400            if (ps != null) {
16401                if (isSystemApp(newPackage)) {
16402                    if (DEBUG_INSTALL) {
16403                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16404                    }
16405                    // Enable system package for requested users
16406                    if (res.origUsers != null) {
16407                        for (int origUserId : res.origUsers) {
16408                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16409                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16410                                        origUserId, installerPackageName);
16411                            }
16412                        }
16413                    }
16414                    // Also convey the prior install/uninstall state
16415                    if (allUsers != null && installedForUsers != null) {
16416                        for (int currentUserId : allUsers) {
16417                            final boolean installed = ArrayUtils.contains(
16418                                    installedForUsers, currentUserId);
16419                            if (DEBUG_INSTALL) {
16420                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16421                            }
16422                            ps.setInstalled(installed, currentUserId);
16423                        }
16424                        // these install state changes will be persisted in the
16425                        // upcoming call to mSettings.writeLPr().
16426                    }
16427                }
16428                // It's implied that when a user requests installation, they want the app to be
16429                // installed and enabled.
16430                if (userId != UserHandle.USER_ALL) {
16431                    ps.setInstalled(true, userId);
16432                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16433                }
16434
16435                // When replacing an existing package, preserve the original install reason for all
16436                // users that had the package installed before.
16437                final Set<Integer> previousUserIds = new ArraySet<>();
16438                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16439                    final int installReasonCount = res.removedInfo.installReasons.size();
16440                    for (int i = 0; i < installReasonCount; i++) {
16441                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16442                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16443                        ps.setInstallReason(previousInstallReason, previousUserId);
16444                        previousUserIds.add(previousUserId);
16445                    }
16446                }
16447
16448                // Set install reason for users that are having the package newly installed.
16449                if (userId == UserHandle.USER_ALL) {
16450                    for (int currentUserId : sUserManager.getUserIds()) {
16451                        if (!previousUserIds.contains(currentUserId)) {
16452                            ps.setInstallReason(installReason, currentUserId);
16453                        }
16454                    }
16455                } else if (!previousUserIds.contains(userId)) {
16456                    ps.setInstallReason(installReason, userId);
16457                }
16458                mSettings.writeKernelMappingLPr(ps);
16459            }
16460            res.name = pkgName;
16461            res.uid = newPackage.applicationInfo.uid;
16462            res.pkg = newPackage;
16463            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16464            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16465            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16466            //to update install status
16467            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16468            mSettings.writeLPr();
16469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16470        }
16471
16472        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16473    }
16474
16475    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16476        try {
16477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16478            installPackageLI(args, res);
16479        } finally {
16480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16481        }
16482    }
16483
16484    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16485        final int installFlags = args.installFlags;
16486        final String installerPackageName = args.installerPackageName;
16487        final String volumeUuid = args.volumeUuid;
16488        final File tmpPackageFile = new File(args.getCodePath());
16489        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16490        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16491                || (args.volumeUuid != null));
16492        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16493        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16494        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16495        boolean replace = false;
16496        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16497        if (args.move != null) {
16498            // moving a complete application; perform an initial scan on the new install location
16499            scanFlags |= SCAN_INITIAL;
16500        }
16501        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16502            scanFlags |= SCAN_DONT_KILL_APP;
16503        }
16504        if (instantApp) {
16505            scanFlags |= SCAN_AS_INSTANT_APP;
16506        }
16507        if (fullApp) {
16508            scanFlags |= SCAN_AS_FULL_APP;
16509        }
16510
16511        // Result object to be returned
16512        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16513
16514        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16515
16516        // Sanity check
16517        if (instantApp && (forwardLocked || onExternal)) {
16518            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16519                    + " external=" + onExternal);
16520            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16521            return;
16522        }
16523
16524        // Retrieve PackageSettings and parse package
16525        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16526                | PackageParser.PARSE_ENFORCE_CODE
16527                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16528                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16529                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16530                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16531        PackageParser pp = new PackageParser();
16532        pp.setSeparateProcesses(mSeparateProcesses);
16533        pp.setDisplayMetrics(mMetrics);
16534        pp.setCallback(mPackageParserCallback);
16535
16536        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16537        final PackageParser.Package pkg;
16538        try {
16539            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16540        } catch (PackageParserException e) {
16541            res.setError("Failed parse during installPackageLI", e);
16542            return;
16543        } finally {
16544            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16545        }
16546
16547        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16548        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16549            Slog.w(TAG, "Instant app package " + pkg.packageName
16550                    + " does not target O, this will be a fatal error.");
16551            // STOPSHIP: Make this a fatal error
16552            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16553        }
16554        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16555            Slog.w(TAG, "Instant app package " + pkg.packageName
16556                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16557            // STOPSHIP: Make this a fatal error
16558            pkg.applicationInfo.targetSandboxVersion = 2;
16559        }
16560
16561        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16562            // Static shared libraries have synthetic package names
16563            renameStaticSharedLibraryPackage(pkg);
16564
16565            // No static shared libs on external storage
16566            if (onExternal) {
16567                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16568                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16569                        "Packages declaring static-shared libs cannot be updated");
16570                return;
16571            }
16572        }
16573
16574        // If we are installing a clustered package add results for the children
16575        if (pkg.childPackages != null) {
16576            synchronized (mPackages) {
16577                final int childCount = pkg.childPackages.size();
16578                for (int i = 0; i < childCount; i++) {
16579                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16580                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16581                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16582                    childRes.pkg = childPkg;
16583                    childRes.name = childPkg.packageName;
16584                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16585                    if (childPs != null) {
16586                        childRes.origUsers = childPs.queryInstalledUsers(
16587                                sUserManager.getUserIds(), true);
16588                    }
16589                    if ((mPackages.containsKey(childPkg.packageName))) {
16590                        childRes.removedInfo = new PackageRemovedInfo();
16591                        childRes.removedInfo.removedPackage = childPkg.packageName;
16592                    }
16593                    if (res.addedChildPackages == null) {
16594                        res.addedChildPackages = new ArrayMap<>();
16595                    }
16596                    res.addedChildPackages.put(childPkg.packageName, childRes);
16597                }
16598            }
16599        }
16600
16601        // If package doesn't declare API override, mark that we have an install
16602        // time CPU ABI override.
16603        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16604            pkg.cpuAbiOverride = args.abiOverride;
16605        }
16606
16607        String pkgName = res.name = pkg.packageName;
16608        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16609            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16610                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16611                return;
16612            }
16613        }
16614
16615        try {
16616            // either use what we've been given or parse directly from the APK
16617            if (args.certificates != null) {
16618                try {
16619                    PackageParser.populateCertificates(pkg, args.certificates);
16620                } catch (PackageParserException e) {
16621                    // there was something wrong with the certificates we were given;
16622                    // try to pull them from the APK
16623                    PackageParser.collectCertificates(pkg, parseFlags);
16624                }
16625            } else {
16626                PackageParser.collectCertificates(pkg, parseFlags);
16627            }
16628        } catch (PackageParserException e) {
16629            res.setError("Failed collect during installPackageLI", e);
16630            return;
16631        }
16632
16633        // Get rid of all references to package scan path via parser.
16634        pp = null;
16635        String oldCodePath = null;
16636        boolean systemApp = false;
16637        synchronized (mPackages) {
16638            // Check if installing already existing package
16639            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16640                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16641                if (pkg.mOriginalPackages != null
16642                        && pkg.mOriginalPackages.contains(oldName)
16643                        && mPackages.containsKey(oldName)) {
16644                    // This package is derived from an original package,
16645                    // and this device has been updating from that original
16646                    // name.  We must continue using the original name, so
16647                    // rename the new package here.
16648                    pkg.setPackageName(oldName);
16649                    pkgName = pkg.packageName;
16650                    replace = true;
16651                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16652                            + oldName + " pkgName=" + pkgName);
16653                } else if (mPackages.containsKey(pkgName)) {
16654                    // This package, under its official name, already exists
16655                    // on the device; we should replace it.
16656                    replace = true;
16657                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16658                }
16659
16660                // Child packages are installed through the parent package
16661                if (pkg.parentPackage != null) {
16662                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16663                            "Package " + pkg.packageName + " is child of package "
16664                                    + pkg.parentPackage.parentPackage + ". Child packages "
16665                                    + "can be updated only through the parent package.");
16666                    return;
16667                }
16668
16669                if (replace) {
16670                    // Prevent apps opting out from runtime permissions
16671                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16672                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16673                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16674                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16675                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16676                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16677                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16678                                        + " doesn't support runtime permissions but the old"
16679                                        + " target SDK " + oldTargetSdk + " does.");
16680                        return;
16681                    }
16682
16683                    // Prevent installing of child packages
16684                    if (oldPackage.parentPackage != null) {
16685                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16686                                "Package " + pkg.packageName + " is child of package "
16687                                        + oldPackage.parentPackage + ". Child packages "
16688                                        + "can be updated only through the parent package.");
16689                        return;
16690                    }
16691                }
16692            }
16693
16694            PackageSetting ps = mSettings.mPackages.get(pkgName);
16695            if (ps != null) {
16696                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16697
16698                // Static shared libs have same package with different versions where
16699                // we internally use a synthetic package name to allow multiple versions
16700                // of the same package, therefore we need to compare signatures against
16701                // the package setting for the latest library version.
16702                PackageSetting signatureCheckPs = ps;
16703                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16704                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16705                    if (libraryEntry != null) {
16706                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16707                    }
16708                }
16709
16710                // Quick sanity check that we're signed correctly if updating;
16711                // we'll check this again later when scanning, but we want to
16712                // bail early here before tripping over redefined permissions.
16713                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16714                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16715                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16716                                + pkg.packageName + " upgrade keys do not match the "
16717                                + "previously installed version");
16718                        return;
16719                    }
16720                } else {
16721                    try {
16722                        verifySignaturesLP(signatureCheckPs, pkg);
16723                    } catch (PackageManagerException e) {
16724                        res.setError(e.error, e.getMessage());
16725                        return;
16726                    }
16727                }
16728
16729                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16730                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16731                    systemApp = (ps.pkg.applicationInfo.flags &
16732                            ApplicationInfo.FLAG_SYSTEM) != 0;
16733                }
16734                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16735            }
16736
16737            int N = pkg.permissions.size();
16738            for (int i = N-1; i >= 0; i--) {
16739                PackageParser.Permission perm = pkg.permissions.get(i);
16740                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16741
16742                // Don't allow anyone but the platform to define ephemeral permissions.
16743                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16744                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16745                    Slog.w(TAG, "Package " + pkg.packageName
16746                            + " attempting to delcare ephemeral permission "
16747                            + perm.info.name + "; Removing ephemeral.");
16748                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16749                }
16750                // Check whether the newly-scanned package wants to define an already-defined perm
16751                if (bp != null) {
16752                    // If the defining package is signed with our cert, it's okay.  This
16753                    // also includes the "updating the same package" case, of course.
16754                    // "updating same package" could also involve key-rotation.
16755                    final boolean sigsOk;
16756                    if (bp.sourcePackage.equals(pkg.packageName)
16757                            && (bp.packageSetting instanceof PackageSetting)
16758                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16759                                    scanFlags))) {
16760                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16761                    } else {
16762                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16763                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16764                    }
16765                    if (!sigsOk) {
16766                        // If the owning package is the system itself, we log but allow
16767                        // install to proceed; we fail the install on all other permission
16768                        // redefinitions.
16769                        if (!bp.sourcePackage.equals("android")) {
16770                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16771                                    + pkg.packageName + " attempting to redeclare permission "
16772                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16773                            res.origPermission = perm.info.name;
16774                            res.origPackage = bp.sourcePackage;
16775                            return;
16776                        } else {
16777                            Slog.w(TAG, "Package " + pkg.packageName
16778                                    + " attempting to redeclare system permission "
16779                                    + perm.info.name + "; ignoring new declaration");
16780                            pkg.permissions.remove(i);
16781                        }
16782                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16783                        // Prevent apps to change protection level to dangerous from any other
16784                        // type as this would allow a privilege escalation where an app adds a
16785                        // normal/signature permission in other app's group and later redefines
16786                        // it as dangerous leading to the group auto-grant.
16787                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16788                                == PermissionInfo.PROTECTION_DANGEROUS) {
16789                            if (bp != null && !bp.isRuntime()) {
16790                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16791                                        + "non-runtime permission " + perm.info.name
16792                                        + " to runtime; keeping old protection level");
16793                                perm.info.protectionLevel = bp.protectionLevel;
16794                            }
16795                        }
16796                    }
16797                }
16798            }
16799        }
16800
16801        if (systemApp) {
16802            if (onExternal) {
16803                // Abort update; system app can't be replaced with app on sdcard
16804                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16805                        "Cannot install updates to system apps on sdcard");
16806                return;
16807            } else if (instantApp) {
16808                // Abort update; system app can't be replaced with an instant app
16809                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16810                        "Cannot update a system app with an instant app");
16811                return;
16812            }
16813        }
16814
16815        if (args.move != null) {
16816            // We did an in-place move, so dex is ready to roll
16817            scanFlags |= SCAN_NO_DEX;
16818            scanFlags |= SCAN_MOVE;
16819
16820            synchronized (mPackages) {
16821                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16822                if (ps == null) {
16823                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16824                            "Missing settings for moved package " + pkgName);
16825                }
16826
16827                // We moved the entire application as-is, so bring over the
16828                // previously derived ABI information.
16829                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16830                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16831            }
16832
16833        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16834            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16835            scanFlags |= SCAN_NO_DEX;
16836
16837            try {
16838                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16839                    args.abiOverride : pkg.cpuAbiOverride);
16840                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16841                        true /*extractLibs*/, mAppLib32InstallDir);
16842            } catch (PackageManagerException pme) {
16843                Slog.e(TAG, "Error deriving application ABI", pme);
16844                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16845                return;
16846            }
16847
16848            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16849            // Do not run PackageDexOptimizer through the local performDexOpt
16850            // method because `pkg` may not be in `mPackages` yet.
16851            //
16852            // Also, don't fail application installs if the dexopt step fails.
16853            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16854                    null /* instructionSets */, false /* checkProfiles */,
16855                    getCompilerFilterForReason(REASON_INSTALL),
16856                    getOrCreateCompilerPackageStats(pkg),
16857                    mDexManager.isUsedByOtherApps(pkg.packageName));
16858            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16859
16860            // Notify BackgroundDexOptService that the package has been changed.
16861            // If this is an update of a package which used to fail to compile,
16862            // BDOS will remove it from its blacklist.
16863            // TODO: Layering violation
16864            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16865        }
16866
16867        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16868            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16869            return;
16870        }
16871
16872        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16873
16874        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16875                "installPackageLI")) {
16876            if (replace) {
16877                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16878                    // Static libs have a synthetic package name containing the version
16879                    // and cannot be updated as an update would get a new package name,
16880                    // unless this is the exact same version code which is useful for
16881                    // development.
16882                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16883                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16884                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16885                                + "static-shared libs cannot be updated");
16886                        return;
16887                    }
16888                }
16889                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16890                        installerPackageName, res, args.installReason);
16891            } else {
16892                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16893                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16894            }
16895        }
16896        synchronized (mPackages) {
16897            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16898            if (ps != null) {
16899                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16900                ps.setUpdateAvailable(false /*updateAvailable*/);
16901            }
16902
16903            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16904            for (int i = 0; i < childCount; i++) {
16905                PackageParser.Package childPkg = pkg.childPackages.get(i);
16906                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16907                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16908                if (childPs != null) {
16909                    childRes.newUsers = childPs.queryInstalledUsers(
16910                            sUserManager.getUserIds(), true);
16911                }
16912            }
16913
16914            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16915                updateSequenceNumberLP(pkgName, res.newUsers);
16916            }
16917        }
16918    }
16919
16920    private void startIntentFilterVerifications(int userId, boolean replacing,
16921            PackageParser.Package pkg) {
16922        if (mIntentFilterVerifierComponent == null) {
16923            Slog.w(TAG, "No IntentFilter verification will not be done as "
16924                    + "there is no IntentFilterVerifier available!");
16925            return;
16926        }
16927
16928        final int verifierUid = getPackageUid(
16929                mIntentFilterVerifierComponent.getPackageName(),
16930                MATCH_DEBUG_TRIAGED_MISSING,
16931                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16932
16933        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16934        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16935        mHandler.sendMessage(msg);
16936
16937        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16938        for (int i = 0; i < childCount; i++) {
16939            PackageParser.Package childPkg = pkg.childPackages.get(i);
16940            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16941            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16942            mHandler.sendMessage(msg);
16943        }
16944    }
16945
16946    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16947            PackageParser.Package pkg) {
16948        int size = pkg.activities.size();
16949        if (size == 0) {
16950            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16951                    "No activity, so no need to verify any IntentFilter!");
16952            return;
16953        }
16954
16955        final boolean hasDomainURLs = hasDomainURLs(pkg);
16956        if (!hasDomainURLs) {
16957            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16958                    "No domain URLs, so no need to verify any IntentFilter!");
16959            return;
16960        }
16961
16962        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16963                + " if any IntentFilter from the " + size
16964                + " Activities needs verification ...");
16965
16966        int count = 0;
16967        final String packageName = pkg.packageName;
16968
16969        synchronized (mPackages) {
16970            // If this is a new install and we see that we've already run verification for this
16971            // package, we have nothing to do: it means the state was restored from backup.
16972            if (!replacing) {
16973                IntentFilterVerificationInfo ivi =
16974                        mSettings.getIntentFilterVerificationLPr(packageName);
16975                if (ivi != null) {
16976                    if (DEBUG_DOMAIN_VERIFICATION) {
16977                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16978                                + ivi.getStatusString());
16979                    }
16980                    return;
16981                }
16982            }
16983
16984            // If any filters need to be verified, then all need to be.
16985            boolean needToVerify = false;
16986            for (PackageParser.Activity a : pkg.activities) {
16987                for (ActivityIntentInfo filter : a.intents) {
16988                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16989                        if (DEBUG_DOMAIN_VERIFICATION) {
16990                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16991                        }
16992                        needToVerify = true;
16993                        break;
16994                    }
16995                }
16996            }
16997
16998            if (needToVerify) {
16999                final int verificationId = mIntentFilterVerificationToken++;
17000                for (PackageParser.Activity a : pkg.activities) {
17001                    for (ActivityIntentInfo filter : a.intents) {
17002                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17003                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17004                                    "Verification needed for IntentFilter:" + filter.toString());
17005                            mIntentFilterVerifier.addOneIntentFilterVerification(
17006                                    verifierUid, userId, verificationId, filter, packageName);
17007                            count++;
17008                        }
17009                    }
17010                }
17011            }
17012        }
17013
17014        if (count > 0) {
17015            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17016                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17017                    +  " for userId:" + userId);
17018            mIntentFilterVerifier.startVerifications(userId);
17019        } else {
17020            if (DEBUG_DOMAIN_VERIFICATION) {
17021                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17022            }
17023        }
17024    }
17025
17026    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17027        final ComponentName cn  = filter.activity.getComponentName();
17028        final String packageName = cn.getPackageName();
17029
17030        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17031                packageName);
17032        if (ivi == null) {
17033            return true;
17034        }
17035        int status = ivi.getStatus();
17036        switch (status) {
17037            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17038            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17039                return true;
17040
17041            default:
17042                // Nothing to do
17043                return false;
17044        }
17045    }
17046
17047    private static boolean isMultiArch(ApplicationInfo info) {
17048        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17049    }
17050
17051    private static boolean isExternal(PackageParser.Package pkg) {
17052        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17053    }
17054
17055    private static boolean isExternal(PackageSetting ps) {
17056        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17057    }
17058
17059    private static boolean isSystemApp(PackageParser.Package pkg) {
17060        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17061    }
17062
17063    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17064        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17065    }
17066
17067    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17068        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17069    }
17070
17071    private static boolean isSystemApp(PackageSetting ps) {
17072        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17073    }
17074
17075    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17076        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17077    }
17078
17079    private int packageFlagsToInstallFlags(PackageSetting ps) {
17080        int installFlags = 0;
17081        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17082            // This existing package was an external ASEC install when we have
17083            // the external flag without a UUID
17084            installFlags |= PackageManager.INSTALL_EXTERNAL;
17085        }
17086        if (ps.isForwardLocked()) {
17087            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17088        }
17089        return installFlags;
17090    }
17091
17092    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17093        if (isExternal(pkg)) {
17094            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17095                return StorageManager.UUID_PRIMARY_PHYSICAL;
17096            } else {
17097                return pkg.volumeUuid;
17098            }
17099        } else {
17100            return StorageManager.UUID_PRIVATE_INTERNAL;
17101        }
17102    }
17103
17104    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17105        if (isExternal(pkg)) {
17106            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17107                return mSettings.getExternalVersion();
17108            } else {
17109                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17110            }
17111        } else {
17112            return mSettings.getInternalVersion();
17113        }
17114    }
17115
17116    private void deleteTempPackageFiles() {
17117        final FilenameFilter filter = new FilenameFilter() {
17118            public boolean accept(File dir, String name) {
17119                return name.startsWith("vmdl") && name.endsWith(".tmp");
17120            }
17121        };
17122        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17123            file.delete();
17124        }
17125    }
17126
17127    @Override
17128    public void deletePackageAsUser(String packageName, int versionCode,
17129            IPackageDeleteObserver observer, int userId, int flags) {
17130        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17131                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17132    }
17133
17134    @Override
17135    public void deletePackageVersioned(VersionedPackage versionedPackage,
17136            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17137        mContext.enforceCallingOrSelfPermission(
17138                android.Manifest.permission.DELETE_PACKAGES, null);
17139        Preconditions.checkNotNull(versionedPackage);
17140        Preconditions.checkNotNull(observer);
17141        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17142                PackageManager.VERSION_CODE_HIGHEST,
17143                Integer.MAX_VALUE, "versionCode must be >= -1");
17144
17145        final String packageName = versionedPackage.getPackageName();
17146        // TODO: We will change version code to long, so in the new API it is long
17147        final int versionCode = (int) versionedPackage.getVersionCode();
17148        final String internalPackageName;
17149        synchronized (mPackages) {
17150            // Normalize package name to handle renamed packages and static libs
17151            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17152                    // TODO: We will change version code to long, so in the new API it is long
17153                    (int) versionedPackage.getVersionCode());
17154        }
17155
17156        final int uid = Binder.getCallingUid();
17157        if (!isOrphaned(internalPackageName)
17158                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17159            try {
17160                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17161                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17162                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17163                observer.onUserActionRequired(intent);
17164            } catch (RemoteException re) {
17165            }
17166            return;
17167        }
17168        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17169        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17170        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17171            mContext.enforceCallingOrSelfPermission(
17172                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17173                    "deletePackage for user " + userId);
17174        }
17175
17176        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17177            try {
17178                observer.onPackageDeleted(packageName,
17179                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17180            } catch (RemoteException re) {
17181            }
17182            return;
17183        }
17184
17185        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17186            try {
17187                observer.onPackageDeleted(packageName,
17188                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17189            } catch (RemoteException re) {
17190            }
17191            return;
17192        }
17193
17194        if (DEBUG_REMOVE) {
17195            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17196                    + " deleteAllUsers: " + deleteAllUsers + " version="
17197                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17198                    ? "VERSION_CODE_HIGHEST" : versionCode));
17199        }
17200        // Queue up an async operation since the package deletion may take a little while.
17201        mHandler.post(new Runnable() {
17202            public void run() {
17203                mHandler.removeCallbacks(this);
17204                int returnCode;
17205                if (!deleteAllUsers) {
17206                    returnCode = deletePackageX(internalPackageName, versionCode,
17207                            userId, deleteFlags);
17208                } else {
17209                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17210                            internalPackageName, users);
17211                    // If nobody is blocking uninstall, proceed with delete for all users
17212                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17213                        returnCode = deletePackageX(internalPackageName, versionCode,
17214                                userId, deleteFlags);
17215                    } else {
17216                        // Otherwise uninstall individually for users with blockUninstalls=false
17217                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17218                        for (int userId : users) {
17219                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17220                                returnCode = deletePackageX(internalPackageName, versionCode,
17221                                        userId, userFlags);
17222                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17223                                    Slog.w(TAG, "Package delete failed for user " + userId
17224                                            + ", returnCode " + returnCode);
17225                                }
17226                            }
17227                        }
17228                        // The app has only been marked uninstalled for certain users.
17229                        // We still need to report that delete was blocked
17230                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17231                    }
17232                }
17233                try {
17234                    observer.onPackageDeleted(packageName, returnCode, null);
17235                } catch (RemoteException e) {
17236                    Log.i(TAG, "Observer no longer exists.");
17237                } //end catch
17238            } //end run
17239        });
17240    }
17241
17242    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17243        if (pkg.staticSharedLibName != null) {
17244            return pkg.manifestPackageName;
17245        }
17246        return pkg.packageName;
17247    }
17248
17249    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17250        // Handle renamed packages
17251        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17252        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17253
17254        // Is this a static library?
17255        SparseArray<SharedLibraryEntry> versionedLib =
17256                mStaticLibsByDeclaringPackage.get(packageName);
17257        if (versionedLib == null || versionedLib.size() <= 0) {
17258            return packageName;
17259        }
17260
17261        // Figure out which lib versions the caller can see
17262        SparseIntArray versionsCallerCanSee = null;
17263        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17264        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17265                && callingAppId != Process.ROOT_UID) {
17266            versionsCallerCanSee = new SparseIntArray();
17267            String libName = versionedLib.valueAt(0).info.getName();
17268            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17269            if (uidPackages != null) {
17270                for (String uidPackage : uidPackages) {
17271                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17272                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17273                    if (libIdx >= 0) {
17274                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17275                        versionsCallerCanSee.append(libVersion, libVersion);
17276                    }
17277                }
17278            }
17279        }
17280
17281        // Caller can see nothing - done
17282        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17283            return packageName;
17284        }
17285
17286        // Find the version the caller can see and the app version code
17287        SharedLibraryEntry highestVersion = null;
17288        final int versionCount = versionedLib.size();
17289        for (int i = 0; i < versionCount; i++) {
17290            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17291            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17292                    libEntry.info.getVersion()) < 0) {
17293                continue;
17294            }
17295            // TODO: We will change version code to long, so in the new API it is long
17296            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17297            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17298                if (libVersionCode == versionCode) {
17299                    return libEntry.apk;
17300                }
17301            } else if (highestVersion == null) {
17302                highestVersion = libEntry;
17303            } else if (libVersionCode  > highestVersion.info
17304                    .getDeclaringPackage().getVersionCode()) {
17305                highestVersion = libEntry;
17306            }
17307        }
17308
17309        if (highestVersion != null) {
17310            return highestVersion.apk;
17311        }
17312
17313        return packageName;
17314    }
17315
17316    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17317        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17318              || callingUid == Process.SYSTEM_UID) {
17319            return true;
17320        }
17321        final int callingUserId = UserHandle.getUserId(callingUid);
17322        // If the caller installed the pkgName, then allow it to silently uninstall.
17323        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17324            return true;
17325        }
17326
17327        // Allow package verifier to silently uninstall.
17328        if (mRequiredVerifierPackage != null &&
17329                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17330            return true;
17331        }
17332
17333        // Allow package uninstaller to silently uninstall.
17334        if (mRequiredUninstallerPackage != null &&
17335                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17336            return true;
17337        }
17338
17339        // Allow storage manager to silently uninstall.
17340        if (mStorageManagerPackage != null &&
17341                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17342            return true;
17343        }
17344        return false;
17345    }
17346
17347    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17348        int[] result = EMPTY_INT_ARRAY;
17349        for (int userId : userIds) {
17350            if (getBlockUninstallForUser(packageName, userId)) {
17351                result = ArrayUtils.appendInt(result, userId);
17352            }
17353        }
17354        return result;
17355    }
17356
17357    @Override
17358    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17359        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17360    }
17361
17362    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17363        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17364                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17365        try {
17366            if (dpm != null) {
17367                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17368                        /* callingUserOnly =*/ false);
17369                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17370                        : deviceOwnerComponentName.getPackageName();
17371                // Does the package contains the device owner?
17372                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17373                // this check is probably not needed, since DO should be registered as a device
17374                // admin on some user too. (Original bug for this: b/17657954)
17375                if (packageName.equals(deviceOwnerPackageName)) {
17376                    return true;
17377                }
17378                // Does it contain a device admin for any user?
17379                int[] users;
17380                if (userId == UserHandle.USER_ALL) {
17381                    users = sUserManager.getUserIds();
17382                } else {
17383                    users = new int[]{userId};
17384                }
17385                for (int i = 0; i < users.length; ++i) {
17386                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17387                        return true;
17388                    }
17389                }
17390            }
17391        } catch (RemoteException e) {
17392        }
17393        return false;
17394    }
17395
17396    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17397        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17398    }
17399
17400    /**
17401     *  This method is an internal method that could be get invoked either
17402     *  to delete an installed package or to clean up a failed installation.
17403     *  After deleting an installed package, a broadcast is sent to notify any
17404     *  listeners that the package has been removed. For cleaning up a failed
17405     *  installation, the broadcast is not necessary since the package's
17406     *  installation wouldn't have sent the initial broadcast either
17407     *  The key steps in deleting a package are
17408     *  deleting the package information in internal structures like mPackages,
17409     *  deleting the packages base directories through installd
17410     *  updating mSettings to reflect current status
17411     *  persisting settings for later use
17412     *  sending a broadcast if necessary
17413     */
17414    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17415        final PackageRemovedInfo info = new PackageRemovedInfo();
17416        final boolean res;
17417
17418        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17419                ? UserHandle.USER_ALL : userId;
17420
17421        if (isPackageDeviceAdmin(packageName, removeUser)) {
17422            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17423            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17424        }
17425
17426        PackageSetting uninstalledPs = null;
17427        PackageParser.Package pkg = null;
17428
17429        // for the uninstall-updates case and restricted profiles, remember the per-
17430        // user handle installed state
17431        int[] allUsers;
17432        synchronized (mPackages) {
17433            uninstalledPs = mSettings.mPackages.get(packageName);
17434            if (uninstalledPs == null) {
17435                Slog.w(TAG, "Not removing non-existent package " + packageName);
17436                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17437            }
17438
17439            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17440                    && uninstalledPs.versionCode != versionCode) {
17441                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17442                        + uninstalledPs.versionCode + " != " + versionCode);
17443                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17444            }
17445
17446            // Static shared libs can be declared by any package, so let us not
17447            // allow removing a package if it provides a lib others depend on.
17448            pkg = mPackages.get(packageName);
17449            if (pkg != null && pkg.staticSharedLibName != null) {
17450                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17451                        pkg.staticSharedLibVersion);
17452                if (libEntry != null) {
17453                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17454                            libEntry.info, 0, userId);
17455                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17456                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17457                                + " hosting lib " + libEntry.info.getName() + " version "
17458                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17459                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17460                    }
17461                }
17462            }
17463
17464            allUsers = sUserManager.getUserIds();
17465            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17466        }
17467
17468        final int freezeUser;
17469        if (isUpdatedSystemApp(uninstalledPs)
17470                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17471            // We're downgrading a system app, which will apply to all users, so
17472            // freeze them all during the downgrade
17473            freezeUser = UserHandle.USER_ALL;
17474        } else {
17475            freezeUser = removeUser;
17476        }
17477
17478        synchronized (mInstallLock) {
17479            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17480            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17481                    deleteFlags, "deletePackageX")) {
17482                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17483                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17484            }
17485            synchronized (mPackages) {
17486                if (res) {
17487                    if (pkg != null) {
17488                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17489                    }
17490                    updateSequenceNumberLP(packageName, info.removedUsers);
17491                }
17492            }
17493        }
17494
17495        if (res) {
17496            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17497            info.sendPackageRemovedBroadcasts(killApp);
17498            info.sendSystemPackageUpdatedBroadcasts();
17499            info.sendSystemPackageAppearedBroadcasts();
17500        }
17501        // Force a gc here.
17502        Runtime.getRuntime().gc();
17503        // Delete the resources here after sending the broadcast to let
17504        // other processes clean up before deleting resources.
17505        if (info.args != null) {
17506            synchronized (mInstallLock) {
17507                info.args.doPostDeleteLI(true);
17508            }
17509        }
17510
17511        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17512    }
17513
17514    class PackageRemovedInfo {
17515        String removedPackage;
17516        int uid = -1;
17517        int removedAppId = -1;
17518        int[] origUsers;
17519        int[] removedUsers = null;
17520        SparseArray<Integer> installReasons;
17521        boolean isRemovedPackageSystemUpdate = false;
17522        boolean isUpdate;
17523        boolean dataRemoved;
17524        boolean removedForAllUsers;
17525        boolean isStaticSharedLib;
17526        // Clean up resources deleted packages.
17527        InstallArgs args = null;
17528        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17529        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17530
17531        void sendPackageRemovedBroadcasts(boolean killApp) {
17532            sendPackageRemovedBroadcastInternal(killApp);
17533            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17534            for (int i = 0; i < childCount; i++) {
17535                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17536                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17537            }
17538        }
17539
17540        void sendSystemPackageUpdatedBroadcasts() {
17541            if (isRemovedPackageSystemUpdate) {
17542                sendSystemPackageUpdatedBroadcastsInternal();
17543                final int childCount = (removedChildPackages != null)
17544                        ? removedChildPackages.size() : 0;
17545                for (int i = 0; i < childCount; i++) {
17546                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17547                    if (childInfo.isRemovedPackageSystemUpdate) {
17548                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17549                    }
17550                }
17551            }
17552        }
17553
17554        void sendSystemPackageAppearedBroadcasts() {
17555            final int packageCount = (appearedChildPackages != null)
17556                    ? appearedChildPackages.size() : 0;
17557            for (int i = 0; i < packageCount; i++) {
17558                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17559                sendPackageAddedForNewUsers(installedInfo.name, true,
17560                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17561            }
17562        }
17563
17564        private void sendSystemPackageUpdatedBroadcastsInternal() {
17565            Bundle extras = new Bundle(2);
17566            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17567            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17568            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17569                    extras, 0, null, null, null);
17570            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17571                    extras, 0, null, null, null);
17572            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17573                    null, 0, removedPackage, null, null);
17574        }
17575
17576        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17577            // Don't send static shared library removal broadcasts as these
17578            // libs are visible only the the apps that depend on them an one
17579            // cannot remove the library if it has a dependency.
17580            if (isStaticSharedLib) {
17581                return;
17582            }
17583            Bundle extras = new Bundle(2);
17584            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17585            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17586            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17587            if (isUpdate || isRemovedPackageSystemUpdate) {
17588                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17589            }
17590            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17591            if (removedPackage != null) {
17592                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17593                        extras, 0, null, null, removedUsers);
17594                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17595                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17596                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17597                            null, null, removedUsers);
17598                }
17599            }
17600            if (removedAppId >= 0) {
17601                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17602                        removedUsers);
17603            }
17604        }
17605    }
17606
17607    /*
17608     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17609     * flag is not set, the data directory is removed as well.
17610     * make sure this flag is set for partially installed apps. If not its meaningless to
17611     * delete a partially installed application.
17612     */
17613    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17614            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17615        String packageName = ps.name;
17616        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17617        // Retrieve object to delete permissions for shared user later on
17618        final PackageParser.Package deletedPkg;
17619        final PackageSetting deletedPs;
17620        // reader
17621        synchronized (mPackages) {
17622            deletedPkg = mPackages.get(packageName);
17623            deletedPs = mSettings.mPackages.get(packageName);
17624            if (outInfo != null) {
17625                outInfo.removedPackage = packageName;
17626                outInfo.isStaticSharedLib = deletedPkg != null
17627                        && deletedPkg.staticSharedLibName != null;
17628                outInfo.removedUsers = deletedPs != null
17629                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17630                        : null;
17631            }
17632        }
17633
17634        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17635
17636        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17637            final PackageParser.Package resolvedPkg;
17638            if (deletedPkg != null) {
17639                resolvedPkg = deletedPkg;
17640            } else {
17641                // We don't have a parsed package when it lives on an ejected
17642                // adopted storage device, so fake something together
17643                resolvedPkg = new PackageParser.Package(ps.name);
17644                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17645            }
17646            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17647                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17648            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17649            if (outInfo != null) {
17650                outInfo.dataRemoved = true;
17651            }
17652            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17653        }
17654
17655        int removedAppId = -1;
17656
17657        // writer
17658        synchronized (mPackages) {
17659            boolean installedStateChanged = false;
17660            if (deletedPs != null) {
17661                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17662                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17663                    clearDefaultBrowserIfNeeded(packageName);
17664                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17665                    removedAppId = mSettings.removePackageLPw(packageName);
17666                    if (outInfo != null) {
17667                        outInfo.removedAppId = removedAppId;
17668                    }
17669                    updatePermissionsLPw(deletedPs.name, null, 0);
17670                    if (deletedPs.sharedUser != null) {
17671                        // Remove permissions associated with package. Since runtime
17672                        // permissions are per user we have to kill the removed package
17673                        // or packages running under the shared user of the removed
17674                        // package if revoking the permissions requested only by the removed
17675                        // package is successful and this causes a change in gids.
17676                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17677                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17678                                    userId);
17679                            if (userIdToKill == UserHandle.USER_ALL
17680                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17681                                // If gids changed for this user, kill all affected packages.
17682                                mHandler.post(new Runnable() {
17683                                    @Override
17684                                    public void run() {
17685                                        // This has to happen with no lock held.
17686                                        killApplication(deletedPs.name, deletedPs.appId,
17687                                                KILL_APP_REASON_GIDS_CHANGED);
17688                                    }
17689                                });
17690                                break;
17691                            }
17692                        }
17693                    }
17694                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17695                }
17696                // make sure to preserve per-user disabled state if this removal was just
17697                // a downgrade of a system app to the factory package
17698                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17699                    if (DEBUG_REMOVE) {
17700                        Slog.d(TAG, "Propagating install state across downgrade");
17701                    }
17702                    for (int userId : allUserHandles) {
17703                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17704                        if (DEBUG_REMOVE) {
17705                            Slog.d(TAG, "    user " + userId + " => " + installed);
17706                        }
17707                        if (installed != ps.getInstalled(userId)) {
17708                            installedStateChanged = true;
17709                        }
17710                        ps.setInstalled(installed, userId);
17711                    }
17712                }
17713            }
17714            // can downgrade to reader
17715            if (writeSettings) {
17716                // Save settings now
17717                mSettings.writeLPr();
17718            }
17719            if (installedStateChanged) {
17720                mSettings.writeKernelMappingLPr(ps);
17721            }
17722        }
17723        if (removedAppId != -1) {
17724            // A user ID was deleted here. Go through all users and remove it
17725            // from KeyStore.
17726            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17727        }
17728    }
17729
17730    static boolean locationIsPrivileged(File path) {
17731        try {
17732            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17733                    .getCanonicalPath();
17734            return path.getCanonicalPath().startsWith(privilegedAppDir);
17735        } catch (IOException e) {
17736            Slog.e(TAG, "Unable to access code path " + path);
17737        }
17738        return false;
17739    }
17740
17741    /*
17742     * Tries to delete system package.
17743     */
17744    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17745            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17746            boolean writeSettings) {
17747        if (deletedPs.parentPackageName != null) {
17748            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17749            return false;
17750        }
17751
17752        final boolean applyUserRestrictions
17753                = (allUserHandles != null) && (outInfo.origUsers != null);
17754        final PackageSetting disabledPs;
17755        // Confirm if the system package has been updated
17756        // An updated system app can be deleted. This will also have to restore
17757        // the system pkg from system partition
17758        // reader
17759        synchronized (mPackages) {
17760            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17761        }
17762
17763        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17764                + " disabledPs=" + disabledPs);
17765
17766        if (disabledPs == null) {
17767            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17768            return false;
17769        } else if (DEBUG_REMOVE) {
17770            Slog.d(TAG, "Deleting system pkg from data partition");
17771        }
17772
17773        if (DEBUG_REMOVE) {
17774            if (applyUserRestrictions) {
17775                Slog.d(TAG, "Remembering install states:");
17776                for (int userId : allUserHandles) {
17777                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17778                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17779                }
17780            }
17781        }
17782
17783        // Delete the updated package
17784        outInfo.isRemovedPackageSystemUpdate = true;
17785        if (outInfo.removedChildPackages != null) {
17786            final int childCount = (deletedPs.childPackageNames != null)
17787                    ? deletedPs.childPackageNames.size() : 0;
17788            for (int i = 0; i < childCount; i++) {
17789                String childPackageName = deletedPs.childPackageNames.get(i);
17790                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17791                        .contains(childPackageName)) {
17792                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17793                            childPackageName);
17794                    if (childInfo != null) {
17795                        childInfo.isRemovedPackageSystemUpdate = true;
17796                    }
17797                }
17798            }
17799        }
17800
17801        if (disabledPs.versionCode < deletedPs.versionCode) {
17802            // Delete data for downgrades
17803            flags &= ~PackageManager.DELETE_KEEP_DATA;
17804        } else {
17805            // Preserve data by setting flag
17806            flags |= PackageManager.DELETE_KEEP_DATA;
17807        }
17808
17809        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17810                outInfo, writeSettings, disabledPs.pkg);
17811        if (!ret) {
17812            return false;
17813        }
17814
17815        // writer
17816        synchronized (mPackages) {
17817            // Reinstate the old system package
17818            enableSystemPackageLPw(disabledPs.pkg);
17819            // Remove any native libraries from the upgraded package.
17820            removeNativeBinariesLI(deletedPs);
17821        }
17822
17823        // Install the system package
17824        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17825        int parseFlags = mDefParseFlags
17826                | PackageParser.PARSE_MUST_BE_APK
17827                | PackageParser.PARSE_IS_SYSTEM
17828                | PackageParser.PARSE_IS_SYSTEM_DIR;
17829        if (locationIsPrivileged(disabledPs.codePath)) {
17830            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17831        }
17832
17833        final PackageParser.Package newPkg;
17834        try {
17835            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17836                0 /* currentTime */, null);
17837        } catch (PackageManagerException e) {
17838            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17839                    + e.getMessage());
17840            return false;
17841        }
17842
17843        try {
17844            // update shared libraries for the newly re-installed system package
17845            updateSharedLibrariesLPr(newPkg, null);
17846        } catch (PackageManagerException e) {
17847            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17848        }
17849
17850        prepareAppDataAfterInstallLIF(newPkg);
17851
17852        // writer
17853        synchronized (mPackages) {
17854            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17855
17856            // Propagate the permissions state as we do not want to drop on the floor
17857            // runtime permissions. The update permissions method below will take
17858            // care of removing obsolete permissions and grant install permissions.
17859            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17860            updatePermissionsLPw(newPkg.packageName, newPkg,
17861                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17862
17863            if (applyUserRestrictions) {
17864                boolean installedStateChanged = false;
17865                if (DEBUG_REMOVE) {
17866                    Slog.d(TAG, "Propagating install state across reinstall");
17867                }
17868                for (int userId : allUserHandles) {
17869                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17870                    if (DEBUG_REMOVE) {
17871                        Slog.d(TAG, "    user " + userId + " => " + installed);
17872                    }
17873                    if (installed != ps.getInstalled(userId)) {
17874                        installedStateChanged = true;
17875                    }
17876                    ps.setInstalled(installed, userId);
17877
17878                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17879                }
17880                // Regardless of writeSettings we need to ensure that this restriction
17881                // state propagation is persisted
17882                mSettings.writeAllUsersPackageRestrictionsLPr();
17883                if (installedStateChanged) {
17884                    mSettings.writeKernelMappingLPr(ps);
17885                }
17886            }
17887            // can downgrade to reader here
17888            if (writeSettings) {
17889                mSettings.writeLPr();
17890            }
17891        }
17892        return true;
17893    }
17894
17895    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17896            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17897            PackageRemovedInfo outInfo, boolean writeSettings,
17898            PackageParser.Package replacingPackage) {
17899        synchronized (mPackages) {
17900            if (outInfo != null) {
17901                outInfo.uid = ps.appId;
17902            }
17903
17904            if (outInfo != null && outInfo.removedChildPackages != null) {
17905                final int childCount = (ps.childPackageNames != null)
17906                        ? ps.childPackageNames.size() : 0;
17907                for (int i = 0; i < childCount; i++) {
17908                    String childPackageName = ps.childPackageNames.get(i);
17909                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17910                    if (childPs == null) {
17911                        return false;
17912                    }
17913                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17914                            childPackageName);
17915                    if (childInfo != null) {
17916                        childInfo.uid = childPs.appId;
17917                    }
17918                }
17919            }
17920        }
17921
17922        // Delete package data from internal structures and also remove data if flag is set
17923        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17924
17925        // Delete the child packages data
17926        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17927        for (int i = 0; i < childCount; i++) {
17928            PackageSetting childPs;
17929            synchronized (mPackages) {
17930                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17931            }
17932            if (childPs != null) {
17933                PackageRemovedInfo childOutInfo = (outInfo != null
17934                        && outInfo.removedChildPackages != null)
17935                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17936                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17937                        && (replacingPackage != null
17938                        && !replacingPackage.hasChildPackage(childPs.name))
17939                        ? flags & ~DELETE_KEEP_DATA : flags;
17940                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17941                        deleteFlags, writeSettings);
17942            }
17943        }
17944
17945        // Delete application code and resources only for parent packages
17946        if (ps.parentPackageName == null) {
17947            if (deleteCodeAndResources && (outInfo != null)) {
17948                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17949                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17950                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17951            }
17952        }
17953
17954        return true;
17955    }
17956
17957    @Override
17958    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17959            int userId) {
17960        mContext.enforceCallingOrSelfPermission(
17961                android.Manifest.permission.DELETE_PACKAGES, null);
17962        synchronized (mPackages) {
17963            PackageSetting ps = mSettings.mPackages.get(packageName);
17964            if (ps == null) {
17965                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17966                return false;
17967            }
17968            // Cannot block uninstall of static shared libs as they are
17969            // considered a part of the using app (emulating static linking).
17970            // Also static libs are installed always on internal storage.
17971            PackageParser.Package pkg = mPackages.get(packageName);
17972            if (pkg != null && pkg.staticSharedLibName != null) {
17973                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17974                        + " providing static shared library: " + pkg.staticSharedLibName);
17975                return false;
17976            }
17977            if (!ps.getInstalled(userId)) {
17978                // Can't block uninstall for an app that is not installed or enabled.
17979                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17980                return false;
17981            }
17982            ps.setBlockUninstall(blockUninstall, userId);
17983            mSettings.writePackageRestrictionsLPr(userId);
17984        }
17985        return true;
17986    }
17987
17988    @Override
17989    public boolean getBlockUninstallForUser(String packageName, int userId) {
17990        synchronized (mPackages) {
17991            PackageSetting ps = mSettings.mPackages.get(packageName);
17992            if (ps == null) {
17993                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17994                return false;
17995            }
17996            return ps.getBlockUninstall(userId);
17997        }
17998    }
17999
18000    @Override
18001    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18002        int callingUid = Binder.getCallingUid();
18003        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18004            throw new SecurityException(
18005                    "setRequiredForSystemUser can only be run by the system or root");
18006        }
18007        synchronized (mPackages) {
18008            PackageSetting ps = mSettings.mPackages.get(packageName);
18009            if (ps == null) {
18010                Log.w(TAG, "Package doesn't exist: " + packageName);
18011                return false;
18012            }
18013            if (systemUserApp) {
18014                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18015            } else {
18016                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18017            }
18018            mSettings.writeLPr();
18019        }
18020        return true;
18021    }
18022
18023    /*
18024     * This method handles package deletion in general
18025     */
18026    private boolean deletePackageLIF(String packageName, UserHandle user,
18027            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18028            PackageRemovedInfo outInfo, boolean writeSettings,
18029            PackageParser.Package replacingPackage) {
18030        if (packageName == null) {
18031            Slog.w(TAG, "Attempt to delete null packageName.");
18032            return false;
18033        }
18034
18035        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18036
18037        PackageSetting ps;
18038        synchronized (mPackages) {
18039            ps = mSettings.mPackages.get(packageName);
18040            if (ps == null) {
18041                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18042                return false;
18043            }
18044
18045            if (ps.parentPackageName != null && (!isSystemApp(ps)
18046                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18047                if (DEBUG_REMOVE) {
18048                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18049                            + ((user == null) ? UserHandle.USER_ALL : user));
18050                }
18051                final int removedUserId = (user != null) ? user.getIdentifier()
18052                        : UserHandle.USER_ALL;
18053                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18054                    return false;
18055                }
18056                markPackageUninstalledForUserLPw(ps, user);
18057                scheduleWritePackageRestrictionsLocked(user);
18058                return true;
18059            }
18060        }
18061
18062        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18063                && user.getIdentifier() != UserHandle.USER_ALL)) {
18064            // The caller is asking that the package only be deleted for a single
18065            // user.  To do this, we just mark its uninstalled state and delete
18066            // its data. If this is a system app, we only allow this to happen if
18067            // they have set the special DELETE_SYSTEM_APP which requests different
18068            // semantics than normal for uninstalling system apps.
18069            markPackageUninstalledForUserLPw(ps, user);
18070
18071            if (!isSystemApp(ps)) {
18072                // Do not uninstall the APK if an app should be cached
18073                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18074                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18075                    // Other user still have this package installed, so all
18076                    // we need to do is clear this user's data and save that
18077                    // it is uninstalled.
18078                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18079                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18080                        return false;
18081                    }
18082                    scheduleWritePackageRestrictionsLocked(user);
18083                    return true;
18084                } else {
18085                    // We need to set it back to 'installed' so the uninstall
18086                    // broadcasts will be sent correctly.
18087                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18088                    ps.setInstalled(true, user.getIdentifier());
18089                    mSettings.writeKernelMappingLPr(ps);
18090                }
18091            } else {
18092                // This is a system app, so we assume that the
18093                // other users still have this package installed, so all
18094                // we need to do is clear this user's data and save that
18095                // it is uninstalled.
18096                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18097                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18098                    return false;
18099                }
18100                scheduleWritePackageRestrictionsLocked(user);
18101                return true;
18102            }
18103        }
18104
18105        // If we are deleting a composite package for all users, keep track
18106        // of result for each child.
18107        if (ps.childPackageNames != null && outInfo != null) {
18108            synchronized (mPackages) {
18109                final int childCount = ps.childPackageNames.size();
18110                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18111                for (int i = 0; i < childCount; i++) {
18112                    String childPackageName = ps.childPackageNames.get(i);
18113                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18114                    childInfo.removedPackage = childPackageName;
18115                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18116                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18117                    if (childPs != null) {
18118                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18119                    }
18120                }
18121            }
18122        }
18123
18124        boolean ret = false;
18125        if (isSystemApp(ps)) {
18126            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18127            // When an updated system application is deleted we delete the existing resources
18128            // as well and fall back to existing code in system partition
18129            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18130        } else {
18131            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18132            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18133                    outInfo, writeSettings, replacingPackage);
18134        }
18135
18136        // Take a note whether we deleted the package for all users
18137        if (outInfo != null) {
18138            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18139            if (outInfo.removedChildPackages != null) {
18140                synchronized (mPackages) {
18141                    final int childCount = outInfo.removedChildPackages.size();
18142                    for (int i = 0; i < childCount; i++) {
18143                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18144                        if (childInfo != null) {
18145                            childInfo.removedForAllUsers = mPackages.get(
18146                                    childInfo.removedPackage) == null;
18147                        }
18148                    }
18149                }
18150            }
18151            // If we uninstalled an update to a system app there may be some
18152            // child packages that appeared as they are declared in the system
18153            // app but were not declared in the update.
18154            if (isSystemApp(ps)) {
18155                synchronized (mPackages) {
18156                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18157                    final int childCount = (updatedPs.childPackageNames != null)
18158                            ? updatedPs.childPackageNames.size() : 0;
18159                    for (int i = 0; i < childCount; i++) {
18160                        String childPackageName = updatedPs.childPackageNames.get(i);
18161                        if (outInfo.removedChildPackages == null
18162                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18163                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18164                            if (childPs == null) {
18165                                continue;
18166                            }
18167                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18168                            installRes.name = childPackageName;
18169                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18170                            installRes.pkg = mPackages.get(childPackageName);
18171                            installRes.uid = childPs.pkg.applicationInfo.uid;
18172                            if (outInfo.appearedChildPackages == null) {
18173                                outInfo.appearedChildPackages = new ArrayMap<>();
18174                            }
18175                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18176                        }
18177                    }
18178                }
18179            }
18180        }
18181
18182        return ret;
18183    }
18184
18185    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18186        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18187                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18188        for (int nextUserId : userIds) {
18189            if (DEBUG_REMOVE) {
18190                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18191            }
18192            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18193                    false /*installed*/,
18194                    true /*stopped*/,
18195                    true /*notLaunched*/,
18196                    false /*hidden*/,
18197                    false /*suspended*/,
18198                    false /*instantApp*/,
18199                    null /*lastDisableAppCaller*/,
18200                    null /*enabledComponents*/,
18201                    null /*disabledComponents*/,
18202                    false /*blockUninstall*/,
18203                    ps.readUserState(nextUserId).domainVerificationStatus,
18204                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18205        }
18206        mSettings.writeKernelMappingLPr(ps);
18207    }
18208
18209    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18210            PackageRemovedInfo outInfo) {
18211        final PackageParser.Package pkg;
18212        synchronized (mPackages) {
18213            pkg = mPackages.get(ps.name);
18214        }
18215
18216        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18217                : new int[] {userId};
18218        for (int nextUserId : userIds) {
18219            if (DEBUG_REMOVE) {
18220                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18221                        + nextUserId);
18222            }
18223
18224            destroyAppDataLIF(pkg, userId,
18225                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18226            destroyAppProfilesLIF(pkg, userId);
18227            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18228            schedulePackageCleaning(ps.name, nextUserId, false);
18229            synchronized (mPackages) {
18230                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18231                    scheduleWritePackageRestrictionsLocked(nextUserId);
18232                }
18233                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18234            }
18235        }
18236
18237        if (outInfo != null) {
18238            outInfo.removedPackage = ps.name;
18239            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18240            outInfo.removedAppId = ps.appId;
18241            outInfo.removedUsers = userIds;
18242        }
18243
18244        return true;
18245    }
18246
18247    private final class ClearStorageConnection implements ServiceConnection {
18248        IMediaContainerService mContainerService;
18249
18250        @Override
18251        public void onServiceConnected(ComponentName name, IBinder service) {
18252            synchronized (this) {
18253                mContainerService = IMediaContainerService.Stub
18254                        .asInterface(Binder.allowBlocking(service));
18255                notifyAll();
18256            }
18257        }
18258
18259        @Override
18260        public void onServiceDisconnected(ComponentName name) {
18261        }
18262    }
18263
18264    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18265        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18266
18267        final boolean mounted;
18268        if (Environment.isExternalStorageEmulated()) {
18269            mounted = true;
18270        } else {
18271            final String status = Environment.getExternalStorageState();
18272
18273            mounted = status.equals(Environment.MEDIA_MOUNTED)
18274                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18275        }
18276
18277        if (!mounted) {
18278            return;
18279        }
18280
18281        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18282        int[] users;
18283        if (userId == UserHandle.USER_ALL) {
18284            users = sUserManager.getUserIds();
18285        } else {
18286            users = new int[] { userId };
18287        }
18288        final ClearStorageConnection conn = new ClearStorageConnection();
18289        if (mContext.bindServiceAsUser(
18290                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18291            try {
18292                for (int curUser : users) {
18293                    long timeout = SystemClock.uptimeMillis() + 5000;
18294                    synchronized (conn) {
18295                        long now;
18296                        while (conn.mContainerService == null &&
18297                                (now = SystemClock.uptimeMillis()) < timeout) {
18298                            try {
18299                                conn.wait(timeout - now);
18300                            } catch (InterruptedException e) {
18301                            }
18302                        }
18303                    }
18304                    if (conn.mContainerService == null) {
18305                        return;
18306                    }
18307
18308                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18309                    clearDirectory(conn.mContainerService,
18310                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18311                    if (allData) {
18312                        clearDirectory(conn.mContainerService,
18313                                userEnv.buildExternalStorageAppDataDirs(packageName));
18314                        clearDirectory(conn.mContainerService,
18315                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18316                    }
18317                }
18318            } finally {
18319                mContext.unbindService(conn);
18320            }
18321        }
18322    }
18323
18324    @Override
18325    public void clearApplicationProfileData(String packageName) {
18326        enforceSystemOrRoot("Only the system can clear all profile data");
18327
18328        final PackageParser.Package pkg;
18329        synchronized (mPackages) {
18330            pkg = mPackages.get(packageName);
18331        }
18332
18333        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18334            synchronized (mInstallLock) {
18335                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18336            }
18337        }
18338    }
18339
18340    @Override
18341    public void clearApplicationUserData(final String packageName,
18342            final IPackageDataObserver observer, final int userId) {
18343        mContext.enforceCallingOrSelfPermission(
18344                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18345
18346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18347                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18348
18349        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18350            throw new SecurityException("Cannot clear data for a protected package: "
18351                    + packageName);
18352        }
18353        // Queue up an async operation since the package deletion may take a little while.
18354        mHandler.post(new Runnable() {
18355            public void run() {
18356                mHandler.removeCallbacks(this);
18357                final boolean succeeded;
18358                try (PackageFreezer freezer = freezePackage(packageName,
18359                        "clearApplicationUserData")) {
18360                    synchronized (mInstallLock) {
18361                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18362                    }
18363                    clearExternalStorageDataSync(packageName, userId, true);
18364                    synchronized (mPackages) {
18365                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18366                                packageName, userId);
18367                    }
18368                }
18369                if (succeeded) {
18370                    // invoke DeviceStorageMonitor's update method to clear any notifications
18371                    DeviceStorageMonitorInternal dsm = LocalServices
18372                            .getService(DeviceStorageMonitorInternal.class);
18373                    if (dsm != null) {
18374                        dsm.checkMemory();
18375                    }
18376                }
18377                if(observer != null) {
18378                    try {
18379                        observer.onRemoveCompleted(packageName, succeeded);
18380                    } catch (RemoteException e) {
18381                        Log.i(TAG, "Observer no longer exists.");
18382                    }
18383                } //end if observer
18384            } //end run
18385        });
18386    }
18387
18388    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18389        if (packageName == null) {
18390            Slog.w(TAG, "Attempt to delete null packageName.");
18391            return false;
18392        }
18393
18394        // Try finding details about the requested package
18395        PackageParser.Package pkg;
18396        synchronized (mPackages) {
18397            pkg = mPackages.get(packageName);
18398            if (pkg == null) {
18399                final PackageSetting ps = mSettings.mPackages.get(packageName);
18400                if (ps != null) {
18401                    pkg = ps.pkg;
18402                }
18403            }
18404
18405            if (pkg == null) {
18406                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18407                return false;
18408            }
18409
18410            PackageSetting ps = (PackageSetting) pkg.mExtras;
18411            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18412        }
18413
18414        clearAppDataLIF(pkg, userId,
18415                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18416
18417        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18418        removeKeystoreDataIfNeeded(userId, appId);
18419
18420        UserManagerInternal umInternal = getUserManagerInternal();
18421        final int flags;
18422        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18423            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18424        } else if (umInternal.isUserRunning(userId)) {
18425            flags = StorageManager.FLAG_STORAGE_DE;
18426        } else {
18427            flags = 0;
18428        }
18429        prepareAppDataContentsLIF(pkg, userId, flags);
18430
18431        return true;
18432    }
18433
18434    /**
18435     * Reverts user permission state changes (permissions and flags) in
18436     * all packages for a given user.
18437     *
18438     * @param userId The device user for which to do a reset.
18439     */
18440    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18441        final int packageCount = mPackages.size();
18442        for (int i = 0; i < packageCount; i++) {
18443            PackageParser.Package pkg = mPackages.valueAt(i);
18444            PackageSetting ps = (PackageSetting) pkg.mExtras;
18445            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18446        }
18447    }
18448
18449    private void resetNetworkPolicies(int userId) {
18450        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18451    }
18452
18453    /**
18454     * Reverts user permission state changes (permissions and flags).
18455     *
18456     * @param ps The package for which to reset.
18457     * @param userId The device user for which to do a reset.
18458     */
18459    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18460            final PackageSetting ps, final int userId) {
18461        if (ps.pkg == null) {
18462            return;
18463        }
18464
18465        // These are flags that can change base on user actions.
18466        final int userSettableMask = FLAG_PERMISSION_USER_SET
18467                | FLAG_PERMISSION_USER_FIXED
18468                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18469                | FLAG_PERMISSION_REVIEW_REQUIRED;
18470
18471        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18472                | FLAG_PERMISSION_POLICY_FIXED;
18473
18474        boolean writeInstallPermissions = false;
18475        boolean writeRuntimePermissions = false;
18476
18477        final int permissionCount = ps.pkg.requestedPermissions.size();
18478        for (int i = 0; i < permissionCount; i++) {
18479            String permission = ps.pkg.requestedPermissions.get(i);
18480
18481            BasePermission bp = mSettings.mPermissions.get(permission);
18482            if (bp == null) {
18483                continue;
18484            }
18485
18486            // If shared user we just reset the state to which only this app contributed.
18487            if (ps.sharedUser != null) {
18488                boolean used = false;
18489                final int packageCount = ps.sharedUser.packages.size();
18490                for (int j = 0; j < packageCount; j++) {
18491                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18492                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18493                            && pkg.pkg.requestedPermissions.contains(permission)) {
18494                        used = true;
18495                        break;
18496                    }
18497                }
18498                if (used) {
18499                    continue;
18500                }
18501            }
18502
18503            PermissionsState permissionsState = ps.getPermissionsState();
18504
18505            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18506
18507            // Always clear the user settable flags.
18508            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18509                    bp.name) != null;
18510            // If permission review is enabled and this is a legacy app, mark the
18511            // permission as requiring a review as this is the initial state.
18512            int flags = 0;
18513            if (mPermissionReviewRequired
18514                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18515                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18516            }
18517            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18518                if (hasInstallState) {
18519                    writeInstallPermissions = true;
18520                } else {
18521                    writeRuntimePermissions = true;
18522                }
18523            }
18524
18525            // Below is only runtime permission handling.
18526            if (!bp.isRuntime()) {
18527                continue;
18528            }
18529
18530            // Never clobber system or policy.
18531            if ((oldFlags & policyOrSystemFlags) != 0) {
18532                continue;
18533            }
18534
18535            // If this permission was granted by default, make sure it is.
18536            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18537                if (permissionsState.grantRuntimePermission(bp, userId)
18538                        != PERMISSION_OPERATION_FAILURE) {
18539                    writeRuntimePermissions = true;
18540                }
18541            // If permission review is enabled the permissions for a legacy apps
18542            // are represented as constantly granted runtime ones, so don't revoke.
18543            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18544                // Otherwise, reset the permission.
18545                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18546                switch (revokeResult) {
18547                    case PERMISSION_OPERATION_SUCCESS:
18548                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18549                        writeRuntimePermissions = true;
18550                        final int appId = ps.appId;
18551                        mHandler.post(new Runnable() {
18552                            @Override
18553                            public void run() {
18554                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18555                            }
18556                        });
18557                    } break;
18558                }
18559            }
18560        }
18561
18562        // Synchronously write as we are taking permissions away.
18563        if (writeRuntimePermissions) {
18564            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18565        }
18566
18567        // Synchronously write as we are taking permissions away.
18568        if (writeInstallPermissions) {
18569            mSettings.writeLPr();
18570        }
18571    }
18572
18573    /**
18574     * Remove entries from the keystore daemon. Will only remove it if the
18575     * {@code appId} is valid.
18576     */
18577    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18578        if (appId < 0) {
18579            return;
18580        }
18581
18582        final KeyStore keyStore = KeyStore.getInstance();
18583        if (keyStore != null) {
18584            if (userId == UserHandle.USER_ALL) {
18585                for (final int individual : sUserManager.getUserIds()) {
18586                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18587                }
18588            } else {
18589                keyStore.clearUid(UserHandle.getUid(userId, appId));
18590            }
18591        } else {
18592            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18593        }
18594    }
18595
18596    @Override
18597    public void deleteApplicationCacheFiles(final String packageName,
18598            final IPackageDataObserver observer) {
18599        final int userId = UserHandle.getCallingUserId();
18600        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18601    }
18602
18603    @Override
18604    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18605            final IPackageDataObserver observer) {
18606        mContext.enforceCallingOrSelfPermission(
18607                android.Manifest.permission.DELETE_CACHE_FILES, null);
18608        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18609                /* requireFullPermission= */ true, /* checkShell= */ false,
18610                "delete application cache files");
18611
18612        final PackageParser.Package pkg;
18613        synchronized (mPackages) {
18614            pkg = mPackages.get(packageName);
18615        }
18616
18617        // Queue up an async operation since the package deletion may take a little while.
18618        mHandler.post(new Runnable() {
18619            public void run() {
18620                synchronized (mInstallLock) {
18621                    final int flags = StorageManager.FLAG_STORAGE_DE
18622                            | StorageManager.FLAG_STORAGE_CE;
18623                    // We're only clearing cache files, so we don't care if the
18624                    // app is unfrozen and still able to run
18625                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18626                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18627                }
18628                clearExternalStorageDataSync(packageName, userId, false);
18629                if (observer != null) {
18630                    try {
18631                        observer.onRemoveCompleted(packageName, true);
18632                    } catch (RemoteException e) {
18633                        Log.i(TAG, "Observer no longer exists.");
18634                    }
18635                }
18636            }
18637        });
18638    }
18639
18640    @Override
18641    public void getPackageSizeInfo(final String packageName, int userHandle,
18642            final IPackageStatsObserver observer) {
18643        throw new UnsupportedOperationException(
18644                "Shame on you for calling a hidden API. Shame!");
18645    }
18646
18647    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18648        final PackageSetting ps;
18649        synchronized (mPackages) {
18650            ps = mSettings.mPackages.get(packageName);
18651            if (ps == null) {
18652                Slog.w(TAG, "Failed to find settings for " + packageName);
18653                return false;
18654            }
18655        }
18656
18657        final String[] packageNames = { packageName };
18658        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18659        final String[] codePaths = { ps.codePathString };
18660
18661        try {
18662            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18663                    ps.appId, ceDataInodes, codePaths, stats);
18664
18665            // For now, ignore code size of packages on system partition
18666            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18667                stats.codeSize = 0;
18668            }
18669
18670            // External clients expect these to be tracked separately
18671            stats.dataSize -= stats.cacheSize;
18672
18673        } catch (InstallerException e) {
18674            Slog.w(TAG, String.valueOf(e));
18675            return false;
18676        }
18677
18678        return true;
18679    }
18680
18681    private int getUidTargetSdkVersionLockedLPr(int uid) {
18682        Object obj = mSettings.getUserIdLPr(uid);
18683        if (obj instanceof SharedUserSetting) {
18684            final SharedUserSetting sus = (SharedUserSetting) obj;
18685            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18686            final Iterator<PackageSetting> it = sus.packages.iterator();
18687            while (it.hasNext()) {
18688                final PackageSetting ps = it.next();
18689                if (ps.pkg != null) {
18690                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18691                    if (v < vers) vers = v;
18692                }
18693            }
18694            return vers;
18695        } else if (obj instanceof PackageSetting) {
18696            final PackageSetting ps = (PackageSetting) obj;
18697            if (ps.pkg != null) {
18698                return ps.pkg.applicationInfo.targetSdkVersion;
18699            }
18700        }
18701        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18702    }
18703
18704    @Override
18705    public void addPreferredActivity(IntentFilter filter, int match,
18706            ComponentName[] set, ComponentName activity, int userId) {
18707        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18708                "Adding preferred");
18709    }
18710
18711    private void addPreferredActivityInternal(IntentFilter filter, int match,
18712            ComponentName[] set, ComponentName activity, boolean always, int userId,
18713            String opname) {
18714        // writer
18715        int callingUid = Binder.getCallingUid();
18716        enforceCrossUserPermission(callingUid, userId,
18717                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18718        if (filter.countActions() == 0) {
18719            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18720            return;
18721        }
18722        synchronized (mPackages) {
18723            if (mContext.checkCallingOrSelfPermission(
18724                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18725                    != PackageManager.PERMISSION_GRANTED) {
18726                if (getUidTargetSdkVersionLockedLPr(callingUid)
18727                        < Build.VERSION_CODES.FROYO) {
18728                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18729                            + callingUid);
18730                    return;
18731                }
18732                mContext.enforceCallingOrSelfPermission(
18733                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18734            }
18735
18736            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18737            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18738                    + userId + ":");
18739            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18740            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18741            scheduleWritePackageRestrictionsLocked(userId);
18742            postPreferredActivityChangedBroadcast(userId);
18743        }
18744    }
18745
18746    private void postPreferredActivityChangedBroadcast(int userId) {
18747        mHandler.post(() -> {
18748            final IActivityManager am = ActivityManager.getService();
18749            if (am == null) {
18750                return;
18751            }
18752
18753            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18754            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18755            try {
18756                am.broadcastIntent(null, intent, null, null,
18757                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18758                        null, false, false, userId);
18759            } catch (RemoteException e) {
18760            }
18761        });
18762    }
18763
18764    @Override
18765    public void replacePreferredActivity(IntentFilter filter, int match,
18766            ComponentName[] set, ComponentName activity, int userId) {
18767        if (filter.countActions() != 1) {
18768            throw new IllegalArgumentException(
18769                    "replacePreferredActivity expects filter to have only 1 action.");
18770        }
18771        if (filter.countDataAuthorities() != 0
18772                || filter.countDataPaths() != 0
18773                || filter.countDataSchemes() > 1
18774                || filter.countDataTypes() != 0) {
18775            throw new IllegalArgumentException(
18776                    "replacePreferredActivity expects filter to have no data authorities, " +
18777                    "paths, or types; and at most one scheme.");
18778        }
18779
18780        final int callingUid = Binder.getCallingUid();
18781        enforceCrossUserPermission(callingUid, userId,
18782                true /* requireFullPermission */, false /* checkShell */,
18783                "replace preferred activity");
18784        synchronized (mPackages) {
18785            if (mContext.checkCallingOrSelfPermission(
18786                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18787                    != PackageManager.PERMISSION_GRANTED) {
18788                if (getUidTargetSdkVersionLockedLPr(callingUid)
18789                        < Build.VERSION_CODES.FROYO) {
18790                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18791                            + Binder.getCallingUid());
18792                    return;
18793                }
18794                mContext.enforceCallingOrSelfPermission(
18795                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18796            }
18797
18798            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18799            if (pir != null) {
18800                // Get all of the existing entries that exactly match this filter.
18801                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18802                if (existing != null && existing.size() == 1) {
18803                    PreferredActivity cur = existing.get(0);
18804                    if (DEBUG_PREFERRED) {
18805                        Slog.i(TAG, "Checking replace of preferred:");
18806                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18807                        if (!cur.mPref.mAlways) {
18808                            Slog.i(TAG, "  -- CUR; not mAlways!");
18809                        } else {
18810                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18811                            Slog.i(TAG, "  -- CUR: mSet="
18812                                    + Arrays.toString(cur.mPref.mSetComponents));
18813                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18814                            Slog.i(TAG, "  -- NEW: mMatch="
18815                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18816                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18817                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18818                        }
18819                    }
18820                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18821                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18822                            && cur.mPref.sameSet(set)) {
18823                        // Setting the preferred activity to what it happens to be already
18824                        if (DEBUG_PREFERRED) {
18825                            Slog.i(TAG, "Replacing with same preferred activity "
18826                                    + cur.mPref.mShortComponent + " for user "
18827                                    + userId + ":");
18828                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18829                        }
18830                        return;
18831                    }
18832                }
18833
18834                if (existing != null) {
18835                    if (DEBUG_PREFERRED) {
18836                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18837                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18838                    }
18839                    for (int i = 0; i < existing.size(); i++) {
18840                        PreferredActivity pa = existing.get(i);
18841                        if (DEBUG_PREFERRED) {
18842                            Slog.i(TAG, "Removing existing preferred activity "
18843                                    + pa.mPref.mComponent + ":");
18844                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18845                        }
18846                        pir.removeFilter(pa);
18847                    }
18848                }
18849            }
18850            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18851                    "Replacing preferred");
18852        }
18853    }
18854
18855    @Override
18856    public void clearPackagePreferredActivities(String packageName) {
18857        final int uid = Binder.getCallingUid();
18858        // writer
18859        synchronized (mPackages) {
18860            PackageParser.Package pkg = mPackages.get(packageName);
18861            if (pkg == null || pkg.applicationInfo.uid != uid) {
18862                if (mContext.checkCallingOrSelfPermission(
18863                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18864                        != PackageManager.PERMISSION_GRANTED) {
18865                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18866                            < Build.VERSION_CODES.FROYO) {
18867                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18868                                + Binder.getCallingUid());
18869                        return;
18870                    }
18871                    mContext.enforceCallingOrSelfPermission(
18872                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18873                }
18874            }
18875
18876            int user = UserHandle.getCallingUserId();
18877            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18878                scheduleWritePackageRestrictionsLocked(user);
18879            }
18880        }
18881    }
18882
18883    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18884    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18885        ArrayList<PreferredActivity> removed = null;
18886        boolean changed = false;
18887        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18888            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18889            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18890            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18891                continue;
18892            }
18893            Iterator<PreferredActivity> it = pir.filterIterator();
18894            while (it.hasNext()) {
18895                PreferredActivity pa = it.next();
18896                // Mark entry for removal only if it matches the package name
18897                // and the entry is of type "always".
18898                if (packageName == null ||
18899                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18900                                && pa.mPref.mAlways)) {
18901                    if (removed == null) {
18902                        removed = new ArrayList<PreferredActivity>();
18903                    }
18904                    removed.add(pa);
18905                }
18906            }
18907            if (removed != null) {
18908                for (int j=0; j<removed.size(); j++) {
18909                    PreferredActivity pa = removed.get(j);
18910                    pir.removeFilter(pa);
18911                }
18912                changed = true;
18913            }
18914        }
18915        if (changed) {
18916            postPreferredActivityChangedBroadcast(userId);
18917        }
18918        return changed;
18919    }
18920
18921    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18922    private void clearIntentFilterVerificationsLPw(int userId) {
18923        final int packageCount = mPackages.size();
18924        for (int i = 0; i < packageCount; i++) {
18925            PackageParser.Package pkg = mPackages.valueAt(i);
18926            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18927        }
18928    }
18929
18930    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18931    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18932        if (userId == UserHandle.USER_ALL) {
18933            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18934                    sUserManager.getUserIds())) {
18935                for (int oneUserId : sUserManager.getUserIds()) {
18936                    scheduleWritePackageRestrictionsLocked(oneUserId);
18937                }
18938            }
18939        } else {
18940            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18941                scheduleWritePackageRestrictionsLocked(userId);
18942            }
18943        }
18944    }
18945
18946    void clearDefaultBrowserIfNeeded(String packageName) {
18947        for (int oneUserId : sUserManager.getUserIds()) {
18948            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18949            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18950            if (packageName.equals(defaultBrowserPackageName)) {
18951                setDefaultBrowserPackageName(null, oneUserId);
18952            }
18953        }
18954    }
18955
18956    @Override
18957    public void resetApplicationPreferences(int userId) {
18958        mContext.enforceCallingOrSelfPermission(
18959                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18960        final long identity = Binder.clearCallingIdentity();
18961        // writer
18962        try {
18963            synchronized (mPackages) {
18964                clearPackagePreferredActivitiesLPw(null, userId);
18965                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18966                // TODO: We have to reset the default SMS and Phone. This requires
18967                // significant refactoring to keep all default apps in the package
18968                // manager (cleaner but more work) or have the services provide
18969                // callbacks to the package manager to request a default app reset.
18970                applyFactoryDefaultBrowserLPw(userId);
18971                clearIntentFilterVerificationsLPw(userId);
18972                primeDomainVerificationsLPw(userId);
18973                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18974                scheduleWritePackageRestrictionsLocked(userId);
18975            }
18976            resetNetworkPolicies(userId);
18977        } finally {
18978            Binder.restoreCallingIdentity(identity);
18979        }
18980    }
18981
18982    @Override
18983    public int getPreferredActivities(List<IntentFilter> outFilters,
18984            List<ComponentName> outActivities, String packageName) {
18985
18986        int num = 0;
18987        final int userId = UserHandle.getCallingUserId();
18988        // reader
18989        synchronized (mPackages) {
18990            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18991            if (pir != null) {
18992                final Iterator<PreferredActivity> it = pir.filterIterator();
18993                while (it.hasNext()) {
18994                    final PreferredActivity pa = it.next();
18995                    if (packageName == null
18996                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18997                                    && pa.mPref.mAlways)) {
18998                        if (outFilters != null) {
18999                            outFilters.add(new IntentFilter(pa));
19000                        }
19001                        if (outActivities != null) {
19002                            outActivities.add(pa.mPref.mComponent);
19003                        }
19004                    }
19005                }
19006            }
19007        }
19008
19009        return num;
19010    }
19011
19012    @Override
19013    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19014            int userId) {
19015        int callingUid = Binder.getCallingUid();
19016        if (callingUid != Process.SYSTEM_UID) {
19017            throw new SecurityException(
19018                    "addPersistentPreferredActivity can only be run by the system");
19019        }
19020        if (filter.countActions() == 0) {
19021            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19022            return;
19023        }
19024        synchronized (mPackages) {
19025            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19026                    ":");
19027            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19028            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19029                    new PersistentPreferredActivity(filter, activity));
19030            scheduleWritePackageRestrictionsLocked(userId);
19031            postPreferredActivityChangedBroadcast(userId);
19032        }
19033    }
19034
19035    @Override
19036    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19037        int callingUid = Binder.getCallingUid();
19038        if (callingUid != Process.SYSTEM_UID) {
19039            throw new SecurityException(
19040                    "clearPackagePersistentPreferredActivities can only be run by the system");
19041        }
19042        ArrayList<PersistentPreferredActivity> removed = null;
19043        boolean changed = false;
19044        synchronized (mPackages) {
19045            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19046                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19047                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19048                        .valueAt(i);
19049                if (userId != thisUserId) {
19050                    continue;
19051                }
19052                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19053                while (it.hasNext()) {
19054                    PersistentPreferredActivity ppa = it.next();
19055                    // Mark entry for removal only if it matches the package name.
19056                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19057                        if (removed == null) {
19058                            removed = new ArrayList<PersistentPreferredActivity>();
19059                        }
19060                        removed.add(ppa);
19061                    }
19062                }
19063                if (removed != null) {
19064                    for (int j=0; j<removed.size(); j++) {
19065                        PersistentPreferredActivity ppa = removed.get(j);
19066                        ppir.removeFilter(ppa);
19067                    }
19068                    changed = true;
19069                }
19070            }
19071
19072            if (changed) {
19073                scheduleWritePackageRestrictionsLocked(userId);
19074                postPreferredActivityChangedBroadcast(userId);
19075            }
19076        }
19077    }
19078
19079    /**
19080     * Common machinery for picking apart a restored XML blob and passing
19081     * it to a caller-supplied functor to be applied to the running system.
19082     */
19083    private void restoreFromXml(XmlPullParser parser, int userId,
19084            String expectedStartTag, BlobXmlRestorer functor)
19085            throws IOException, XmlPullParserException {
19086        int type;
19087        while ((type = parser.next()) != XmlPullParser.START_TAG
19088                && type != XmlPullParser.END_DOCUMENT) {
19089        }
19090        if (type != XmlPullParser.START_TAG) {
19091            // oops didn't find a start tag?!
19092            if (DEBUG_BACKUP) {
19093                Slog.e(TAG, "Didn't find start tag during restore");
19094            }
19095            return;
19096        }
19097Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19098        // this is supposed to be TAG_PREFERRED_BACKUP
19099        if (!expectedStartTag.equals(parser.getName())) {
19100            if (DEBUG_BACKUP) {
19101                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19102            }
19103            return;
19104        }
19105
19106        // skip interfering stuff, then we're aligned with the backing implementation
19107        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19108Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19109        functor.apply(parser, userId);
19110    }
19111
19112    private interface BlobXmlRestorer {
19113        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19114    }
19115
19116    /**
19117     * Non-Binder method, support for the backup/restore mechanism: write the
19118     * full set of preferred activities in its canonical XML format.  Returns the
19119     * XML output as a byte array, or null if there is none.
19120     */
19121    @Override
19122    public byte[] getPreferredActivityBackup(int userId) {
19123        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19124            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19125        }
19126
19127        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19128        try {
19129            final XmlSerializer serializer = new FastXmlSerializer();
19130            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19131            serializer.startDocument(null, true);
19132            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19133
19134            synchronized (mPackages) {
19135                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19136            }
19137
19138            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19139            serializer.endDocument();
19140            serializer.flush();
19141        } catch (Exception e) {
19142            if (DEBUG_BACKUP) {
19143                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19144            }
19145            return null;
19146        }
19147
19148        return dataStream.toByteArray();
19149    }
19150
19151    @Override
19152    public void restorePreferredActivities(byte[] backup, int userId) {
19153        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19154            throw new SecurityException("Only the system may call restorePreferredActivities()");
19155        }
19156
19157        try {
19158            final XmlPullParser parser = Xml.newPullParser();
19159            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19160            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19161                    new BlobXmlRestorer() {
19162                        @Override
19163                        public void apply(XmlPullParser parser, int userId)
19164                                throws XmlPullParserException, IOException {
19165                            synchronized (mPackages) {
19166                                mSettings.readPreferredActivitiesLPw(parser, userId);
19167                            }
19168                        }
19169                    } );
19170        } catch (Exception e) {
19171            if (DEBUG_BACKUP) {
19172                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19173            }
19174        }
19175    }
19176
19177    /**
19178     * Non-Binder method, support for the backup/restore mechanism: write the
19179     * default browser (etc) settings in its canonical XML format.  Returns the default
19180     * browser XML representation as a byte array, or null if there is none.
19181     */
19182    @Override
19183    public byte[] getDefaultAppsBackup(int userId) {
19184        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19185            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19186        }
19187
19188        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19189        try {
19190            final XmlSerializer serializer = new FastXmlSerializer();
19191            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19192            serializer.startDocument(null, true);
19193            serializer.startTag(null, TAG_DEFAULT_APPS);
19194
19195            synchronized (mPackages) {
19196                mSettings.writeDefaultAppsLPr(serializer, userId);
19197            }
19198
19199            serializer.endTag(null, TAG_DEFAULT_APPS);
19200            serializer.endDocument();
19201            serializer.flush();
19202        } catch (Exception e) {
19203            if (DEBUG_BACKUP) {
19204                Slog.e(TAG, "Unable to write default apps for backup", e);
19205            }
19206            return null;
19207        }
19208
19209        return dataStream.toByteArray();
19210    }
19211
19212    @Override
19213    public void restoreDefaultApps(byte[] backup, int userId) {
19214        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19215            throw new SecurityException("Only the system may call restoreDefaultApps()");
19216        }
19217
19218        try {
19219            final XmlPullParser parser = Xml.newPullParser();
19220            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19221            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19222                    new BlobXmlRestorer() {
19223                        @Override
19224                        public void apply(XmlPullParser parser, int userId)
19225                                throws XmlPullParserException, IOException {
19226                            synchronized (mPackages) {
19227                                mSettings.readDefaultAppsLPw(parser, userId);
19228                            }
19229                        }
19230                    } );
19231        } catch (Exception e) {
19232            if (DEBUG_BACKUP) {
19233                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19234            }
19235        }
19236    }
19237
19238    @Override
19239    public byte[] getIntentFilterVerificationBackup(int userId) {
19240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19241            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19242        }
19243
19244        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19245        try {
19246            final XmlSerializer serializer = new FastXmlSerializer();
19247            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19248            serializer.startDocument(null, true);
19249            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19250
19251            synchronized (mPackages) {
19252                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19253            }
19254
19255            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19256            serializer.endDocument();
19257            serializer.flush();
19258        } catch (Exception e) {
19259            if (DEBUG_BACKUP) {
19260                Slog.e(TAG, "Unable to write default apps for backup", e);
19261            }
19262            return null;
19263        }
19264
19265        return dataStream.toByteArray();
19266    }
19267
19268    @Override
19269    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19270        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19271            throw new SecurityException("Only the system may call restorePreferredActivities()");
19272        }
19273
19274        try {
19275            final XmlPullParser parser = Xml.newPullParser();
19276            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19277            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19278                    new BlobXmlRestorer() {
19279                        @Override
19280                        public void apply(XmlPullParser parser, int userId)
19281                                throws XmlPullParserException, IOException {
19282                            synchronized (mPackages) {
19283                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19284                                mSettings.writeLPr();
19285                            }
19286                        }
19287                    } );
19288        } catch (Exception e) {
19289            if (DEBUG_BACKUP) {
19290                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19291            }
19292        }
19293    }
19294
19295    @Override
19296    public byte[] getPermissionGrantBackup(int userId) {
19297        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19298            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19299        }
19300
19301        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19302        try {
19303            final XmlSerializer serializer = new FastXmlSerializer();
19304            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19305            serializer.startDocument(null, true);
19306            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19307
19308            synchronized (mPackages) {
19309                serializeRuntimePermissionGrantsLPr(serializer, userId);
19310            }
19311
19312            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19313            serializer.endDocument();
19314            serializer.flush();
19315        } catch (Exception e) {
19316            if (DEBUG_BACKUP) {
19317                Slog.e(TAG, "Unable to write default apps for backup", e);
19318            }
19319            return null;
19320        }
19321
19322        return dataStream.toByteArray();
19323    }
19324
19325    @Override
19326    public void restorePermissionGrants(byte[] backup, int userId) {
19327        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19328            throw new SecurityException("Only the system may call restorePermissionGrants()");
19329        }
19330
19331        try {
19332            final XmlPullParser parser = Xml.newPullParser();
19333            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19334            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19335                    new BlobXmlRestorer() {
19336                        @Override
19337                        public void apply(XmlPullParser parser, int userId)
19338                                throws XmlPullParserException, IOException {
19339                            synchronized (mPackages) {
19340                                processRestoredPermissionGrantsLPr(parser, userId);
19341                            }
19342                        }
19343                    } );
19344        } catch (Exception e) {
19345            if (DEBUG_BACKUP) {
19346                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19347            }
19348        }
19349    }
19350
19351    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19352            throws IOException {
19353        serializer.startTag(null, TAG_ALL_GRANTS);
19354
19355        final int N = mSettings.mPackages.size();
19356        for (int i = 0; i < N; i++) {
19357            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19358            boolean pkgGrantsKnown = false;
19359
19360            PermissionsState packagePerms = ps.getPermissionsState();
19361
19362            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19363                final int grantFlags = state.getFlags();
19364                // only look at grants that are not system/policy fixed
19365                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19366                    final boolean isGranted = state.isGranted();
19367                    // And only back up the user-twiddled state bits
19368                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19369                        final String packageName = mSettings.mPackages.keyAt(i);
19370                        if (!pkgGrantsKnown) {
19371                            serializer.startTag(null, TAG_GRANT);
19372                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19373                            pkgGrantsKnown = true;
19374                        }
19375
19376                        final boolean userSet =
19377                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19378                        final boolean userFixed =
19379                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19380                        final boolean revoke =
19381                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19382
19383                        serializer.startTag(null, TAG_PERMISSION);
19384                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19385                        if (isGranted) {
19386                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19387                        }
19388                        if (userSet) {
19389                            serializer.attribute(null, ATTR_USER_SET, "true");
19390                        }
19391                        if (userFixed) {
19392                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19393                        }
19394                        if (revoke) {
19395                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19396                        }
19397                        serializer.endTag(null, TAG_PERMISSION);
19398                    }
19399                }
19400            }
19401
19402            if (pkgGrantsKnown) {
19403                serializer.endTag(null, TAG_GRANT);
19404            }
19405        }
19406
19407        serializer.endTag(null, TAG_ALL_GRANTS);
19408    }
19409
19410    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19411            throws XmlPullParserException, IOException {
19412        String pkgName = null;
19413        int outerDepth = parser.getDepth();
19414        int type;
19415        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19416                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19417            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19418                continue;
19419            }
19420
19421            final String tagName = parser.getName();
19422            if (tagName.equals(TAG_GRANT)) {
19423                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19424                if (DEBUG_BACKUP) {
19425                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19426                }
19427            } else if (tagName.equals(TAG_PERMISSION)) {
19428
19429                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19430                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19431
19432                int newFlagSet = 0;
19433                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19434                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19435                }
19436                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19437                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19438                }
19439                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19440                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19441                }
19442                if (DEBUG_BACKUP) {
19443                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19444                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19445                }
19446                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19447                if (ps != null) {
19448                    // Already installed so we apply the grant immediately
19449                    if (DEBUG_BACKUP) {
19450                        Slog.v(TAG, "        + already installed; applying");
19451                    }
19452                    PermissionsState perms = ps.getPermissionsState();
19453                    BasePermission bp = mSettings.mPermissions.get(permName);
19454                    if (bp != null) {
19455                        if (isGranted) {
19456                            perms.grantRuntimePermission(bp, userId);
19457                        }
19458                        if (newFlagSet != 0) {
19459                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19460                        }
19461                    }
19462                } else {
19463                    // Need to wait for post-restore install to apply the grant
19464                    if (DEBUG_BACKUP) {
19465                        Slog.v(TAG, "        - not yet installed; saving for later");
19466                    }
19467                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19468                            isGranted, newFlagSet, userId);
19469                }
19470            } else {
19471                PackageManagerService.reportSettingsProblem(Log.WARN,
19472                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19473                XmlUtils.skipCurrentTag(parser);
19474            }
19475        }
19476
19477        scheduleWriteSettingsLocked();
19478        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19479    }
19480
19481    @Override
19482    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19483            int sourceUserId, int targetUserId, int flags) {
19484        mContext.enforceCallingOrSelfPermission(
19485                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19486        int callingUid = Binder.getCallingUid();
19487        enforceOwnerRights(ownerPackage, callingUid);
19488        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19489        if (intentFilter.countActions() == 0) {
19490            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19491            return;
19492        }
19493        synchronized (mPackages) {
19494            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19495                    ownerPackage, targetUserId, flags);
19496            CrossProfileIntentResolver resolver =
19497                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19498            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19499            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19500            if (existing != null) {
19501                int size = existing.size();
19502                for (int i = 0; i < size; i++) {
19503                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19504                        return;
19505                    }
19506                }
19507            }
19508            resolver.addFilter(newFilter);
19509            scheduleWritePackageRestrictionsLocked(sourceUserId);
19510        }
19511    }
19512
19513    @Override
19514    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19515        mContext.enforceCallingOrSelfPermission(
19516                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19517        int callingUid = Binder.getCallingUid();
19518        enforceOwnerRights(ownerPackage, callingUid);
19519        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19520        synchronized (mPackages) {
19521            CrossProfileIntentResolver resolver =
19522                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19523            ArraySet<CrossProfileIntentFilter> set =
19524                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19525            for (CrossProfileIntentFilter filter : set) {
19526                if (filter.getOwnerPackage().equals(ownerPackage)) {
19527                    resolver.removeFilter(filter);
19528                }
19529            }
19530            scheduleWritePackageRestrictionsLocked(sourceUserId);
19531        }
19532    }
19533
19534    // Enforcing that callingUid is owning pkg on userId
19535    private void enforceOwnerRights(String pkg, int callingUid) {
19536        // The system owns everything.
19537        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19538            return;
19539        }
19540        int callingUserId = UserHandle.getUserId(callingUid);
19541        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19542        if (pi == null) {
19543            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19544                    + callingUserId);
19545        }
19546        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19547            throw new SecurityException("Calling uid " + callingUid
19548                    + " does not own package " + pkg);
19549        }
19550    }
19551
19552    @Override
19553    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19554        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19555    }
19556
19557    /**
19558     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19559     * then reports the most likely home activity or null if there are more than one.
19560     */
19561    public ComponentName getDefaultHomeActivity(int userId) {
19562        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19563        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19564        if (cn != null) {
19565            return cn;
19566        }
19567
19568        // Find the launcher with the highest priority and return that component if there are no
19569        // other home activity with the same priority.
19570        int lastPriority = Integer.MIN_VALUE;
19571        ComponentName lastComponent = null;
19572        final int size = allHomeCandidates.size();
19573        for (int i = 0; i < size; i++) {
19574            final ResolveInfo ri = allHomeCandidates.get(i);
19575            if (ri.priority > lastPriority) {
19576                lastComponent = ri.activityInfo.getComponentName();
19577                lastPriority = ri.priority;
19578            } else if (ri.priority == lastPriority) {
19579                // Two components found with same priority.
19580                lastComponent = null;
19581            }
19582        }
19583        return lastComponent;
19584    }
19585
19586    private Intent getHomeIntent() {
19587        Intent intent = new Intent(Intent.ACTION_MAIN);
19588        intent.addCategory(Intent.CATEGORY_HOME);
19589        intent.addCategory(Intent.CATEGORY_DEFAULT);
19590        return intent;
19591    }
19592
19593    private IntentFilter getHomeFilter() {
19594        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19595        filter.addCategory(Intent.CATEGORY_HOME);
19596        filter.addCategory(Intent.CATEGORY_DEFAULT);
19597        return filter;
19598    }
19599
19600    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19601            int userId) {
19602        Intent intent  = getHomeIntent();
19603        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19604                PackageManager.GET_META_DATA, userId);
19605        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19606                true, false, false, userId);
19607
19608        allHomeCandidates.clear();
19609        if (list != null) {
19610            for (ResolveInfo ri : list) {
19611                allHomeCandidates.add(ri);
19612            }
19613        }
19614        return (preferred == null || preferred.activityInfo == null)
19615                ? null
19616                : new ComponentName(preferred.activityInfo.packageName,
19617                        preferred.activityInfo.name);
19618    }
19619
19620    @Override
19621    public void setHomeActivity(ComponentName comp, int userId) {
19622        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19623        getHomeActivitiesAsUser(homeActivities, userId);
19624
19625        boolean found = false;
19626
19627        final int size = homeActivities.size();
19628        final ComponentName[] set = new ComponentName[size];
19629        for (int i = 0; i < size; i++) {
19630            final ResolveInfo candidate = homeActivities.get(i);
19631            final ActivityInfo info = candidate.activityInfo;
19632            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19633            set[i] = activityName;
19634            if (!found && activityName.equals(comp)) {
19635                found = true;
19636            }
19637        }
19638        if (!found) {
19639            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19640                    + userId);
19641        }
19642        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19643                set, comp, userId);
19644    }
19645
19646    private @Nullable String getSetupWizardPackageName() {
19647        final Intent intent = new Intent(Intent.ACTION_MAIN);
19648        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19649
19650        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19651                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19652                        | MATCH_DISABLED_COMPONENTS,
19653                UserHandle.myUserId());
19654        if (matches.size() == 1) {
19655            return matches.get(0).getComponentInfo().packageName;
19656        } else {
19657            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19658                    + ": matches=" + matches);
19659            return null;
19660        }
19661    }
19662
19663    private @Nullable String getStorageManagerPackageName() {
19664        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19665
19666        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19667                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19668                        | MATCH_DISABLED_COMPONENTS,
19669                UserHandle.myUserId());
19670        if (matches.size() == 1) {
19671            return matches.get(0).getComponentInfo().packageName;
19672        } else {
19673            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19674                    + matches.size() + ": matches=" + matches);
19675            return null;
19676        }
19677    }
19678
19679    @Override
19680    public void setApplicationEnabledSetting(String appPackageName,
19681            int newState, int flags, int userId, String callingPackage) {
19682        if (!sUserManager.exists(userId)) return;
19683        if (callingPackage == null) {
19684            callingPackage = Integer.toString(Binder.getCallingUid());
19685        }
19686        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19687    }
19688
19689    @Override
19690    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19691        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19692        synchronized (mPackages) {
19693            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19694            if (pkgSetting != null) {
19695                pkgSetting.setUpdateAvailable(updateAvailable);
19696            }
19697        }
19698    }
19699
19700    @Override
19701    public void setComponentEnabledSetting(ComponentName componentName,
19702            int newState, int flags, int userId) {
19703        if (!sUserManager.exists(userId)) return;
19704        setEnabledSetting(componentName.getPackageName(),
19705                componentName.getClassName(), newState, flags, userId, null);
19706    }
19707
19708    private void setEnabledSetting(final String packageName, String className, int newState,
19709            final int flags, int userId, String callingPackage) {
19710        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19711              || newState == COMPONENT_ENABLED_STATE_ENABLED
19712              || newState == COMPONENT_ENABLED_STATE_DISABLED
19713              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19714              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19715            throw new IllegalArgumentException("Invalid new component state: "
19716                    + newState);
19717        }
19718        PackageSetting pkgSetting;
19719        final int uid = Binder.getCallingUid();
19720        final int permission;
19721        if (uid == Process.SYSTEM_UID) {
19722            permission = PackageManager.PERMISSION_GRANTED;
19723        } else {
19724            permission = mContext.checkCallingOrSelfPermission(
19725                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19726        }
19727        enforceCrossUserPermission(uid, userId,
19728                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19729        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19730        boolean sendNow = false;
19731        boolean isApp = (className == null);
19732        String componentName = isApp ? packageName : className;
19733        int packageUid = -1;
19734        ArrayList<String> components;
19735
19736        // writer
19737        synchronized (mPackages) {
19738            pkgSetting = mSettings.mPackages.get(packageName);
19739            if (pkgSetting == null) {
19740                if (className == null) {
19741                    throw new IllegalArgumentException("Unknown package: " + packageName);
19742                }
19743                throw new IllegalArgumentException(
19744                        "Unknown component: " + packageName + "/" + className);
19745            }
19746        }
19747
19748        // Limit who can change which apps
19749        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19750            // Don't allow apps that don't have permission to modify other apps
19751            if (!allowedByPermission) {
19752                throw new SecurityException(
19753                        "Permission Denial: attempt to change component state from pid="
19754                        + Binder.getCallingPid()
19755                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19756            }
19757            // Don't allow changing protected packages.
19758            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19759                throw new SecurityException("Cannot disable a protected package: " + packageName);
19760            }
19761        }
19762
19763        synchronized (mPackages) {
19764            if (uid == Process.SHELL_UID
19765                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19766                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19767                // unless it is a test package.
19768                int oldState = pkgSetting.getEnabled(userId);
19769                if (className == null
19770                    &&
19771                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19772                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19773                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19774                    &&
19775                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19776                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19777                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19778                    // ok
19779                } else {
19780                    throw new SecurityException(
19781                            "Shell cannot change component state for " + packageName + "/"
19782                            + className + " to " + newState);
19783                }
19784            }
19785            if (className == null) {
19786                // We're dealing with an application/package level state change
19787                if (pkgSetting.getEnabled(userId) == newState) {
19788                    // Nothing to do
19789                    return;
19790                }
19791                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19792                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19793                    // Don't care about who enables an app.
19794                    callingPackage = null;
19795                }
19796                pkgSetting.setEnabled(newState, userId, callingPackage);
19797                // pkgSetting.pkg.mSetEnabled = newState;
19798            } else {
19799                // We're dealing with a component level state change
19800                // First, verify that this is a valid class name.
19801                PackageParser.Package pkg = pkgSetting.pkg;
19802                if (pkg == null || !pkg.hasComponentClassName(className)) {
19803                    if (pkg != null &&
19804                            pkg.applicationInfo.targetSdkVersion >=
19805                                    Build.VERSION_CODES.JELLY_BEAN) {
19806                        throw new IllegalArgumentException("Component class " + className
19807                                + " does not exist in " + packageName);
19808                    } else {
19809                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19810                                + className + " does not exist in " + packageName);
19811                    }
19812                }
19813                switch (newState) {
19814                case COMPONENT_ENABLED_STATE_ENABLED:
19815                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19816                        return;
19817                    }
19818                    break;
19819                case COMPONENT_ENABLED_STATE_DISABLED:
19820                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19821                        return;
19822                    }
19823                    break;
19824                case COMPONENT_ENABLED_STATE_DEFAULT:
19825                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19826                        return;
19827                    }
19828                    break;
19829                default:
19830                    Slog.e(TAG, "Invalid new component state: " + newState);
19831                    return;
19832                }
19833            }
19834            scheduleWritePackageRestrictionsLocked(userId);
19835            updateSequenceNumberLP(packageName, new int[] { userId });
19836            components = mPendingBroadcasts.get(userId, packageName);
19837            final boolean newPackage = components == null;
19838            if (newPackage) {
19839                components = new ArrayList<String>();
19840            }
19841            if (!components.contains(componentName)) {
19842                components.add(componentName);
19843            }
19844            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19845                sendNow = true;
19846                // Purge entry from pending broadcast list if another one exists already
19847                // since we are sending one right away.
19848                mPendingBroadcasts.remove(userId, packageName);
19849            } else {
19850                if (newPackage) {
19851                    mPendingBroadcasts.put(userId, packageName, components);
19852                }
19853                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19854                    // Schedule a message
19855                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19856                }
19857            }
19858        }
19859
19860        long callingId = Binder.clearCallingIdentity();
19861        try {
19862            if (sendNow) {
19863                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19864                sendPackageChangedBroadcast(packageName,
19865                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19866            }
19867        } finally {
19868            Binder.restoreCallingIdentity(callingId);
19869        }
19870    }
19871
19872    @Override
19873    public void flushPackageRestrictionsAsUser(int userId) {
19874        if (!sUserManager.exists(userId)) {
19875            return;
19876        }
19877        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19878                false /* checkShell */, "flushPackageRestrictions");
19879        synchronized (mPackages) {
19880            mSettings.writePackageRestrictionsLPr(userId);
19881            mDirtyUsers.remove(userId);
19882            if (mDirtyUsers.isEmpty()) {
19883                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19884            }
19885        }
19886    }
19887
19888    private void sendPackageChangedBroadcast(String packageName,
19889            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19890        if (DEBUG_INSTALL)
19891            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19892                    + componentNames);
19893        Bundle extras = new Bundle(4);
19894        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19895        String nameList[] = new String[componentNames.size()];
19896        componentNames.toArray(nameList);
19897        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19898        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19899        extras.putInt(Intent.EXTRA_UID, packageUid);
19900        // If this is not reporting a change of the overall package, then only send it
19901        // to registered receivers.  We don't want to launch a swath of apps for every
19902        // little component state change.
19903        final int flags = !componentNames.contains(packageName)
19904                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19905        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19906                new int[] {UserHandle.getUserId(packageUid)});
19907    }
19908
19909    @Override
19910    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19911        if (!sUserManager.exists(userId)) return;
19912        final int uid = Binder.getCallingUid();
19913        final int permission = mContext.checkCallingOrSelfPermission(
19914                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19915        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19916        enforceCrossUserPermission(uid, userId,
19917                true /* requireFullPermission */, true /* checkShell */, "stop package");
19918        // writer
19919        synchronized (mPackages) {
19920            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19921                    allowedByPermission, uid, userId)) {
19922                scheduleWritePackageRestrictionsLocked(userId);
19923            }
19924        }
19925    }
19926
19927    @Override
19928    public String getInstallerPackageName(String packageName) {
19929        // reader
19930        synchronized (mPackages) {
19931            return mSettings.getInstallerPackageNameLPr(packageName);
19932        }
19933    }
19934
19935    public boolean isOrphaned(String packageName) {
19936        // reader
19937        synchronized (mPackages) {
19938            return mSettings.isOrphaned(packageName);
19939        }
19940    }
19941
19942    @Override
19943    public int getApplicationEnabledSetting(String packageName, int userId) {
19944        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19945        int uid = Binder.getCallingUid();
19946        enforceCrossUserPermission(uid, userId,
19947                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19948        // reader
19949        synchronized (mPackages) {
19950            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19951        }
19952    }
19953
19954    @Override
19955    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19956        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19957        int uid = Binder.getCallingUid();
19958        enforceCrossUserPermission(uid, userId,
19959                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19960        // reader
19961        synchronized (mPackages) {
19962            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19963        }
19964    }
19965
19966    @Override
19967    public void enterSafeMode() {
19968        enforceSystemOrRoot("Only the system can request entering safe mode");
19969
19970        if (!mSystemReady) {
19971            mSafeMode = true;
19972        }
19973    }
19974
19975    @Override
19976    public void systemReady() {
19977        mSystemReady = true;
19978
19979        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19980        // disabled after already being started.
19981        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19982                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19983
19984        // Read the compatibilty setting when the system is ready.
19985        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19986                mContext.getContentResolver(),
19987                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19988        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19989        if (DEBUG_SETTINGS) {
19990            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19991        }
19992
19993        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19994
19995        synchronized (mPackages) {
19996            // Verify that all of the preferred activity components actually
19997            // exist.  It is possible for applications to be updated and at
19998            // that point remove a previously declared activity component that
19999            // had been set as a preferred activity.  We try to clean this up
20000            // the next time we encounter that preferred activity, but it is
20001            // possible for the user flow to never be able to return to that
20002            // situation so here we do a sanity check to make sure we haven't
20003            // left any junk around.
20004            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20005            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20006                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20007                removed.clear();
20008                for (PreferredActivity pa : pir.filterSet()) {
20009                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20010                        removed.add(pa);
20011                    }
20012                }
20013                if (removed.size() > 0) {
20014                    for (int r=0; r<removed.size(); r++) {
20015                        PreferredActivity pa = removed.get(r);
20016                        Slog.w(TAG, "Removing dangling preferred activity: "
20017                                + pa.mPref.mComponent);
20018                        pir.removeFilter(pa);
20019                    }
20020                    mSettings.writePackageRestrictionsLPr(
20021                            mSettings.mPreferredActivities.keyAt(i));
20022                }
20023            }
20024
20025            for (int userId : UserManagerService.getInstance().getUserIds()) {
20026                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20027                    grantPermissionsUserIds = ArrayUtils.appendInt(
20028                            grantPermissionsUserIds, userId);
20029                }
20030            }
20031        }
20032        sUserManager.systemReady();
20033
20034        // If we upgraded grant all default permissions before kicking off.
20035        for (int userId : grantPermissionsUserIds) {
20036            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20037        }
20038
20039        // If we did not grant default permissions, we preload from this the
20040        // default permission exceptions lazily to ensure we don't hit the
20041        // disk on a new user creation.
20042        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20043            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20044        }
20045
20046        // Kick off any messages waiting for system ready
20047        if (mPostSystemReadyMessages != null) {
20048            for (Message msg : mPostSystemReadyMessages) {
20049                msg.sendToTarget();
20050            }
20051            mPostSystemReadyMessages = null;
20052        }
20053
20054        // Watch for external volumes that come and go over time
20055        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20056        storage.registerListener(mStorageListener);
20057
20058        mInstallerService.systemReady();
20059        mPackageDexOptimizer.systemReady();
20060
20061        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20062                StorageManagerInternal.class);
20063        StorageManagerInternal.addExternalStoragePolicy(
20064                new StorageManagerInternal.ExternalStorageMountPolicy() {
20065            @Override
20066            public int getMountMode(int uid, String packageName) {
20067                if (Process.isIsolated(uid)) {
20068                    return Zygote.MOUNT_EXTERNAL_NONE;
20069                }
20070                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20071                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20072                }
20073                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20074                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20075                }
20076                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20077                    return Zygote.MOUNT_EXTERNAL_READ;
20078                }
20079                return Zygote.MOUNT_EXTERNAL_WRITE;
20080            }
20081
20082            @Override
20083            public boolean hasExternalStorage(int uid, String packageName) {
20084                return true;
20085            }
20086        });
20087
20088        // Now that we're mostly running, clean up stale users and apps
20089        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20090        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20091
20092        if (mPrivappPermissionsViolations != null) {
20093            Slog.wtf(TAG,"Signature|privileged permissions not in "
20094                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20095            mPrivappPermissionsViolations = null;
20096        }
20097    }
20098
20099    public void waitForAppDataPrepared() {
20100        if (mPrepareAppDataFuture == null) {
20101            return;
20102        }
20103        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20104        mPrepareAppDataFuture = null;
20105    }
20106
20107    @Override
20108    public boolean isSafeMode() {
20109        return mSafeMode;
20110    }
20111
20112    @Override
20113    public boolean hasSystemUidErrors() {
20114        return mHasSystemUidErrors;
20115    }
20116
20117    static String arrayToString(int[] array) {
20118        StringBuffer buf = new StringBuffer(128);
20119        buf.append('[');
20120        if (array != null) {
20121            for (int i=0; i<array.length; i++) {
20122                if (i > 0) buf.append(", ");
20123                buf.append(array[i]);
20124            }
20125        }
20126        buf.append(']');
20127        return buf.toString();
20128    }
20129
20130    static class DumpState {
20131        public static final int DUMP_LIBS = 1 << 0;
20132        public static final int DUMP_FEATURES = 1 << 1;
20133        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20134        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20135        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20136        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20137        public static final int DUMP_PERMISSIONS = 1 << 6;
20138        public static final int DUMP_PACKAGES = 1 << 7;
20139        public static final int DUMP_SHARED_USERS = 1 << 8;
20140        public static final int DUMP_MESSAGES = 1 << 9;
20141        public static final int DUMP_PROVIDERS = 1 << 10;
20142        public static final int DUMP_VERIFIERS = 1 << 11;
20143        public static final int DUMP_PREFERRED = 1 << 12;
20144        public static final int DUMP_PREFERRED_XML = 1 << 13;
20145        public static final int DUMP_KEYSETS = 1 << 14;
20146        public static final int DUMP_VERSION = 1 << 15;
20147        public static final int DUMP_INSTALLS = 1 << 16;
20148        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20149        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20150        public static final int DUMP_FROZEN = 1 << 19;
20151        public static final int DUMP_DEXOPT = 1 << 20;
20152        public static final int DUMP_COMPILER_STATS = 1 << 21;
20153        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20154
20155        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20156
20157        private int mTypes;
20158
20159        private int mOptions;
20160
20161        private boolean mTitlePrinted;
20162
20163        private SharedUserSetting mSharedUser;
20164
20165        public boolean isDumping(int type) {
20166            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20167                return true;
20168            }
20169
20170            return (mTypes & type) != 0;
20171        }
20172
20173        public void setDump(int type) {
20174            mTypes |= type;
20175        }
20176
20177        public boolean isOptionEnabled(int option) {
20178            return (mOptions & option) != 0;
20179        }
20180
20181        public void setOptionEnabled(int option) {
20182            mOptions |= option;
20183        }
20184
20185        public boolean onTitlePrinted() {
20186            final boolean printed = mTitlePrinted;
20187            mTitlePrinted = true;
20188            return printed;
20189        }
20190
20191        public boolean getTitlePrinted() {
20192            return mTitlePrinted;
20193        }
20194
20195        public void setTitlePrinted(boolean enabled) {
20196            mTitlePrinted = enabled;
20197        }
20198
20199        public SharedUserSetting getSharedUser() {
20200            return mSharedUser;
20201        }
20202
20203        public void setSharedUser(SharedUserSetting user) {
20204            mSharedUser = user;
20205        }
20206    }
20207
20208    @Override
20209    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20210            FileDescriptor err, String[] args, ShellCallback callback,
20211            ResultReceiver resultReceiver) {
20212        (new PackageManagerShellCommand(this)).exec(
20213                this, in, out, err, args, callback, resultReceiver);
20214    }
20215
20216    @Override
20217    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20218        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20219                != PackageManager.PERMISSION_GRANTED) {
20220            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20221                    + Binder.getCallingPid()
20222                    + ", uid=" + Binder.getCallingUid()
20223                    + " without permission "
20224                    + android.Manifest.permission.DUMP);
20225            return;
20226        }
20227
20228        DumpState dumpState = new DumpState();
20229        boolean fullPreferred = false;
20230        boolean checkin = false;
20231
20232        String packageName = null;
20233        ArraySet<String> permissionNames = null;
20234
20235        int opti = 0;
20236        while (opti < args.length) {
20237            String opt = args[opti];
20238            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20239                break;
20240            }
20241            opti++;
20242
20243            if ("-a".equals(opt)) {
20244                // Right now we only know how to print all.
20245            } else if ("-h".equals(opt)) {
20246                pw.println("Package manager dump options:");
20247                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20248                pw.println("    --checkin: dump for a checkin");
20249                pw.println("    -f: print details of intent filters");
20250                pw.println("    -h: print this help");
20251                pw.println("  cmd may be one of:");
20252                pw.println("    l[ibraries]: list known shared libraries");
20253                pw.println("    f[eatures]: list device features");
20254                pw.println("    k[eysets]: print known keysets");
20255                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20256                pw.println("    perm[issions]: dump permissions");
20257                pw.println("    permission [name ...]: dump declaration and use of given permission");
20258                pw.println("    pref[erred]: print preferred package settings");
20259                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20260                pw.println("    prov[iders]: dump content providers");
20261                pw.println("    p[ackages]: dump installed packages");
20262                pw.println("    s[hared-users]: dump shared user IDs");
20263                pw.println("    m[essages]: print collected runtime messages");
20264                pw.println("    v[erifiers]: print package verifier info");
20265                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20266                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20267                pw.println("    version: print database version info");
20268                pw.println("    write: write current settings now");
20269                pw.println("    installs: details about install sessions");
20270                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20271                pw.println("    dexopt: dump dexopt state");
20272                pw.println("    compiler-stats: dump compiler statistics");
20273                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20274                pw.println("    <package.name>: info about given package");
20275                return;
20276            } else if ("--checkin".equals(opt)) {
20277                checkin = true;
20278            } else if ("-f".equals(opt)) {
20279                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20280            } else if ("--proto".equals(opt)) {
20281                dumpProto(fd);
20282                return;
20283            } else {
20284                pw.println("Unknown argument: " + opt + "; use -h for help");
20285            }
20286        }
20287
20288        // Is the caller requesting to dump a particular piece of data?
20289        if (opti < args.length) {
20290            String cmd = args[opti];
20291            opti++;
20292            // Is this a package name?
20293            if ("android".equals(cmd) || cmd.contains(".")) {
20294                packageName = cmd;
20295                // When dumping a single package, we always dump all of its
20296                // filter information since the amount of data will be reasonable.
20297                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20298            } else if ("check-permission".equals(cmd)) {
20299                if (opti >= args.length) {
20300                    pw.println("Error: check-permission missing permission argument");
20301                    return;
20302                }
20303                String perm = args[opti];
20304                opti++;
20305                if (opti >= args.length) {
20306                    pw.println("Error: check-permission missing package argument");
20307                    return;
20308                }
20309
20310                String pkg = args[opti];
20311                opti++;
20312                int user = UserHandle.getUserId(Binder.getCallingUid());
20313                if (opti < args.length) {
20314                    try {
20315                        user = Integer.parseInt(args[opti]);
20316                    } catch (NumberFormatException e) {
20317                        pw.println("Error: check-permission user argument is not a number: "
20318                                + args[opti]);
20319                        return;
20320                    }
20321                }
20322
20323                // Normalize package name to handle renamed packages and static libs
20324                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20325
20326                pw.println(checkPermission(perm, pkg, user));
20327                return;
20328            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20329                dumpState.setDump(DumpState.DUMP_LIBS);
20330            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20331                dumpState.setDump(DumpState.DUMP_FEATURES);
20332            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20333                if (opti >= args.length) {
20334                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20335                            | DumpState.DUMP_SERVICE_RESOLVERS
20336                            | DumpState.DUMP_RECEIVER_RESOLVERS
20337                            | DumpState.DUMP_CONTENT_RESOLVERS);
20338                } else {
20339                    while (opti < args.length) {
20340                        String name = args[opti];
20341                        if ("a".equals(name) || "activity".equals(name)) {
20342                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20343                        } else if ("s".equals(name) || "service".equals(name)) {
20344                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20345                        } else if ("r".equals(name) || "receiver".equals(name)) {
20346                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20347                        } else if ("c".equals(name) || "content".equals(name)) {
20348                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20349                        } else {
20350                            pw.println("Error: unknown resolver table type: " + name);
20351                            return;
20352                        }
20353                        opti++;
20354                    }
20355                }
20356            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20357                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20358            } else if ("permission".equals(cmd)) {
20359                if (opti >= args.length) {
20360                    pw.println("Error: permission requires permission name");
20361                    return;
20362                }
20363                permissionNames = new ArraySet<>();
20364                while (opti < args.length) {
20365                    permissionNames.add(args[opti]);
20366                    opti++;
20367                }
20368                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20369                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20370            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20371                dumpState.setDump(DumpState.DUMP_PREFERRED);
20372            } else if ("preferred-xml".equals(cmd)) {
20373                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20374                if (opti < args.length && "--full".equals(args[opti])) {
20375                    fullPreferred = true;
20376                    opti++;
20377                }
20378            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20379                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20380            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20381                dumpState.setDump(DumpState.DUMP_PACKAGES);
20382            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20383                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20384            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20385                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20386            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20387                dumpState.setDump(DumpState.DUMP_MESSAGES);
20388            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20389                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20390            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20391                    || "intent-filter-verifiers".equals(cmd)) {
20392                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20393            } else if ("version".equals(cmd)) {
20394                dumpState.setDump(DumpState.DUMP_VERSION);
20395            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20396                dumpState.setDump(DumpState.DUMP_KEYSETS);
20397            } else if ("installs".equals(cmd)) {
20398                dumpState.setDump(DumpState.DUMP_INSTALLS);
20399            } else if ("frozen".equals(cmd)) {
20400                dumpState.setDump(DumpState.DUMP_FROZEN);
20401            } else if ("dexopt".equals(cmd)) {
20402                dumpState.setDump(DumpState.DUMP_DEXOPT);
20403            } else if ("compiler-stats".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20405            } else if ("enabled-overlays".equals(cmd)) {
20406                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20407            } else if ("write".equals(cmd)) {
20408                synchronized (mPackages) {
20409                    mSettings.writeLPr();
20410                    pw.println("Settings written.");
20411                    return;
20412                }
20413            }
20414        }
20415
20416        if (checkin) {
20417            pw.println("vers,1");
20418        }
20419
20420        // reader
20421        synchronized (mPackages) {
20422            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20423                if (!checkin) {
20424                    if (dumpState.onTitlePrinted())
20425                        pw.println();
20426                    pw.println("Database versions:");
20427                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20428                }
20429            }
20430
20431            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20432                if (!checkin) {
20433                    if (dumpState.onTitlePrinted())
20434                        pw.println();
20435                    pw.println("Verifiers:");
20436                    pw.print("  Required: ");
20437                    pw.print(mRequiredVerifierPackage);
20438                    pw.print(" (uid=");
20439                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20440                            UserHandle.USER_SYSTEM));
20441                    pw.println(")");
20442                } else if (mRequiredVerifierPackage != null) {
20443                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20444                    pw.print(",");
20445                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20446                            UserHandle.USER_SYSTEM));
20447                }
20448            }
20449
20450            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20451                    packageName == null) {
20452                if (mIntentFilterVerifierComponent != null) {
20453                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20454                    if (!checkin) {
20455                        if (dumpState.onTitlePrinted())
20456                            pw.println();
20457                        pw.println("Intent Filter Verifier:");
20458                        pw.print("  Using: ");
20459                        pw.print(verifierPackageName);
20460                        pw.print(" (uid=");
20461                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20462                                UserHandle.USER_SYSTEM));
20463                        pw.println(")");
20464                    } else if (verifierPackageName != null) {
20465                        pw.print("ifv,"); pw.print(verifierPackageName);
20466                        pw.print(",");
20467                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20468                                UserHandle.USER_SYSTEM));
20469                    }
20470                } else {
20471                    pw.println();
20472                    pw.println("No Intent Filter Verifier available!");
20473                }
20474            }
20475
20476            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20477                boolean printedHeader = false;
20478                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20479                while (it.hasNext()) {
20480                    String libName = it.next();
20481                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20482                    if (versionedLib == null) {
20483                        continue;
20484                    }
20485                    final int versionCount = versionedLib.size();
20486                    for (int i = 0; i < versionCount; i++) {
20487                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20488                        if (!checkin) {
20489                            if (!printedHeader) {
20490                                if (dumpState.onTitlePrinted())
20491                                    pw.println();
20492                                pw.println("Libraries:");
20493                                printedHeader = true;
20494                            }
20495                            pw.print("  ");
20496                        } else {
20497                            pw.print("lib,");
20498                        }
20499                        pw.print(libEntry.info.getName());
20500                        if (libEntry.info.isStatic()) {
20501                            pw.print(" version=" + libEntry.info.getVersion());
20502                        }
20503                        if (!checkin) {
20504                            pw.print(" -> ");
20505                        }
20506                        if (libEntry.path != null) {
20507                            pw.print(" (jar) ");
20508                            pw.print(libEntry.path);
20509                        } else {
20510                            pw.print(" (apk) ");
20511                            pw.print(libEntry.apk);
20512                        }
20513                        pw.println();
20514                    }
20515                }
20516            }
20517
20518            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20519                if (dumpState.onTitlePrinted())
20520                    pw.println();
20521                if (!checkin) {
20522                    pw.println("Features:");
20523                }
20524
20525                synchronized (mAvailableFeatures) {
20526                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20527                        if (checkin) {
20528                            pw.print("feat,");
20529                            pw.print(feat.name);
20530                            pw.print(",");
20531                            pw.println(feat.version);
20532                        } else {
20533                            pw.print("  ");
20534                            pw.print(feat.name);
20535                            if (feat.version > 0) {
20536                                pw.print(" version=");
20537                                pw.print(feat.version);
20538                            }
20539                            pw.println();
20540                        }
20541                    }
20542                }
20543            }
20544
20545            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20546                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20547                        : "Activity Resolver Table:", "  ", packageName,
20548                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20549                    dumpState.setTitlePrinted(true);
20550                }
20551            }
20552            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20553                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20554                        : "Receiver Resolver Table:", "  ", packageName,
20555                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20556                    dumpState.setTitlePrinted(true);
20557                }
20558            }
20559            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20560                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20561                        : "Service Resolver Table:", "  ", packageName,
20562                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20563                    dumpState.setTitlePrinted(true);
20564                }
20565            }
20566            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20567                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20568                        : "Provider Resolver Table:", "  ", packageName,
20569                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20570                    dumpState.setTitlePrinted(true);
20571                }
20572            }
20573
20574            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20575                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20576                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20577                    int user = mSettings.mPreferredActivities.keyAt(i);
20578                    if (pir.dump(pw,
20579                            dumpState.getTitlePrinted()
20580                                ? "\nPreferred Activities User " + user + ":"
20581                                : "Preferred Activities User " + user + ":", "  ",
20582                            packageName, true, false)) {
20583                        dumpState.setTitlePrinted(true);
20584                    }
20585                }
20586            }
20587
20588            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20589                pw.flush();
20590                FileOutputStream fout = new FileOutputStream(fd);
20591                BufferedOutputStream str = new BufferedOutputStream(fout);
20592                XmlSerializer serializer = new FastXmlSerializer();
20593                try {
20594                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20595                    serializer.startDocument(null, true);
20596                    serializer.setFeature(
20597                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20598                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20599                    serializer.endDocument();
20600                    serializer.flush();
20601                } catch (IllegalArgumentException e) {
20602                    pw.println("Failed writing: " + e);
20603                } catch (IllegalStateException e) {
20604                    pw.println("Failed writing: " + e);
20605                } catch (IOException e) {
20606                    pw.println("Failed writing: " + e);
20607                }
20608            }
20609
20610            if (!checkin
20611                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20612                    && packageName == null) {
20613                pw.println();
20614                int count = mSettings.mPackages.size();
20615                if (count == 0) {
20616                    pw.println("No applications!");
20617                    pw.println();
20618                } else {
20619                    final String prefix = "  ";
20620                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20621                    if (allPackageSettings.size() == 0) {
20622                        pw.println("No domain preferred apps!");
20623                        pw.println();
20624                    } else {
20625                        pw.println("App verification status:");
20626                        pw.println();
20627                        count = 0;
20628                        for (PackageSetting ps : allPackageSettings) {
20629                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20630                            if (ivi == null || ivi.getPackageName() == null) continue;
20631                            pw.println(prefix + "Package: " + ivi.getPackageName());
20632                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20633                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20634                            pw.println();
20635                            count++;
20636                        }
20637                        if (count == 0) {
20638                            pw.println(prefix + "No app verification established.");
20639                            pw.println();
20640                        }
20641                        for (int userId : sUserManager.getUserIds()) {
20642                            pw.println("App linkages for user " + userId + ":");
20643                            pw.println();
20644                            count = 0;
20645                            for (PackageSetting ps : allPackageSettings) {
20646                                final long status = ps.getDomainVerificationStatusForUser(userId);
20647                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20648                                        && !DEBUG_DOMAIN_VERIFICATION) {
20649                                    continue;
20650                                }
20651                                pw.println(prefix + "Package: " + ps.name);
20652                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20653                                String statusStr = IntentFilterVerificationInfo.
20654                                        getStatusStringFromValue(status);
20655                                pw.println(prefix + "Status:  " + statusStr);
20656                                pw.println();
20657                                count++;
20658                            }
20659                            if (count == 0) {
20660                                pw.println(prefix + "No configured app linkages.");
20661                                pw.println();
20662                            }
20663                        }
20664                    }
20665                }
20666            }
20667
20668            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20669                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20670                if (packageName == null && permissionNames == null) {
20671                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20672                        if (iperm == 0) {
20673                            if (dumpState.onTitlePrinted())
20674                                pw.println();
20675                            pw.println("AppOp Permissions:");
20676                        }
20677                        pw.print("  AppOp Permission ");
20678                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20679                        pw.println(":");
20680                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20681                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20682                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20683                        }
20684                    }
20685                }
20686            }
20687
20688            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20689                boolean printedSomething = false;
20690                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20691                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20692                        continue;
20693                    }
20694                    if (!printedSomething) {
20695                        if (dumpState.onTitlePrinted())
20696                            pw.println();
20697                        pw.println("Registered ContentProviders:");
20698                        printedSomething = true;
20699                    }
20700                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20701                    pw.print("    "); pw.println(p.toString());
20702                }
20703                printedSomething = false;
20704                for (Map.Entry<String, PackageParser.Provider> entry :
20705                        mProvidersByAuthority.entrySet()) {
20706                    PackageParser.Provider p = entry.getValue();
20707                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20708                        continue;
20709                    }
20710                    if (!printedSomething) {
20711                        if (dumpState.onTitlePrinted())
20712                            pw.println();
20713                        pw.println("ContentProvider Authorities:");
20714                        printedSomething = true;
20715                    }
20716                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20717                    pw.print("    "); pw.println(p.toString());
20718                    if (p.info != null && p.info.applicationInfo != null) {
20719                        final String appInfo = p.info.applicationInfo.toString();
20720                        pw.print("      applicationInfo="); pw.println(appInfo);
20721                    }
20722                }
20723            }
20724
20725            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20726                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20727            }
20728
20729            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20730                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20731            }
20732
20733            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20734                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20735            }
20736
20737            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20738                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20739            }
20740
20741            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20742                // XXX should handle packageName != null by dumping only install data that
20743                // the given package is involved with.
20744                if (dumpState.onTitlePrinted()) pw.println();
20745                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20746            }
20747
20748            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20749                // XXX should handle packageName != null by dumping only install data that
20750                // the given package is involved with.
20751                if (dumpState.onTitlePrinted()) pw.println();
20752
20753                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20754                ipw.println();
20755                ipw.println("Frozen packages:");
20756                ipw.increaseIndent();
20757                if (mFrozenPackages.size() == 0) {
20758                    ipw.println("(none)");
20759                } else {
20760                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20761                        ipw.println(mFrozenPackages.valueAt(i));
20762                    }
20763                }
20764                ipw.decreaseIndent();
20765            }
20766
20767            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20768                if (dumpState.onTitlePrinted()) pw.println();
20769                dumpDexoptStateLPr(pw, packageName);
20770            }
20771
20772            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20773                if (dumpState.onTitlePrinted()) pw.println();
20774                dumpCompilerStatsLPr(pw, packageName);
20775            }
20776
20777            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20778                if (dumpState.onTitlePrinted()) pw.println();
20779                dumpEnabledOverlaysLPr(pw);
20780            }
20781
20782            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20783                if (dumpState.onTitlePrinted()) pw.println();
20784                mSettings.dumpReadMessagesLPr(pw, dumpState);
20785
20786                pw.println();
20787                pw.println("Package warning messages:");
20788                BufferedReader in = null;
20789                String line = null;
20790                try {
20791                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20792                    while ((line = in.readLine()) != null) {
20793                        if (line.contains("ignored: updated version")) continue;
20794                        pw.println(line);
20795                    }
20796                } catch (IOException ignored) {
20797                } finally {
20798                    IoUtils.closeQuietly(in);
20799                }
20800            }
20801
20802            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20803                BufferedReader in = null;
20804                String line = null;
20805                try {
20806                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20807                    while ((line = in.readLine()) != null) {
20808                        if (line.contains("ignored: updated version")) continue;
20809                        pw.print("msg,");
20810                        pw.println(line);
20811                    }
20812                } catch (IOException ignored) {
20813                } finally {
20814                    IoUtils.closeQuietly(in);
20815                }
20816            }
20817        }
20818    }
20819
20820    private void dumpProto(FileDescriptor fd) {
20821        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20822
20823        synchronized (mPackages) {
20824            final long requiredVerifierPackageToken =
20825                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20826            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20827            proto.write(
20828                    PackageServiceDumpProto.PackageShortProto.UID,
20829                    getPackageUid(
20830                            mRequiredVerifierPackage,
20831                            MATCH_DEBUG_TRIAGED_MISSING,
20832                            UserHandle.USER_SYSTEM));
20833            proto.end(requiredVerifierPackageToken);
20834
20835            if (mIntentFilterVerifierComponent != null) {
20836                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20837                final long verifierPackageToken =
20838                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20839                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20840                proto.write(
20841                        PackageServiceDumpProto.PackageShortProto.UID,
20842                        getPackageUid(
20843                                verifierPackageName,
20844                                MATCH_DEBUG_TRIAGED_MISSING,
20845                                UserHandle.USER_SYSTEM));
20846                proto.end(verifierPackageToken);
20847            }
20848
20849            dumpSharedLibrariesProto(proto);
20850            dumpFeaturesProto(proto);
20851            mSettings.dumpPackagesProto(proto);
20852            mSettings.dumpSharedUsersProto(proto);
20853            dumpMessagesProto(proto);
20854        }
20855        proto.flush();
20856    }
20857
20858    private void dumpMessagesProto(ProtoOutputStream proto) {
20859        BufferedReader in = null;
20860        String line = null;
20861        try {
20862            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20863            while ((line = in.readLine()) != null) {
20864                if (line.contains("ignored: updated version")) continue;
20865                proto.write(PackageServiceDumpProto.MESSAGES, line);
20866            }
20867        } catch (IOException ignored) {
20868        } finally {
20869            IoUtils.closeQuietly(in);
20870        }
20871    }
20872
20873    private void dumpFeaturesProto(ProtoOutputStream proto) {
20874        synchronized (mAvailableFeatures) {
20875            final int count = mAvailableFeatures.size();
20876            for (int i = 0; i < count; i++) {
20877                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20878                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20879                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20880                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20881                proto.end(featureToken);
20882            }
20883        }
20884    }
20885
20886    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20887        final int count = mSharedLibraries.size();
20888        for (int i = 0; i < count; i++) {
20889            final String libName = mSharedLibraries.keyAt(i);
20890            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20891            if (versionedLib == null) {
20892                continue;
20893            }
20894            final int versionCount = versionedLib.size();
20895            for (int j = 0; j < versionCount; j++) {
20896                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20897                final long sharedLibraryToken =
20898                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20899                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20900                final boolean isJar = (libEntry.path != null);
20901                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20902                if (isJar) {
20903                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20904                } else {
20905                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20906                }
20907                proto.end(sharedLibraryToken);
20908            }
20909        }
20910    }
20911
20912    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20913        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20914        ipw.println();
20915        ipw.println("Dexopt state:");
20916        ipw.increaseIndent();
20917        Collection<PackageParser.Package> packages = null;
20918        if (packageName != null) {
20919            PackageParser.Package targetPackage = mPackages.get(packageName);
20920            if (targetPackage != null) {
20921                packages = Collections.singletonList(targetPackage);
20922            } else {
20923                ipw.println("Unable to find package: " + packageName);
20924                return;
20925            }
20926        } else {
20927            packages = mPackages.values();
20928        }
20929
20930        for (PackageParser.Package pkg : packages) {
20931            ipw.println("[" + pkg.packageName + "]");
20932            ipw.increaseIndent();
20933            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20934            ipw.decreaseIndent();
20935        }
20936    }
20937
20938    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20939        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20940        ipw.println();
20941        ipw.println("Compiler stats:");
20942        ipw.increaseIndent();
20943        Collection<PackageParser.Package> packages = null;
20944        if (packageName != null) {
20945            PackageParser.Package targetPackage = mPackages.get(packageName);
20946            if (targetPackage != null) {
20947                packages = Collections.singletonList(targetPackage);
20948            } else {
20949                ipw.println("Unable to find package: " + packageName);
20950                return;
20951            }
20952        } else {
20953            packages = mPackages.values();
20954        }
20955
20956        for (PackageParser.Package pkg : packages) {
20957            ipw.println("[" + pkg.packageName + "]");
20958            ipw.increaseIndent();
20959
20960            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20961            if (stats == null) {
20962                ipw.println("(No recorded stats)");
20963            } else {
20964                stats.dump(ipw);
20965            }
20966            ipw.decreaseIndent();
20967        }
20968    }
20969
20970    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20971        pw.println("Enabled overlay paths:");
20972        final int N = mEnabledOverlayPaths.size();
20973        for (int i = 0; i < N; i++) {
20974            final int userId = mEnabledOverlayPaths.keyAt(i);
20975            pw.println(String.format("    User %d:", userId));
20976            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20977                mEnabledOverlayPaths.valueAt(i);
20978            final int M = userSpecificOverlays.size();
20979            for (int j = 0; j < M; j++) {
20980                final String targetPackageName = userSpecificOverlays.keyAt(j);
20981                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20982                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20983            }
20984        }
20985    }
20986
20987    private String dumpDomainString(String packageName) {
20988        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20989                .getList();
20990        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20991
20992        ArraySet<String> result = new ArraySet<>();
20993        if (iviList.size() > 0) {
20994            for (IntentFilterVerificationInfo ivi : iviList) {
20995                for (String host : ivi.getDomains()) {
20996                    result.add(host);
20997                }
20998            }
20999        }
21000        if (filters != null && filters.size() > 0) {
21001            for (IntentFilter filter : filters) {
21002                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21003                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21004                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21005                    result.addAll(filter.getHostsList());
21006                }
21007            }
21008        }
21009
21010        StringBuilder sb = new StringBuilder(result.size() * 16);
21011        for (String domain : result) {
21012            if (sb.length() > 0) sb.append(" ");
21013            sb.append(domain);
21014        }
21015        return sb.toString();
21016    }
21017
21018    // ------- apps on sdcard specific code -------
21019    static final boolean DEBUG_SD_INSTALL = false;
21020
21021    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21022
21023    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21024
21025    private boolean mMediaMounted = false;
21026
21027    static String getEncryptKey() {
21028        try {
21029            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21030                    SD_ENCRYPTION_KEYSTORE_NAME);
21031            if (sdEncKey == null) {
21032                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21033                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21034                if (sdEncKey == null) {
21035                    Slog.e(TAG, "Failed to create encryption keys");
21036                    return null;
21037                }
21038            }
21039            return sdEncKey;
21040        } catch (NoSuchAlgorithmException nsae) {
21041            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21042            return null;
21043        } catch (IOException ioe) {
21044            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21045            return null;
21046        }
21047    }
21048
21049    /*
21050     * Update media status on PackageManager.
21051     */
21052    @Override
21053    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21054        int callingUid = Binder.getCallingUid();
21055        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21056            throw new SecurityException("Media status can only be updated by the system");
21057        }
21058        // reader; this apparently protects mMediaMounted, but should probably
21059        // be a different lock in that case.
21060        synchronized (mPackages) {
21061            Log.i(TAG, "Updating external media status from "
21062                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21063                    + (mediaStatus ? "mounted" : "unmounted"));
21064            if (DEBUG_SD_INSTALL)
21065                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21066                        + ", mMediaMounted=" + mMediaMounted);
21067            if (mediaStatus == mMediaMounted) {
21068                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21069                        : 0, -1);
21070                mHandler.sendMessage(msg);
21071                return;
21072            }
21073            mMediaMounted = mediaStatus;
21074        }
21075        // Queue up an async operation since the package installation may take a
21076        // little while.
21077        mHandler.post(new Runnable() {
21078            public void run() {
21079                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21080            }
21081        });
21082    }
21083
21084    /**
21085     * Called by StorageManagerService when the initial ASECs to scan are available.
21086     * Should block until all the ASEC containers are finished being scanned.
21087     */
21088    public void scanAvailableAsecs() {
21089        updateExternalMediaStatusInner(true, false, false);
21090    }
21091
21092    /*
21093     * Collect information of applications on external media, map them against
21094     * existing containers and update information based on current mount status.
21095     * Please note that we always have to report status if reportStatus has been
21096     * set to true especially when unloading packages.
21097     */
21098    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21099            boolean externalStorage) {
21100        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21101        int[] uidArr = EmptyArray.INT;
21102
21103        final String[] list = PackageHelper.getSecureContainerList();
21104        if (ArrayUtils.isEmpty(list)) {
21105            Log.i(TAG, "No secure containers found");
21106        } else {
21107            // Process list of secure containers and categorize them
21108            // as active or stale based on their package internal state.
21109
21110            // reader
21111            synchronized (mPackages) {
21112                for (String cid : list) {
21113                    // Leave stages untouched for now; installer service owns them
21114                    if (PackageInstallerService.isStageName(cid)) continue;
21115
21116                    if (DEBUG_SD_INSTALL)
21117                        Log.i(TAG, "Processing container " + cid);
21118                    String pkgName = getAsecPackageName(cid);
21119                    if (pkgName == null) {
21120                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21121                        continue;
21122                    }
21123                    if (DEBUG_SD_INSTALL)
21124                        Log.i(TAG, "Looking for pkg : " + pkgName);
21125
21126                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21127                    if (ps == null) {
21128                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21129                        continue;
21130                    }
21131
21132                    /*
21133                     * Skip packages that are not external if we're unmounting
21134                     * external storage.
21135                     */
21136                    if (externalStorage && !isMounted && !isExternal(ps)) {
21137                        continue;
21138                    }
21139
21140                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21141                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21142                    // The package status is changed only if the code path
21143                    // matches between settings and the container id.
21144                    if (ps.codePathString != null
21145                            && ps.codePathString.startsWith(args.getCodePath())) {
21146                        if (DEBUG_SD_INSTALL) {
21147                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21148                                    + " at code path: " + ps.codePathString);
21149                        }
21150
21151                        // We do have a valid package installed on sdcard
21152                        processCids.put(args, ps.codePathString);
21153                        final int uid = ps.appId;
21154                        if (uid != -1) {
21155                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21156                        }
21157                    } else {
21158                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21159                                + ps.codePathString);
21160                    }
21161                }
21162            }
21163
21164            Arrays.sort(uidArr);
21165        }
21166
21167        // Process packages with valid entries.
21168        if (isMounted) {
21169            if (DEBUG_SD_INSTALL)
21170                Log.i(TAG, "Loading packages");
21171            loadMediaPackages(processCids, uidArr, externalStorage);
21172            startCleaningPackages();
21173            mInstallerService.onSecureContainersAvailable();
21174        } else {
21175            if (DEBUG_SD_INSTALL)
21176                Log.i(TAG, "Unloading packages");
21177            unloadMediaPackages(processCids, uidArr, reportStatus);
21178        }
21179    }
21180
21181    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21182            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21183        final int size = infos.size();
21184        final String[] packageNames = new String[size];
21185        final int[] packageUids = new int[size];
21186        for (int i = 0; i < size; i++) {
21187            final ApplicationInfo info = infos.get(i);
21188            packageNames[i] = info.packageName;
21189            packageUids[i] = info.uid;
21190        }
21191        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21192                finishedReceiver);
21193    }
21194
21195    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21196            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21197        sendResourcesChangedBroadcast(mediaStatus, replacing,
21198                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21199    }
21200
21201    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21202            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21203        int size = pkgList.length;
21204        if (size > 0) {
21205            // Send broadcasts here
21206            Bundle extras = new Bundle();
21207            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21208            if (uidArr != null) {
21209                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21210            }
21211            if (replacing) {
21212                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21213            }
21214            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21215                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21216            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21217        }
21218    }
21219
21220   /*
21221     * Look at potentially valid container ids from processCids If package
21222     * information doesn't match the one on record or package scanning fails,
21223     * the cid is added to list of removeCids. We currently don't delete stale
21224     * containers.
21225     */
21226    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21227            boolean externalStorage) {
21228        ArrayList<String> pkgList = new ArrayList<String>();
21229        Set<AsecInstallArgs> keys = processCids.keySet();
21230
21231        for (AsecInstallArgs args : keys) {
21232            String codePath = processCids.get(args);
21233            if (DEBUG_SD_INSTALL)
21234                Log.i(TAG, "Loading container : " + args.cid);
21235            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21236            try {
21237                // Make sure there are no container errors first.
21238                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21239                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21240                            + " when installing from sdcard");
21241                    continue;
21242                }
21243                // Check code path here.
21244                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21245                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21246                            + " does not match one in settings " + codePath);
21247                    continue;
21248                }
21249                // Parse package
21250                int parseFlags = mDefParseFlags;
21251                if (args.isExternalAsec()) {
21252                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21253                }
21254                if (args.isFwdLocked()) {
21255                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21256                }
21257
21258                synchronized (mInstallLock) {
21259                    PackageParser.Package pkg = null;
21260                    try {
21261                        // Sadly we don't know the package name yet to freeze it
21262                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21263                                SCAN_IGNORE_FROZEN, 0, null);
21264                    } catch (PackageManagerException e) {
21265                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21266                    }
21267                    // Scan the package
21268                    if (pkg != null) {
21269                        /*
21270                         * TODO why is the lock being held? doPostInstall is
21271                         * called in other places without the lock. This needs
21272                         * to be straightened out.
21273                         */
21274                        // writer
21275                        synchronized (mPackages) {
21276                            retCode = PackageManager.INSTALL_SUCCEEDED;
21277                            pkgList.add(pkg.packageName);
21278                            // Post process args
21279                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21280                                    pkg.applicationInfo.uid);
21281                        }
21282                    } else {
21283                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21284                    }
21285                }
21286
21287            } finally {
21288                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21289                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21290                }
21291            }
21292        }
21293        // writer
21294        synchronized (mPackages) {
21295            // If the platform SDK has changed since the last time we booted,
21296            // we need to re-grant app permission to catch any new ones that
21297            // appear. This is really a hack, and means that apps can in some
21298            // cases get permissions that the user didn't initially explicitly
21299            // allow... it would be nice to have some better way to handle
21300            // this situation.
21301            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21302                    : mSettings.getInternalVersion();
21303            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21304                    : StorageManager.UUID_PRIVATE_INTERNAL;
21305
21306            int updateFlags = UPDATE_PERMISSIONS_ALL;
21307            if (ver.sdkVersion != mSdkVersion) {
21308                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21309                        + mSdkVersion + "; regranting permissions for external");
21310                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21311            }
21312            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21313
21314            // Yay, everything is now upgraded
21315            ver.forceCurrent();
21316
21317            // can downgrade to reader
21318            // Persist settings
21319            mSettings.writeLPr();
21320        }
21321        // Send a broadcast to let everyone know we are done processing
21322        if (pkgList.size() > 0) {
21323            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21324        }
21325    }
21326
21327   /*
21328     * Utility method to unload a list of specified containers
21329     */
21330    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21331        // Just unmount all valid containers.
21332        for (AsecInstallArgs arg : cidArgs) {
21333            synchronized (mInstallLock) {
21334                arg.doPostDeleteLI(false);
21335           }
21336       }
21337   }
21338
21339    /*
21340     * Unload packages mounted on external media. This involves deleting package
21341     * data from internal structures, sending broadcasts about disabled packages,
21342     * gc'ing to free up references, unmounting all secure containers
21343     * corresponding to packages on external media, and posting a
21344     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21345     * that we always have to post this message if status has been requested no
21346     * matter what.
21347     */
21348    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21349            final boolean reportStatus) {
21350        if (DEBUG_SD_INSTALL)
21351            Log.i(TAG, "unloading media packages");
21352        ArrayList<String> pkgList = new ArrayList<String>();
21353        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21354        final Set<AsecInstallArgs> keys = processCids.keySet();
21355        for (AsecInstallArgs args : keys) {
21356            String pkgName = args.getPackageName();
21357            if (DEBUG_SD_INSTALL)
21358                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21359            // Delete package internally
21360            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21361            synchronized (mInstallLock) {
21362                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21363                final boolean res;
21364                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21365                        "unloadMediaPackages")) {
21366                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21367                            null);
21368                }
21369                if (res) {
21370                    pkgList.add(pkgName);
21371                } else {
21372                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21373                    failedList.add(args);
21374                }
21375            }
21376        }
21377
21378        // reader
21379        synchronized (mPackages) {
21380            // We didn't update the settings after removing each package;
21381            // write them now for all packages.
21382            mSettings.writeLPr();
21383        }
21384
21385        // We have to absolutely send UPDATED_MEDIA_STATUS only
21386        // after confirming that all the receivers processed the ordered
21387        // broadcast when packages get disabled, force a gc to clean things up.
21388        // and unload all the containers.
21389        if (pkgList.size() > 0) {
21390            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21391                    new IIntentReceiver.Stub() {
21392                public void performReceive(Intent intent, int resultCode, String data,
21393                        Bundle extras, boolean ordered, boolean sticky,
21394                        int sendingUser) throws RemoteException {
21395                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21396                            reportStatus ? 1 : 0, 1, keys);
21397                    mHandler.sendMessage(msg);
21398                }
21399            });
21400        } else {
21401            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21402                    keys);
21403            mHandler.sendMessage(msg);
21404        }
21405    }
21406
21407    private void loadPrivatePackages(final VolumeInfo vol) {
21408        mHandler.post(new Runnable() {
21409            @Override
21410            public void run() {
21411                loadPrivatePackagesInner(vol);
21412            }
21413        });
21414    }
21415
21416    private void loadPrivatePackagesInner(VolumeInfo vol) {
21417        final String volumeUuid = vol.fsUuid;
21418        if (TextUtils.isEmpty(volumeUuid)) {
21419            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21420            return;
21421        }
21422
21423        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21424        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21425        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21426
21427        final VersionInfo ver;
21428        final List<PackageSetting> packages;
21429        synchronized (mPackages) {
21430            ver = mSettings.findOrCreateVersion(volumeUuid);
21431            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21432        }
21433
21434        for (PackageSetting ps : packages) {
21435            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21436            synchronized (mInstallLock) {
21437                final PackageParser.Package pkg;
21438                try {
21439                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21440                    loaded.add(pkg.applicationInfo);
21441
21442                } catch (PackageManagerException e) {
21443                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21444                }
21445
21446                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21447                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21448                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21449                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21450                }
21451            }
21452        }
21453
21454        // Reconcile app data for all started/unlocked users
21455        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21456        final UserManager um = mContext.getSystemService(UserManager.class);
21457        UserManagerInternal umInternal = getUserManagerInternal();
21458        for (UserInfo user : um.getUsers()) {
21459            final int flags;
21460            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21461                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21462            } else if (umInternal.isUserRunning(user.id)) {
21463                flags = StorageManager.FLAG_STORAGE_DE;
21464            } else {
21465                continue;
21466            }
21467
21468            try {
21469                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21470                synchronized (mInstallLock) {
21471                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21472                }
21473            } catch (IllegalStateException e) {
21474                // Device was probably ejected, and we'll process that event momentarily
21475                Slog.w(TAG, "Failed to prepare storage: " + e);
21476            }
21477        }
21478
21479        synchronized (mPackages) {
21480            int updateFlags = UPDATE_PERMISSIONS_ALL;
21481            if (ver.sdkVersion != mSdkVersion) {
21482                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21483                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21484                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21485            }
21486            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21487
21488            // Yay, everything is now upgraded
21489            ver.forceCurrent();
21490
21491            mSettings.writeLPr();
21492        }
21493
21494        for (PackageFreezer freezer : freezers) {
21495            freezer.close();
21496        }
21497
21498        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21499        sendResourcesChangedBroadcast(true, false, loaded, null);
21500    }
21501
21502    private void unloadPrivatePackages(final VolumeInfo vol) {
21503        mHandler.post(new Runnable() {
21504            @Override
21505            public void run() {
21506                unloadPrivatePackagesInner(vol);
21507            }
21508        });
21509    }
21510
21511    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21512        final String volumeUuid = vol.fsUuid;
21513        if (TextUtils.isEmpty(volumeUuid)) {
21514            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21515            return;
21516        }
21517
21518        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21519        synchronized (mInstallLock) {
21520        synchronized (mPackages) {
21521            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21522            for (PackageSetting ps : packages) {
21523                if (ps.pkg == null) continue;
21524
21525                final ApplicationInfo info = ps.pkg.applicationInfo;
21526                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21527                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21528
21529                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21530                        "unloadPrivatePackagesInner")) {
21531                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21532                            false, null)) {
21533                        unloaded.add(info);
21534                    } else {
21535                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21536                    }
21537                }
21538
21539                // Try very hard to release any references to this package
21540                // so we don't risk the system server being killed due to
21541                // open FDs
21542                AttributeCache.instance().removePackage(ps.name);
21543            }
21544
21545            mSettings.writeLPr();
21546        }
21547        }
21548
21549        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21550        sendResourcesChangedBroadcast(false, false, unloaded, null);
21551
21552        // Try very hard to release any references to this path so we don't risk
21553        // the system server being killed due to open FDs
21554        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21555
21556        for (int i = 0; i < 3; i++) {
21557            System.gc();
21558            System.runFinalization();
21559        }
21560    }
21561
21562    private void assertPackageKnown(String volumeUuid, String packageName)
21563            throws PackageManagerException {
21564        synchronized (mPackages) {
21565            // Normalize package name to handle renamed packages
21566            packageName = normalizePackageNameLPr(packageName);
21567
21568            final PackageSetting ps = mSettings.mPackages.get(packageName);
21569            if (ps == null) {
21570                throw new PackageManagerException("Package " + packageName + " is unknown");
21571            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21572                throw new PackageManagerException(
21573                        "Package " + packageName + " found on unknown volume " + volumeUuid
21574                                + "; expected volume " + ps.volumeUuid);
21575            }
21576        }
21577    }
21578
21579    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21580            throws PackageManagerException {
21581        synchronized (mPackages) {
21582            // Normalize package name to handle renamed packages
21583            packageName = normalizePackageNameLPr(packageName);
21584
21585            final PackageSetting ps = mSettings.mPackages.get(packageName);
21586            if (ps == null) {
21587                throw new PackageManagerException("Package " + packageName + " is unknown");
21588            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21589                throw new PackageManagerException(
21590                        "Package " + packageName + " found on unknown volume " + volumeUuid
21591                                + "; expected volume " + ps.volumeUuid);
21592            } else if (!ps.getInstalled(userId)) {
21593                throw new PackageManagerException(
21594                        "Package " + packageName + " not installed for user " + userId);
21595            }
21596        }
21597    }
21598
21599    private List<String> collectAbsoluteCodePaths() {
21600        synchronized (mPackages) {
21601            List<String> codePaths = new ArrayList<>();
21602            final int packageCount = mSettings.mPackages.size();
21603            for (int i = 0; i < packageCount; i++) {
21604                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21605                codePaths.add(ps.codePath.getAbsolutePath());
21606            }
21607            return codePaths;
21608        }
21609    }
21610
21611    /**
21612     * Examine all apps present on given mounted volume, and destroy apps that
21613     * aren't expected, either due to uninstallation or reinstallation on
21614     * another volume.
21615     */
21616    private void reconcileApps(String volumeUuid) {
21617        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21618        List<File> filesToDelete = null;
21619
21620        final File[] files = FileUtils.listFilesOrEmpty(
21621                Environment.getDataAppDirectory(volumeUuid));
21622        for (File file : files) {
21623            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21624                    && !PackageInstallerService.isStageName(file.getName());
21625            if (!isPackage) {
21626                // Ignore entries which are not packages
21627                continue;
21628            }
21629
21630            String absolutePath = file.getAbsolutePath();
21631
21632            boolean pathValid = false;
21633            final int absoluteCodePathCount = absoluteCodePaths.size();
21634            for (int i = 0; i < absoluteCodePathCount; i++) {
21635                String absoluteCodePath = absoluteCodePaths.get(i);
21636                if (absolutePath.startsWith(absoluteCodePath)) {
21637                    pathValid = true;
21638                    break;
21639                }
21640            }
21641
21642            if (!pathValid) {
21643                if (filesToDelete == null) {
21644                    filesToDelete = new ArrayList<>();
21645                }
21646                filesToDelete.add(file);
21647            }
21648        }
21649
21650        if (filesToDelete != null) {
21651            final int fileToDeleteCount = filesToDelete.size();
21652            for (int i = 0; i < fileToDeleteCount; i++) {
21653                File fileToDelete = filesToDelete.get(i);
21654                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21655                synchronized (mInstallLock) {
21656                    removeCodePathLI(fileToDelete);
21657                }
21658            }
21659        }
21660    }
21661
21662    /**
21663     * Reconcile all app data for the given user.
21664     * <p>
21665     * Verifies that directories exist and that ownership and labeling is
21666     * correct for all installed apps on all mounted volumes.
21667     */
21668    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21669        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21670        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21671            final String volumeUuid = vol.getFsUuid();
21672            synchronized (mInstallLock) {
21673                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21674            }
21675        }
21676    }
21677
21678    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21679            boolean migrateAppData) {
21680        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21681    }
21682
21683    /**
21684     * Reconcile all app data on given mounted volume.
21685     * <p>
21686     * Destroys app data that isn't expected, either due to uninstallation or
21687     * reinstallation on another volume.
21688     * <p>
21689     * Verifies that directories exist and that ownership and labeling is
21690     * correct for all installed apps.
21691     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21692     */
21693    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21694            boolean migrateAppData, boolean onlyCoreApps) {
21695        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21696                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21697        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21698
21699        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21700        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21701
21702        // First look for stale data that doesn't belong, and check if things
21703        // have changed since we did our last restorecon
21704        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21705            if (StorageManager.isFileEncryptedNativeOrEmulated()
21706                    && !StorageManager.isUserKeyUnlocked(userId)) {
21707                throw new RuntimeException(
21708                        "Yikes, someone asked us to reconcile CE storage while " + userId
21709                                + " was still locked; this would have caused massive data loss!");
21710            }
21711
21712            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21713            for (File file : files) {
21714                final String packageName = file.getName();
21715                try {
21716                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21717                } catch (PackageManagerException e) {
21718                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21719                    try {
21720                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21721                                StorageManager.FLAG_STORAGE_CE, 0);
21722                    } catch (InstallerException e2) {
21723                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21724                    }
21725                }
21726            }
21727        }
21728        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21729            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21730            for (File file : files) {
21731                final String packageName = file.getName();
21732                try {
21733                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21734                } catch (PackageManagerException e) {
21735                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21736                    try {
21737                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21738                                StorageManager.FLAG_STORAGE_DE, 0);
21739                    } catch (InstallerException e2) {
21740                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21741                    }
21742                }
21743            }
21744        }
21745
21746        // Ensure that data directories are ready to roll for all packages
21747        // installed for this volume and user
21748        final List<PackageSetting> packages;
21749        synchronized (mPackages) {
21750            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21751        }
21752        int preparedCount = 0;
21753        for (PackageSetting ps : packages) {
21754            final String packageName = ps.name;
21755            if (ps.pkg == null) {
21756                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21757                // TODO: might be due to legacy ASEC apps; we should circle back
21758                // and reconcile again once they're scanned
21759                continue;
21760            }
21761            // Skip non-core apps if requested
21762            if (onlyCoreApps && !ps.pkg.coreApp) {
21763                result.add(packageName);
21764                continue;
21765            }
21766
21767            if (ps.getInstalled(userId)) {
21768                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21769                preparedCount++;
21770            }
21771        }
21772
21773        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21774        return result;
21775    }
21776
21777    /**
21778     * Prepare app data for the given app just after it was installed or
21779     * upgraded. This method carefully only touches users that it's installed
21780     * for, and it forces a restorecon to handle any seinfo changes.
21781     * <p>
21782     * Verifies that directories exist and that ownership and labeling is
21783     * correct for all installed apps. If there is an ownership mismatch, it
21784     * will try recovering system apps by wiping data; third-party app data is
21785     * left intact.
21786     * <p>
21787     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21788     */
21789    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21790        final PackageSetting ps;
21791        synchronized (mPackages) {
21792            ps = mSettings.mPackages.get(pkg.packageName);
21793            mSettings.writeKernelMappingLPr(ps);
21794        }
21795
21796        final UserManager um = mContext.getSystemService(UserManager.class);
21797        UserManagerInternal umInternal = getUserManagerInternal();
21798        for (UserInfo user : um.getUsers()) {
21799            final int flags;
21800            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21801                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21802            } else if (umInternal.isUserRunning(user.id)) {
21803                flags = StorageManager.FLAG_STORAGE_DE;
21804            } else {
21805                continue;
21806            }
21807
21808            if (ps.getInstalled(user.id)) {
21809                // TODO: when user data is locked, mark that we're still dirty
21810                prepareAppDataLIF(pkg, user.id, flags);
21811            }
21812        }
21813    }
21814
21815    /**
21816     * Prepare app data for the given app.
21817     * <p>
21818     * Verifies that directories exist and that ownership and labeling is
21819     * correct for all installed apps. If there is an ownership mismatch, this
21820     * will try recovering system apps by wiping data; third-party app data is
21821     * left intact.
21822     */
21823    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21824        if (pkg == null) {
21825            Slog.wtf(TAG, "Package was null!", new Throwable());
21826            return;
21827        }
21828        prepareAppDataLeafLIF(pkg, userId, flags);
21829        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21830        for (int i = 0; i < childCount; i++) {
21831            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21832        }
21833    }
21834
21835    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21836            boolean maybeMigrateAppData) {
21837        prepareAppDataLIF(pkg, userId, flags);
21838
21839        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21840            // We may have just shuffled around app data directories, so
21841            // prepare them one more time
21842            prepareAppDataLIF(pkg, userId, flags);
21843        }
21844    }
21845
21846    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21847        if (DEBUG_APP_DATA) {
21848            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21849                    + Integer.toHexString(flags));
21850        }
21851
21852        final String volumeUuid = pkg.volumeUuid;
21853        final String packageName = pkg.packageName;
21854        final ApplicationInfo app = pkg.applicationInfo;
21855        final int appId = UserHandle.getAppId(app.uid);
21856
21857        Preconditions.checkNotNull(app.seInfo);
21858
21859        long ceDataInode = -1;
21860        try {
21861            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21862                    appId, app.seInfo, app.targetSdkVersion);
21863        } catch (InstallerException e) {
21864            if (app.isSystemApp()) {
21865                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21866                        + ", but trying to recover: " + e);
21867                destroyAppDataLeafLIF(pkg, userId, flags);
21868                try {
21869                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21870                            appId, app.seInfo, app.targetSdkVersion);
21871                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21872                } catch (InstallerException e2) {
21873                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21874                }
21875            } else {
21876                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21877            }
21878        }
21879
21880        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21881            // TODO: mark this structure as dirty so we persist it!
21882            synchronized (mPackages) {
21883                final PackageSetting ps = mSettings.mPackages.get(packageName);
21884                if (ps != null) {
21885                    ps.setCeDataInode(ceDataInode, userId);
21886                }
21887            }
21888        }
21889
21890        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21891    }
21892
21893    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21894        if (pkg == null) {
21895            Slog.wtf(TAG, "Package was null!", new Throwable());
21896            return;
21897        }
21898        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21899        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21900        for (int i = 0; i < childCount; i++) {
21901            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21902        }
21903    }
21904
21905    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21906        final String volumeUuid = pkg.volumeUuid;
21907        final String packageName = pkg.packageName;
21908        final ApplicationInfo app = pkg.applicationInfo;
21909
21910        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21911            // Create a native library symlink only if we have native libraries
21912            // and if the native libraries are 32 bit libraries. We do not provide
21913            // this symlink for 64 bit libraries.
21914            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21915                final String nativeLibPath = app.nativeLibraryDir;
21916                try {
21917                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21918                            nativeLibPath, userId);
21919                } catch (InstallerException e) {
21920                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21921                }
21922            }
21923        }
21924    }
21925
21926    /**
21927     * For system apps on non-FBE devices, this method migrates any existing
21928     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21929     * requested by the app.
21930     */
21931    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21932        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21933                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21934            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21935                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21936            try {
21937                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21938                        storageTarget);
21939            } catch (InstallerException e) {
21940                logCriticalInfo(Log.WARN,
21941                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21942            }
21943            return true;
21944        } else {
21945            return false;
21946        }
21947    }
21948
21949    public PackageFreezer freezePackage(String packageName, String killReason) {
21950        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21951    }
21952
21953    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21954        return new PackageFreezer(packageName, userId, killReason);
21955    }
21956
21957    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21958            String killReason) {
21959        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21960    }
21961
21962    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21963            String killReason) {
21964        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21965            return new PackageFreezer();
21966        } else {
21967            return freezePackage(packageName, userId, killReason);
21968        }
21969    }
21970
21971    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21972            String killReason) {
21973        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21974    }
21975
21976    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21977            String killReason) {
21978        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21979            return new PackageFreezer();
21980        } else {
21981            return freezePackage(packageName, userId, killReason);
21982        }
21983    }
21984
21985    /**
21986     * Class that freezes and kills the given package upon creation, and
21987     * unfreezes it upon closing. This is typically used when doing surgery on
21988     * app code/data to prevent the app from running while you're working.
21989     */
21990    private class PackageFreezer implements AutoCloseable {
21991        private final String mPackageName;
21992        private final PackageFreezer[] mChildren;
21993
21994        private final boolean mWeFroze;
21995
21996        private final AtomicBoolean mClosed = new AtomicBoolean();
21997        private final CloseGuard mCloseGuard = CloseGuard.get();
21998
21999        /**
22000         * Create and return a stub freezer that doesn't actually do anything,
22001         * typically used when someone requested
22002         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22003         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22004         */
22005        public PackageFreezer() {
22006            mPackageName = null;
22007            mChildren = null;
22008            mWeFroze = false;
22009            mCloseGuard.open("close");
22010        }
22011
22012        public PackageFreezer(String packageName, int userId, String killReason) {
22013            synchronized (mPackages) {
22014                mPackageName = packageName;
22015                mWeFroze = mFrozenPackages.add(mPackageName);
22016
22017                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22018                if (ps != null) {
22019                    killApplication(ps.name, ps.appId, userId, killReason);
22020                }
22021
22022                final PackageParser.Package p = mPackages.get(packageName);
22023                if (p != null && p.childPackages != null) {
22024                    final int N = p.childPackages.size();
22025                    mChildren = new PackageFreezer[N];
22026                    for (int i = 0; i < N; i++) {
22027                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22028                                userId, killReason);
22029                    }
22030                } else {
22031                    mChildren = null;
22032                }
22033            }
22034            mCloseGuard.open("close");
22035        }
22036
22037        @Override
22038        protected void finalize() throws Throwable {
22039            try {
22040                mCloseGuard.warnIfOpen();
22041                close();
22042            } finally {
22043                super.finalize();
22044            }
22045        }
22046
22047        @Override
22048        public void close() {
22049            mCloseGuard.close();
22050            if (mClosed.compareAndSet(false, true)) {
22051                synchronized (mPackages) {
22052                    if (mWeFroze) {
22053                        mFrozenPackages.remove(mPackageName);
22054                    }
22055
22056                    if (mChildren != null) {
22057                        for (PackageFreezer freezer : mChildren) {
22058                            freezer.close();
22059                        }
22060                    }
22061                }
22062            }
22063        }
22064    }
22065
22066    /**
22067     * Verify that given package is currently frozen.
22068     */
22069    private void checkPackageFrozen(String packageName) {
22070        synchronized (mPackages) {
22071            if (!mFrozenPackages.contains(packageName)) {
22072                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22073            }
22074        }
22075    }
22076
22077    @Override
22078    public int movePackage(final String packageName, final String volumeUuid) {
22079        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22080
22081        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22082        final int moveId = mNextMoveId.getAndIncrement();
22083        mHandler.post(new Runnable() {
22084            @Override
22085            public void run() {
22086                try {
22087                    movePackageInternal(packageName, volumeUuid, moveId, user);
22088                } catch (PackageManagerException e) {
22089                    Slog.w(TAG, "Failed to move " + packageName, e);
22090                    mMoveCallbacks.notifyStatusChanged(moveId,
22091                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22092                }
22093            }
22094        });
22095        return moveId;
22096    }
22097
22098    private void movePackageInternal(final String packageName, final String volumeUuid,
22099            final int moveId, UserHandle user) throws PackageManagerException {
22100        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22101        final PackageManager pm = mContext.getPackageManager();
22102
22103        final boolean currentAsec;
22104        final String currentVolumeUuid;
22105        final File codeFile;
22106        final String installerPackageName;
22107        final String packageAbiOverride;
22108        final int appId;
22109        final String seinfo;
22110        final String label;
22111        final int targetSdkVersion;
22112        final PackageFreezer freezer;
22113        final int[] installedUserIds;
22114
22115        // reader
22116        synchronized (mPackages) {
22117            final PackageParser.Package pkg = mPackages.get(packageName);
22118            final PackageSetting ps = mSettings.mPackages.get(packageName);
22119            if (pkg == null || ps == null) {
22120                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22121            }
22122
22123            if (pkg.applicationInfo.isSystemApp()) {
22124                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22125                        "Cannot move system application");
22126            }
22127
22128            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22129            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22130                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22131            if (isInternalStorage && !allow3rdPartyOnInternal) {
22132                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22133                        "3rd party apps are not allowed on internal storage");
22134            }
22135
22136            if (pkg.applicationInfo.isExternalAsec()) {
22137                currentAsec = true;
22138                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22139            } else if (pkg.applicationInfo.isForwardLocked()) {
22140                currentAsec = true;
22141                currentVolumeUuid = "forward_locked";
22142            } else {
22143                currentAsec = false;
22144                currentVolumeUuid = ps.volumeUuid;
22145
22146                final File probe = new File(pkg.codePath);
22147                final File probeOat = new File(probe, "oat");
22148                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22149                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22150                            "Move only supported for modern cluster style installs");
22151                }
22152            }
22153
22154            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22155                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22156                        "Package already moved to " + volumeUuid);
22157            }
22158            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22159                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22160                        "Device admin cannot be moved");
22161            }
22162
22163            if (mFrozenPackages.contains(packageName)) {
22164                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22165                        "Failed to move already frozen package");
22166            }
22167
22168            codeFile = new File(pkg.codePath);
22169            installerPackageName = ps.installerPackageName;
22170            packageAbiOverride = ps.cpuAbiOverrideString;
22171            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22172            seinfo = pkg.applicationInfo.seInfo;
22173            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22174            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22175            freezer = freezePackage(packageName, "movePackageInternal");
22176            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22177        }
22178
22179        final Bundle extras = new Bundle();
22180        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22181        extras.putString(Intent.EXTRA_TITLE, label);
22182        mMoveCallbacks.notifyCreated(moveId, extras);
22183
22184        int installFlags;
22185        final boolean moveCompleteApp;
22186        final File measurePath;
22187
22188        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22189            installFlags = INSTALL_INTERNAL;
22190            moveCompleteApp = !currentAsec;
22191            measurePath = Environment.getDataAppDirectory(volumeUuid);
22192        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22193            installFlags = INSTALL_EXTERNAL;
22194            moveCompleteApp = false;
22195            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22196        } else {
22197            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22198            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22199                    || !volume.isMountedWritable()) {
22200                freezer.close();
22201                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22202                        "Move location not mounted private volume");
22203            }
22204
22205            Preconditions.checkState(!currentAsec);
22206
22207            installFlags = INSTALL_INTERNAL;
22208            moveCompleteApp = true;
22209            measurePath = Environment.getDataAppDirectory(volumeUuid);
22210        }
22211
22212        final PackageStats stats = new PackageStats(null, -1);
22213        synchronized (mInstaller) {
22214            for (int userId : installedUserIds) {
22215                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22216                    freezer.close();
22217                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22218                            "Failed to measure package size");
22219                }
22220            }
22221        }
22222
22223        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22224                + stats.dataSize);
22225
22226        final long startFreeBytes = measurePath.getFreeSpace();
22227        final long sizeBytes;
22228        if (moveCompleteApp) {
22229            sizeBytes = stats.codeSize + stats.dataSize;
22230        } else {
22231            sizeBytes = stats.codeSize;
22232        }
22233
22234        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22235            freezer.close();
22236            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22237                    "Not enough free space to move");
22238        }
22239
22240        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22241
22242        final CountDownLatch installedLatch = new CountDownLatch(1);
22243        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22244            @Override
22245            public void onUserActionRequired(Intent intent) throws RemoteException {
22246                throw new IllegalStateException();
22247            }
22248
22249            @Override
22250            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22251                    Bundle extras) throws RemoteException {
22252                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22253                        + PackageManager.installStatusToString(returnCode, msg));
22254
22255                installedLatch.countDown();
22256                freezer.close();
22257
22258                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22259                switch (status) {
22260                    case PackageInstaller.STATUS_SUCCESS:
22261                        mMoveCallbacks.notifyStatusChanged(moveId,
22262                                PackageManager.MOVE_SUCCEEDED);
22263                        break;
22264                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22265                        mMoveCallbacks.notifyStatusChanged(moveId,
22266                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22267                        break;
22268                    default:
22269                        mMoveCallbacks.notifyStatusChanged(moveId,
22270                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22271                        break;
22272                }
22273            }
22274        };
22275
22276        final MoveInfo move;
22277        if (moveCompleteApp) {
22278            // Kick off a thread to report progress estimates
22279            new Thread() {
22280                @Override
22281                public void run() {
22282                    while (true) {
22283                        try {
22284                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22285                                break;
22286                            }
22287                        } catch (InterruptedException ignored) {
22288                        }
22289
22290                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22291                        final int progress = 10 + (int) MathUtils.constrain(
22292                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22293                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22294                    }
22295                }
22296            }.start();
22297
22298            final String dataAppName = codeFile.getName();
22299            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22300                    dataAppName, appId, seinfo, targetSdkVersion);
22301        } else {
22302            move = null;
22303        }
22304
22305        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22306
22307        final Message msg = mHandler.obtainMessage(INIT_COPY);
22308        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22309        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22310                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22311                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22312                PackageManager.INSTALL_REASON_UNKNOWN);
22313        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22314        msg.obj = params;
22315
22316        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22317                System.identityHashCode(msg.obj));
22318        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22319                System.identityHashCode(msg.obj));
22320
22321        mHandler.sendMessage(msg);
22322    }
22323
22324    @Override
22325    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22326        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22327
22328        final int realMoveId = mNextMoveId.getAndIncrement();
22329        final Bundle extras = new Bundle();
22330        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22331        mMoveCallbacks.notifyCreated(realMoveId, extras);
22332
22333        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22334            @Override
22335            public void onCreated(int moveId, Bundle extras) {
22336                // Ignored
22337            }
22338
22339            @Override
22340            public void onStatusChanged(int moveId, int status, long estMillis) {
22341                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22342            }
22343        };
22344
22345        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22346        storage.setPrimaryStorageUuid(volumeUuid, callback);
22347        return realMoveId;
22348    }
22349
22350    @Override
22351    public int getMoveStatus(int moveId) {
22352        mContext.enforceCallingOrSelfPermission(
22353                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22354        return mMoveCallbacks.mLastStatus.get(moveId);
22355    }
22356
22357    @Override
22358    public void registerMoveCallback(IPackageMoveObserver callback) {
22359        mContext.enforceCallingOrSelfPermission(
22360                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22361        mMoveCallbacks.register(callback);
22362    }
22363
22364    @Override
22365    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22366        mContext.enforceCallingOrSelfPermission(
22367                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22368        mMoveCallbacks.unregister(callback);
22369    }
22370
22371    @Override
22372    public boolean setInstallLocation(int loc) {
22373        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22374                null);
22375        if (getInstallLocation() == loc) {
22376            return true;
22377        }
22378        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22379                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22380            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22381                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22382            return true;
22383        }
22384        return false;
22385   }
22386
22387    @Override
22388    public int getInstallLocation() {
22389        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22390                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22391                PackageHelper.APP_INSTALL_AUTO);
22392    }
22393
22394    /** Called by UserManagerService */
22395    void cleanUpUser(UserManagerService userManager, int userHandle) {
22396        synchronized (mPackages) {
22397            mDirtyUsers.remove(userHandle);
22398            mUserNeedsBadging.delete(userHandle);
22399            mSettings.removeUserLPw(userHandle);
22400            mPendingBroadcasts.remove(userHandle);
22401            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22402            removeUnusedPackagesLPw(userManager, userHandle);
22403        }
22404    }
22405
22406    /**
22407     * We're removing userHandle and would like to remove any downloaded packages
22408     * that are no longer in use by any other user.
22409     * @param userHandle the user being removed
22410     */
22411    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22412        final boolean DEBUG_CLEAN_APKS = false;
22413        int [] users = userManager.getUserIds();
22414        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22415        while (psit.hasNext()) {
22416            PackageSetting ps = psit.next();
22417            if (ps.pkg == null) {
22418                continue;
22419            }
22420            final String packageName = ps.pkg.packageName;
22421            // Skip over if system app
22422            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22423                continue;
22424            }
22425            if (DEBUG_CLEAN_APKS) {
22426                Slog.i(TAG, "Checking package " + packageName);
22427            }
22428            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22429            if (keep) {
22430                if (DEBUG_CLEAN_APKS) {
22431                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22432                }
22433            } else {
22434                for (int i = 0; i < users.length; i++) {
22435                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22436                        keep = true;
22437                        if (DEBUG_CLEAN_APKS) {
22438                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22439                                    + users[i]);
22440                        }
22441                        break;
22442                    }
22443                }
22444            }
22445            if (!keep) {
22446                if (DEBUG_CLEAN_APKS) {
22447                    Slog.i(TAG, "  Removing package " + packageName);
22448                }
22449                mHandler.post(new Runnable() {
22450                    public void run() {
22451                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22452                                userHandle, 0);
22453                    } //end run
22454                });
22455            }
22456        }
22457    }
22458
22459    /** Called by UserManagerService */
22460    void createNewUser(int userId, String[] disallowedPackages) {
22461        synchronized (mInstallLock) {
22462            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22463        }
22464        synchronized (mPackages) {
22465            scheduleWritePackageRestrictionsLocked(userId);
22466            scheduleWritePackageListLocked(userId);
22467            applyFactoryDefaultBrowserLPw(userId);
22468            primeDomainVerificationsLPw(userId);
22469        }
22470    }
22471
22472    void onNewUserCreated(final int userId) {
22473        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22474        // If permission review for legacy apps is required, we represent
22475        // dagerous permissions for such apps as always granted runtime
22476        // permissions to keep per user flag state whether review is needed.
22477        // Hence, if a new user is added we have to propagate dangerous
22478        // permission grants for these legacy apps.
22479        if (mPermissionReviewRequired) {
22480            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22481                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22482        }
22483    }
22484
22485    @Override
22486    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22487        mContext.enforceCallingOrSelfPermission(
22488                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22489                "Only package verification agents can read the verifier device identity");
22490
22491        synchronized (mPackages) {
22492            return mSettings.getVerifierDeviceIdentityLPw();
22493        }
22494    }
22495
22496    @Override
22497    public void setPermissionEnforced(String permission, boolean enforced) {
22498        // TODO: Now that we no longer change GID for storage, this should to away.
22499        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22500                "setPermissionEnforced");
22501        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22502            synchronized (mPackages) {
22503                if (mSettings.mReadExternalStorageEnforced == null
22504                        || mSettings.mReadExternalStorageEnforced != enforced) {
22505                    mSettings.mReadExternalStorageEnforced = enforced;
22506                    mSettings.writeLPr();
22507                }
22508            }
22509            // kill any non-foreground processes so we restart them and
22510            // grant/revoke the GID.
22511            final IActivityManager am = ActivityManager.getService();
22512            if (am != null) {
22513                final long token = Binder.clearCallingIdentity();
22514                try {
22515                    am.killProcessesBelowForeground("setPermissionEnforcement");
22516                } catch (RemoteException e) {
22517                } finally {
22518                    Binder.restoreCallingIdentity(token);
22519                }
22520            }
22521        } else {
22522            throw new IllegalArgumentException("No selective enforcement for " + permission);
22523        }
22524    }
22525
22526    @Override
22527    @Deprecated
22528    public boolean isPermissionEnforced(String permission) {
22529        return true;
22530    }
22531
22532    @Override
22533    public boolean isStorageLow() {
22534        final long token = Binder.clearCallingIdentity();
22535        try {
22536            final DeviceStorageMonitorInternal
22537                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22538            if (dsm != null) {
22539                return dsm.isMemoryLow();
22540            } else {
22541                return false;
22542            }
22543        } finally {
22544            Binder.restoreCallingIdentity(token);
22545        }
22546    }
22547
22548    @Override
22549    public IPackageInstaller getPackageInstaller() {
22550        return mInstallerService;
22551    }
22552
22553    private boolean userNeedsBadging(int userId) {
22554        int index = mUserNeedsBadging.indexOfKey(userId);
22555        if (index < 0) {
22556            final UserInfo userInfo;
22557            final long token = Binder.clearCallingIdentity();
22558            try {
22559                userInfo = sUserManager.getUserInfo(userId);
22560            } finally {
22561                Binder.restoreCallingIdentity(token);
22562            }
22563            final boolean b;
22564            if (userInfo != null && userInfo.isManagedProfile()) {
22565                b = true;
22566            } else {
22567                b = false;
22568            }
22569            mUserNeedsBadging.put(userId, b);
22570            return b;
22571        }
22572        return mUserNeedsBadging.valueAt(index);
22573    }
22574
22575    @Override
22576    public KeySet getKeySetByAlias(String packageName, String alias) {
22577        if (packageName == null || alias == null) {
22578            return null;
22579        }
22580        synchronized(mPackages) {
22581            final PackageParser.Package pkg = mPackages.get(packageName);
22582            if (pkg == null) {
22583                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22584                throw new IllegalArgumentException("Unknown package: " + packageName);
22585            }
22586            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22587            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22588        }
22589    }
22590
22591    @Override
22592    public KeySet getSigningKeySet(String packageName) {
22593        if (packageName == null) {
22594            return null;
22595        }
22596        synchronized(mPackages) {
22597            final PackageParser.Package pkg = mPackages.get(packageName);
22598            if (pkg == null) {
22599                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22600                throw new IllegalArgumentException("Unknown package: " + packageName);
22601            }
22602            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22603                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22604                throw new SecurityException("May not access signing KeySet of other apps.");
22605            }
22606            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22607            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22608        }
22609    }
22610
22611    @Override
22612    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22613        if (packageName == null || ks == null) {
22614            return false;
22615        }
22616        synchronized(mPackages) {
22617            final PackageParser.Package pkg = mPackages.get(packageName);
22618            if (pkg == null) {
22619                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22620                throw new IllegalArgumentException("Unknown package: " + packageName);
22621            }
22622            IBinder ksh = ks.getToken();
22623            if (ksh instanceof KeySetHandle) {
22624                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22625                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22626            }
22627            return false;
22628        }
22629    }
22630
22631    @Override
22632    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22633        if (packageName == null || ks == null) {
22634            return false;
22635        }
22636        synchronized(mPackages) {
22637            final PackageParser.Package pkg = mPackages.get(packageName);
22638            if (pkg == null) {
22639                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22640                throw new IllegalArgumentException("Unknown package: " + packageName);
22641            }
22642            IBinder ksh = ks.getToken();
22643            if (ksh instanceof KeySetHandle) {
22644                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22645                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22646            }
22647            return false;
22648        }
22649    }
22650
22651    private void deletePackageIfUnusedLPr(final String packageName) {
22652        PackageSetting ps = mSettings.mPackages.get(packageName);
22653        if (ps == null) {
22654            return;
22655        }
22656        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22657            // TODO Implement atomic delete if package is unused
22658            // It is currently possible that the package will be deleted even if it is installed
22659            // after this method returns.
22660            mHandler.post(new Runnable() {
22661                public void run() {
22662                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22663                            0, PackageManager.DELETE_ALL_USERS);
22664                }
22665            });
22666        }
22667    }
22668
22669    /**
22670     * Check and throw if the given before/after packages would be considered a
22671     * downgrade.
22672     */
22673    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22674            throws PackageManagerException {
22675        if (after.versionCode < before.mVersionCode) {
22676            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22677                    "Update version code " + after.versionCode + " is older than current "
22678                    + before.mVersionCode);
22679        } else if (after.versionCode == before.mVersionCode) {
22680            if (after.baseRevisionCode < before.baseRevisionCode) {
22681                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22682                        "Update base revision code " + after.baseRevisionCode
22683                        + " is older than current " + before.baseRevisionCode);
22684            }
22685
22686            if (!ArrayUtils.isEmpty(after.splitNames)) {
22687                for (int i = 0; i < after.splitNames.length; i++) {
22688                    final String splitName = after.splitNames[i];
22689                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22690                    if (j != -1) {
22691                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22692                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22693                                    "Update split " + splitName + " revision code "
22694                                    + after.splitRevisionCodes[i] + " is older than current "
22695                                    + before.splitRevisionCodes[j]);
22696                        }
22697                    }
22698                }
22699            }
22700        }
22701    }
22702
22703    private static class MoveCallbacks extends Handler {
22704        private static final int MSG_CREATED = 1;
22705        private static final int MSG_STATUS_CHANGED = 2;
22706
22707        private final RemoteCallbackList<IPackageMoveObserver>
22708                mCallbacks = new RemoteCallbackList<>();
22709
22710        private final SparseIntArray mLastStatus = new SparseIntArray();
22711
22712        public MoveCallbacks(Looper looper) {
22713            super(looper);
22714        }
22715
22716        public void register(IPackageMoveObserver callback) {
22717            mCallbacks.register(callback);
22718        }
22719
22720        public void unregister(IPackageMoveObserver callback) {
22721            mCallbacks.unregister(callback);
22722        }
22723
22724        @Override
22725        public void handleMessage(Message msg) {
22726            final SomeArgs args = (SomeArgs) msg.obj;
22727            final int n = mCallbacks.beginBroadcast();
22728            for (int i = 0; i < n; i++) {
22729                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22730                try {
22731                    invokeCallback(callback, msg.what, args);
22732                } catch (RemoteException ignored) {
22733                }
22734            }
22735            mCallbacks.finishBroadcast();
22736            args.recycle();
22737        }
22738
22739        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22740                throws RemoteException {
22741            switch (what) {
22742                case MSG_CREATED: {
22743                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22744                    break;
22745                }
22746                case MSG_STATUS_CHANGED: {
22747                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22748                    break;
22749                }
22750            }
22751        }
22752
22753        private void notifyCreated(int moveId, Bundle extras) {
22754            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22755
22756            final SomeArgs args = SomeArgs.obtain();
22757            args.argi1 = moveId;
22758            args.arg2 = extras;
22759            obtainMessage(MSG_CREATED, args).sendToTarget();
22760        }
22761
22762        private void notifyStatusChanged(int moveId, int status) {
22763            notifyStatusChanged(moveId, status, -1);
22764        }
22765
22766        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22767            Slog.v(TAG, "Move " + moveId + " status " + status);
22768
22769            final SomeArgs args = SomeArgs.obtain();
22770            args.argi1 = moveId;
22771            args.argi2 = status;
22772            args.arg3 = estMillis;
22773            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22774
22775            synchronized (mLastStatus) {
22776                mLastStatus.put(moveId, status);
22777            }
22778        }
22779    }
22780
22781    private final static class OnPermissionChangeListeners extends Handler {
22782        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22783
22784        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22785                new RemoteCallbackList<>();
22786
22787        public OnPermissionChangeListeners(Looper looper) {
22788            super(looper);
22789        }
22790
22791        @Override
22792        public void handleMessage(Message msg) {
22793            switch (msg.what) {
22794                case MSG_ON_PERMISSIONS_CHANGED: {
22795                    final int uid = msg.arg1;
22796                    handleOnPermissionsChanged(uid);
22797                } break;
22798            }
22799        }
22800
22801        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22802            mPermissionListeners.register(listener);
22803
22804        }
22805
22806        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22807            mPermissionListeners.unregister(listener);
22808        }
22809
22810        public void onPermissionsChanged(int uid) {
22811            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22812                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22813            }
22814        }
22815
22816        private void handleOnPermissionsChanged(int uid) {
22817            final int count = mPermissionListeners.beginBroadcast();
22818            try {
22819                for (int i = 0; i < count; i++) {
22820                    IOnPermissionsChangeListener callback = mPermissionListeners
22821                            .getBroadcastItem(i);
22822                    try {
22823                        callback.onPermissionsChanged(uid);
22824                    } catch (RemoteException e) {
22825                        Log.e(TAG, "Permission listener is dead", e);
22826                    }
22827                }
22828            } finally {
22829                mPermissionListeners.finishBroadcast();
22830            }
22831        }
22832    }
22833
22834    private class PackageManagerInternalImpl extends PackageManagerInternal {
22835        @Override
22836        public void setLocationPackagesProvider(PackagesProvider provider) {
22837            synchronized (mPackages) {
22838                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22839            }
22840        }
22841
22842        @Override
22843        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22844            synchronized (mPackages) {
22845                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22846            }
22847        }
22848
22849        @Override
22850        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22851            synchronized (mPackages) {
22852                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22853            }
22854        }
22855
22856        @Override
22857        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22858            synchronized (mPackages) {
22859                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22860            }
22861        }
22862
22863        @Override
22864        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22865            synchronized (mPackages) {
22866                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22867            }
22868        }
22869
22870        @Override
22871        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22872            synchronized (mPackages) {
22873                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22874            }
22875        }
22876
22877        @Override
22878        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22879            synchronized (mPackages) {
22880                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22881                        packageName, userId);
22882            }
22883        }
22884
22885        @Override
22886        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22887            synchronized (mPackages) {
22888                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22889                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22890                        packageName, userId);
22891            }
22892        }
22893
22894        @Override
22895        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22896            synchronized (mPackages) {
22897                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22898                        packageName, userId);
22899            }
22900        }
22901
22902        @Override
22903        public void setKeepUninstalledPackages(final List<String> packageList) {
22904            Preconditions.checkNotNull(packageList);
22905            List<String> removedFromList = null;
22906            synchronized (mPackages) {
22907                if (mKeepUninstalledPackages != null) {
22908                    final int packagesCount = mKeepUninstalledPackages.size();
22909                    for (int i = 0; i < packagesCount; i++) {
22910                        String oldPackage = mKeepUninstalledPackages.get(i);
22911                        if (packageList != null && packageList.contains(oldPackage)) {
22912                            continue;
22913                        }
22914                        if (removedFromList == null) {
22915                            removedFromList = new ArrayList<>();
22916                        }
22917                        removedFromList.add(oldPackage);
22918                    }
22919                }
22920                mKeepUninstalledPackages = new ArrayList<>(packageList);
22921                if (removedFromList != null) {
22922                    final int removedCount = removedFromList.size();
22923                    for (int i = 0; i < removedCount; i++) {
22924                        deletePackageIfUnusedLPr(removedFromList.get(i));
22925                    }
22926                }
22927            }
22928        }
22929
22930        @Override
22931        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22932            synchronized (mPackages) {
22933                // If we do not support permission review, done.
22934                if (!mPermissionReviewRequired) {
22935                    return false;
22936                }
22937
22938                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22939                if (packageSetting == null) {
22940                    return false;
22941                }
22942
22943                // Permission review applies only to apps not supporting the new permission model.
22944                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22945                    return false;
22946                }
22947
22948                // Legacy apps have the permission and get user consent on launch.
22949                PermissionsState permissionsState = packageSetting.getPermissionsState();
22950                return permissionsState.isPermissionReviewRequired(userId);
22951            }
22952        }
22953
22954        @Override
22955        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22956            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22957        }
22958
22959        @Override
22960        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22961                int userId) {
22962            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22963        }
22964
22965        @Override
22966        public void setDeviceAndProfileOwnerPackages(
22967                int deviceOwnerUserId, String deviceOwnerPackage,
22968                SparseArray<String> profileOwnerPackages) {
22969            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22970                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22971        }
22972
22973        @Override
22974        public boolean isPackageDataProtected(int userId, String packageName) {
22975            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22976        }
22977
22978        @Override
22979        public boolean isPackageEphemeral(int userId, String packageName) {
22980            synchronized (mPackages) {
22981                final PackageSetting ps = mSettings.mPackages.get(packageName);
22982                return ps != null ? ps.getInstantApp(userId) : false;
22983            }
22984        }
22985
22986        @Override
22987        public boolean wasPackageEverLaunched(String packageName, int userId) {
22988            synchronized (mPackages) {
22989                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22990            }
22991        }
22992
22993        @Override
22994        public void grantRuntimePermission(String packageName, String name, int userId,
22995                boolean overridePolicy) {
22996            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22997                    overridePolicy);
22998        }
22999
23000        @Override
23001        public void revokeRuntimePermission(String packageName, String name, int userId,
23002                boolean overridePolicy) {
23003            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23004                    overridePolicy);
23005        }
23006
23007        @Override
23008        public String getNameForUid(int uid) {
23009            return PackageManagerService.this.getNameForUid(uid);
23010        }
23011
23012        @Override
23013        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23014                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23015            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23016                    responseObj, origIntent, resolvedType, callingPackage, userId);
23017        }
23018
23019        @Override
23020        public void grantEphemeralAccess(int userId, Intent intent,
23021                int targetAppId, int ephemeralAppId) {
23022            synchronized (mPackages) {
23023                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23024                        targetAppId, ephemeralAppId);
23025            }
23026        }
23027
23028        @Override
23029        public void pruneInstantApps() {
23030            synchronized (mPackages) {
23031                mInstantAppRegistry.pruneInstantAppsLPw();
23032            }
23033        }
23034
23035        @Override
23036        public String getSetupWizardPackageName() {
23037            return mSetupWizardPackage;
23038        }
23039
23040        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23041            if (policy != null) {
23042                mExternalSourcesPolicy = policy;
23043            }
23044        }
23045
23046        @Override
23047        public boolean isPackagePersistent(String packageName) {
23048            synchronized (mPackages) {
23049                PackageParser.Package pkg = mPackages.get(packageName);
23050                return pkg != null
23051                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23052                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23053                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23054                        : false;
23055            }
23056        }
23057
23058        @Override
23059        public List<PackageInfo> getOverlayPackages(int userId) {
23060            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23061            synchronized (mPackages) {
23062                for (PackageParser.Package p : mPackages.values()) {
23063                    if (p.mOverlayTarget != null) {
23064                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23065                        if (pkg != null) {
23066                            overlayPackages.add(pkg);
23067                        }
23068                    }
23069                }
23070            }
23071            return overlayPackages;
23072        }
23073
23074        @Override
23075        public List<String> getTargetPackageNames(int userId) {
23076            List<String> targetPackages = new ArrayList<>();
23077            synchronized (mPackages) {
23078                for (PackageParser.Package p : mPackages.values()) {
23079                    if (p.mOverlayTarget == null) {
23080                        targetPackages.add(p.packageName);
23081                    }
23082                }
23083            }
23084            return targetPackages;
23085        }
23086
23087        @Override
23088        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23089                @Nullable List<String> overlayPackageNames) {
23090            synchronized (mPackages) {
23091                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23092                    Slog.e(TAG, "failed to find package " + targetPackageName);
23093                    return false;
23094                }
23095
23096                ArrayList<String> paths = null;
23097                if (overlayPackageNames != null) {
23098                    final int N = overlayPackageNames.size();
23099                    paths = new ArrayList<>(N);
23100                    for (int i = 0; i < N; i++) {
23101                        final String packageName = overlayPackageNames.get(i);
23102                        final PackageParser.Package pkg = mPackages.get(packageName);
23103                        if (pkg == null) {
23104                            Slog.e(TAG, "failed to find package " + packageName);
23105                            return false;
23106                        }
23107                        paths.add(pkg.baseCodePath);
23108                    }
23109                }
23110
23111                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23112                    mEnabledOverlayPaths.get(userId);
23113                if (userSpecificOverlays == null) {
23114                    userSpecificOverlays = new ArrayMap<>();
23115                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23116                }
23117
23118                if (paths != null && paths.size() > 0) {
23119                    userSpecificOverlays.put(targetPackageName, paths);
23120                } else {
23121                    userSpecificOverlays.remove(targetPackageName);
23122                }
23123                return true;
23124            }
23125        }
23126
23127        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23128                int flags, int userId) {
23129            return resolveIntentInternal(
23130                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23131        }
23132    }
23133
23134    @Override
23135    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23136        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23137        synchronized (mPackages) {
23138            final long identity = Binder.clearCallingIdentity();
23139            try {
23140                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23141                        packageNames, userId);
23142            } finally {
23143                Binder.restoreCallingIdentity(identity);
23144            }
23145        }
23146    }
23147
23148    @Override
23149    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23150        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23151        synchronized (mPackages) {
23152            final long identity = Binder.clearCallingIdentity();
23153            try {
23154                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23155                        packageNames, userId);
23156            } finally {
23157                Binder.restoreCallingIdentity(identity);
23158            }
23159        }
23160    }
23161
23162    private static void enforceSystemOrPhoneCaller(String tag) {
23163        int callingUid = Binder.getCallingUid();
23164        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23165            throw new SecurityException(
23166                    "Cannot call " + tag + " from UID " + callingUid);
23167        }
23168    }
23169
23170    boolean isHistoricalPackageUsageAvailable() {
23171        return mPackageUsage.isHistoricalPackageUsageAvailable();
23172    }
23173
23174    /**
23175     * Return a <b>copy</b> of the collection of packages known to the package manager.
23176     * @return A copy of the values of mPackages.
23177     */
23178    Collection<PackageParser.Package> getPackages() {
23179        synchronized (mPackages) {
23180            return new ArrayList<>(mPackages.values());
23181        }
23182    }
23183
23184    /**
23185     * Logs process start information (including base APK hash) to the security log.
23186     * @hide
23187     */
23188    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23189            String apkFile, int pid) {
23190        if (!SecurityLog.isLoggingEnabled()) {
23191            return;
23192        }
23193        Bundle data = new Bundle();
23194        data.putLong("startTimestamp", System.currentTimeMillis());
23195        data.putString("processName", processName);
23196        data.putInt("uid", uid);
23197        data.putString("seinfo", seinfo);
23198        data.putString("apkFile", apkFile);
23199        data.putInt("pid", pid);
23200        Message msg = mProcessLoggingHandler.obtainMessage(
23201                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23202        msg.setData(data);
23203        mProcessLoggingHandler.sendMessage(msg);
23204    }
23205
23206    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23207        return mCompilerStats.getPackageStats(pkgName);
23208    }
23209
23210    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23211        return getOrCreateCompilerPackageStats(pkg.packageName);
23212    }
23213
23214    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23215        return mCompilerStats.getOrCreatePackageStats(pkgName);
23216    }
23217
23218    public void deleteCompilerPackageStats(String pkgName) {
23219        mCompilerStats.deletePackageStats(pkgName);
23220    }
23221
23222    @Override
23223    public int getInstallReason(String packageName, int userId) {
23224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23225                true /* requireFullPermission */, false /* checkShell */,
23226                "get install reason");
23227        synchronized (mPackages) {
23228            final PackageSetting ps = mSettings.mPackages.get(packageName);
23229            if (ps != null) {
23230                return ps.getInstallReason(userId);
23231            }
23232        }
23233        return PackageManager.INSTALL_REASON_UNKNOWN;
23234    }
23235
23236    @Override
23237    public boolean canRequestPackageInstalls(String packageName, int userId) {
23238        int callingUid = Binder.getCallingUid();
23239        int uid = getPackageUid(packageName, 0, userId);
23240        if (callingUid != uid && callingUid != Process.ROOT_UID
23241                && callingUid != Process.SYSTEM_UID) {
23242            throw new SecurityException(
23243                    "Caller uid " + callingUid + " does not own package " + packageName);
23244        }
23245        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23246        if (info == null) {
23247            return false;
23248        }
23249        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23250            throw new UnsupportedOperationException(
23251                    "Operation only supported on apps targeting Android O or higher");
23252        }
23253        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23254        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23255        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23256            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23257        }
23258        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23259            return false;
23260        }
23261        if (mExternalSourcesPolicy != null) {
23262            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23263            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23264                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23265            }
23266        }
23267        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23268    }
23269}
23270