PackageManagerService.java revision ecb34651be8b69de5aaedf9a9651d366e336d3a3
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Process.PACKAGE_INFO_GID;
79import static android.os.Process.SYSTEM_UID;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.app.ActivityManager;
105import android.app.ActivityManagerNative;
106import android.app.IActivityManager;
107import android.app.admin.DevicePolicyManagerInternal;
108import android.app.admin.IDevicePolicyManager;
109import android.app.admin.SecurityLog;
110import android.app.backup.IBackupManager;
111import android.content.BroadcastReceiver;
112import android.content.ComponentName;
113import android.content.Context;
114import android.content.IIntentReceiver;
115import android.content.Intent;
116import android.content.IntentFilter;
117import android.content.IntentSender;
118import android.content.IntentSender.SendIntentException;
119import android.content.ServiceConnection;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.AppsQueryHelper;
123import android.content.pm.ComponentInfo;
124import android.content.pm.EphemeralApplicationInfo;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.Process;
181import android.os.RemoteCallbackList;
182import android.os.RemoteException;
183import android.os.ResultReceiver;
184import android.os.SELinux;
185import android.os.ServiceManager;
186import android.os.SystemClock;
187import android.os.SystemProperties;
188import android.os.Trace;
189import android.os.UserHandle;
190import android.os.UserManager;
191import android.os.storage.IMountService;
192import android.os.storage.MountServiceInternal;
193import android.os.storage.StorageEventListener;
194import android.os.storage.StorageManager;
195import android.os.storage.VolumeInfo;
196import android.os.storage.VolumeRecord;
197import android.security.KeyStore;
198import android.security.SystemKeyStore;
199import android.system.ErrnoException;
200import android.system.Os;
201import android.text.TextUtils;
202import android.text.format.DateUtils;
203import android.util.ArrayMap;
204import android.util.ArraySet;
205import android.util.AtomicFile;
206import android.util.DisplayMetrics;
207import android.util.EventLog;
208import android.util.ExceptionUtils;
209import android.util.Log;
210import android.util.LogPrinter;
211import android.util.MathUtils;
212import android.util.PrintStreamPrinter;
213import android.util.Slog;
214import android.util.SparseArray;
215import android.util.SparseBooleanArray;
216import android.util.SparseIntArray;
217import android.util.Xml;
218import android.view.Display;
219
220import com.android.internal.R;
221import com.android.internal.annotations.GuardedBy;
222import com.android.internal.app.IMediaContainerService;
223import com.android.internal.app.ResolverActivity;
224import com.android.internal.content.NativeLibraryHelper;
225import com.android.internal.content.PackageHelper;
226import com.android.internal.os.IParcelFileDescriptorFactory;
227import com.android.internal.os.InstallerConnection.InstallerException;
228import com.android.internal.os.SomeArgs;
229import com.android.internal.os.Zygote;
230import com.android.internal.util.ArrayUtils;
231import com.android.internal.util.FastPrintWriter;
232import com.android.internal.util.FastXmlSerializer;
233import com.android.internal.util.IndentingPrintWriter;
234import com.android.internal.util.Preconditions;
235import com.android.internal.util.XmlUtils;
236import com.android.server.EventLogTags;
237import com.android.server.FgThread;
238import com.android.server.IntentResolver;
239import com.android.server.LocalServices;
240import com.android.server.ServiceThread;
241import com.android.server.SystemConfig;
242import com.android.server.Watchdog;
243import com.android.server.pm.PermissionsState.PermissionState;
244import com.android.server.pm.Settings.DatabaseVersion;
245import com.android.server.pm.Settings.VersionInfo;
246import com.android.server.storage.DeviceStorageMonitorInternal;
247
248import dalvik.system.DexFile;
249import dalvik.system.VMRuntime;
250
251import libcore.io.IoUtils;
252import libcore.util.EmptyArray;
253
254import org.xmlpull.v1.XmlPullParser;
255import org.xmlpull.v1.XmlPullParserException;
256import org.xmlpull.v1.XmlSerializer;
257
258import java.io.BufferedInputStream;
259import java.io.BufferedOutputStream;
260import java.io.BufferedReader;
261import java.io.ByteArrayInputStream;
262import java.io.ByteArrayOutputStream;
263import java.io.File;
264import java.io.FileDescriptor;
265import java.io.FileNotFoundException;
266import java.io.FileOutputStream;
267import java.io.FileReader;
268import java.io.FilenameFilter;
269import java.io.IOException;
270import java.io.InputStream;
271import java.io.PrintWriter;
272import java.nio.charset.StandardCharsets;
273import java.security.MessageDigest;
274import java.security.NoSuchAlgorithmException;
275import java.security.PublicKey;
276import java.security.cert.CertificateEncodingException;
277import java.security.cert.CertificateException;
278import java.text.SimpleDateFormat;
279import java.util.ArrayList;
280import java.util.Arrays;
281import java.util.Collection;
282import java.util.Collections;
283import java.util.Comparator;
284import java.util.Date;
285import java.util.HashSet;
286import java.util.Iterator;
287import java.util.List;
288import java.util.Map;
289import java.util.Objects;
290import java.util.Set;
291import java.util.concurrent.CountDownLatch;
292import java.util.concurrent.TimeUnit;
293import java.util.concurrent.atomic.AtomicBoolean;
294import java.util.concurrent.atomic.AtomicInteger;
295import java.util.concurrent.atomic.AtomicLong;
296
297/**
298 * Keep track of all those .apks everywhere.
299 *
300 * This is very central to the platform's security; please run the unit
301 * tests whenever making modifications here:
302 *
303runtest -c android.content.pm.PackageManagerTests frameworks-core
304 *
305 * {@hide}
306 */
307public class PackageManagerService extends IPackageManager.Stub {
308    static final String TAG = "PackageManager";
309    static final boolean DEBUG_SETTINGS = false;
310    static final boolean DEBUG_PREFERRED = false;
311    static final boolean DEBUG_UPGRADE = false;
312    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
313    private static final boolean DEBUG_BACKUP = false;
314    private static final boolean DEBUG_INSTALL = false;
315    private static final boolean DEBUG_REMOVE = false;
316    private static final boolean DEBUG_BROADCASTS = false;
317    private static final boolean DEBUG_SHOW_INFO = false;
318    private static final boolean DEBUG_PACKAGE_INFO = false;
319    private static final boolean DEBUG_INTENT_MATCHING = false;
320    private static final boolean DEBUG_PACKAGE_SCANNING = false;
321    private static final boolean DEBUG_VERIFY = false;
322
323    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
324    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
325    // user, but by default initialize to this.
326    static final boolean DEBUG_DEXOPT = false;
327
328    private static final boolean DEBUG_ABI_SELECTION = false;
329    private static final boolean DEBUG_EPHEMERAL = false;
330    private static final boolean DEBUG_TRIAGED_MISSING = false;
331    private static final boolean DEBUG_APP_DATA = false;
332
333    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
334
335    private static final boolean DISABLE_EPHEMERAL_APPS = true;
336
337    private static final int RADIO_UID = Process.PHONE_UID;
338    private static final int LOG_UID = Process.LOG_UID;
339    private static final int NFC_UID = Process.NFC_UID;
340    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
341    private static final int SHELL_UID = Process.SHELL_UID;
342
343    // Cap the size of permission trees that 3rd party apps can define
344    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
345
346    // Suffix used during package installation when copying/moving
347    // package apks to install directory.
348    private static final String INSTALL_PACKAGE_SUFFIX = "-";
349
350    static final int SCAN_NO_DEX = 1<<1;
351    static final int SCAN_FORCE_DEX = 1<<2;
352    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
353    static final int SCAN_NEW_INSTALL = 1<<4;
354    static final int SCAN_NO_PATHS = 1<<5;
355    static final int SCAN_UPDATE_TIME = 1<<6;
356    static final int SCAN_DEFER_DEX = 1<<7;
357    static final int SCAN_BOOTING = 1<<8;
358    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
359    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
360    static final int SCAN_REPLACING = 1<<11;
361    static final int SCAN_REQUIRE_KNOWN = 1<<12;
362    static final int SCAN_MOVE = 1<<13;
363    static final int SCAN_INITIAL = 1<<14;
364    static final int SCAN_CHECK_ONLY = 1<<15;
365    static final int SCAN_DONT_KILL_APP = 1<<17;
366
367    static final int REMOVE_CHATTY = 1<<16;
368
369    private static final int[] EMPTY_INT_ARRAY = new int[0];
370
371    /**
372     * Timeout (in milliseconds) after which the watchdog should declare that
373     * our handler thread is wedged.  The usual default for such things is one
374     * minute but we sometimes do very lengthy I/O operations on this thread,
375     * such as installing multi-gigabyte applications, so ours needs to be longer.
376     */
377    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
378
379    /**
380     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
381     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
382     * settings entry if available, otherwise we use the hardcoded default.  If it's been
383     * more than this long since the last fstrim, we force one during the boot sequence.
384     *
385     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
386     * one gets run at the next available charging+idle time.  This final mandatory
387     * no-fstrim check kicks in only of the other scheduling criteria is never met.
388     */
389    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
390
391    /**
392     * Whether verification is enabled by default.
393     */
394    private static final boolean DEFAULT_VERIFY_ENABLE = true;
395
396    /**
397     * The default maximum time to wait for the verification agent to return in
398     * milliseconds.
399     */
400    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
401
402    /**
403     * The default response for package verification timeout.
404     *
405     * This can be either PackageManager.VERIFICATION_ALLOW or
406     * PackageManager.VERIFICATION_REJECT.
407     */
408    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
409
410    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
411
412    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
413            DEFAULT_CONTAINER_PACKAGE,
414            "com.android.defcontainer.DefaultContainerService");
415
416    private static final String KILL_APP_REASON_GIDS_CHANGED =
417            "permission grant or revoke changed gids";
418
419    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
420            "permissions revoked";
421
422    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
423
424    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
425
426    /** Permission grant: not grant the permission. */
427    private static final int GRANT_DENIED = 1;
428
429    /** Permission grant: grant the permission as an install permission. */
430    private static final int GRANT_INSTALL = 2;
431
432    /** Permission grant: grant the permission as a runtime one. */
433    private static final int GRANT_RUNTIME = 3;
434
435    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
436    private static final int GRANT_UPGRADE = 4;
437
438    /** Canonical intent used to identify what counts as a "web browser" app */
439    private static final Intent sBrowserIntent;
440    static {
441        sBrowserIntent = new Intent();
442        sBrowserIntent.setAction(Intent.ACTION_VIEW);
443        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
444        sBrowserIntent.setData(Uri.parse("http:"));
445    }
446
447    // Compilation reasons.
448    public static final int REASON_FIRST_BOOT = 0;
449    public static final int REASON_BOOT = 1;
450    public static final int REASON_INSTALL = 2;
451    public static final int REASON_BACKGROUND_DEXOPT = 3;
452    public static final int REASON_AB_OTA = 4;
453    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
454    public static final int REASON_SHARED_APK = 6;
455    public static final int REASON_FORCED_DEXOPT = 7;
456
457    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
458
459    final ServiceThread mHandlerThread;
460
461    final PackageHandler mHandler;
462
463    private final ProcessLoggingHandler mProcessLoggingHandler;
464
465    /**
466     * Messages for {@link #mHandler} that need to wait for system ready before
467     * being dispatched.
468     */
469    private ArrayList<Message> mPostSystemReadyMessages;
470
471    final int mSdkVersion = Build.VERSION.SDK_INT;
472
473    final Context mContext;
474    final boolean mFactoryTest;
475    final boolean mOnlyCore;
476    final DisplayMetrics mMetrics;
477    final int mDefParseFlags;
478    final String[] mSeparateProcesses;
479    final boolean mIsUpgrade;
480    final boolean mIsPreNUpgrade;
481
482    /** The location for ASEC container files on internal storage. */
483    final String mAsecInternalPath;
484
485    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
486    // LOCK HELD.  Can be called with mInstallLock held.
487    @GuardedBy("mInstallLock")
488    final Installer mInstaller;
489
490    /** Directory where installed third-party apps stored */
491    final File mAppInstallDir;
492    final File mEphemeralInstallDir;
493
494    /**
495     * Directory to which applications installed internally have their
496     * 32 bit native libraries copied.
497     */
498    private File mAppLib32InstallDir;
499
500    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
501    // apps.
502    final File mDrmAppPrivateInstallDir;
503
504    // ----------------------------------------------------------------
505
506    // Lock for state used when installing and doing other long running
507    // operations.  Methods that must be called with this lock held have
508    // the suffix "LI".
509    final Object mInstallLock = new Object();
510
511    // ----------------------------------------------------------------
512
513    // Keys are String (package name), values are Package.  This also serves
514    // as the lock for the global state.  Methods that must be called with
515    // this lock held have the prefix "LP".
516    @GuardedBy("mPackages")
517    final ArrayMap<String, PackageParser.Package> mPackages =
518            new ArrayMap<String, PackageParser.Package>();
519
520    final ArrayMap<String, Set<String>> mKnownCodebase =
521            new ArrayMap<String, Set<String>>();
522
523    // Tracks available target package names -> overlay package paths.
524    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
525        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
526
527    /**
528     * Tracks new system packages [received in an OTA] that we expect to
529     * find updated user-installed versions. Keys are package name, values
530     * are package location.
531     */
532    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
533
534    /**
535     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
536     */
537    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
538    /**
539     * Whether or not system app permissions should be promoted from install to runtime.
540     */
541    boolean mPromoteSystemApps;
542
543    final Settings mSettings;
544    boolean mRestoredSettings;
545
546    // System configuration read by SystemConfig.
547    final int[] mGlobalGids;
548    final SparseArray<ArraySet<String>> mSystemPermissions;
549    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
550
551    // If mac_permissions.xml was found for seinfo labeling.
552    boolean mFoundPolicyFile;
553
554    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
555
556    public static final class SharedLibraryEntry {
557        public final String path;
558        public final String apk;
559
560        SharedLibraryEntry(String _path, String _apk) {
561            path = _path;
562            apk = _apk;
563        }
564    }
565
566    // Currently known shared libraries.
567    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
568            new ArrayMap<String, SharedLibraryEntry>();
569
570    // All available activities, for your resolving pleasure.
571    final ActivityIntentResolver mActivities =
572            new ActivityIntentResolver();
573
574    // All available receivers, for your resolving pleasure.
575    final ActivityIntentResolver mReceivers =
576            new ActivityIntentResolver();
577
578    // All available services, for your resolving pleasure.
579    final ServiceIntentResolver mServices = new ServiceIntentResolver();
580
581    // All available providers, for your resolving pleasure.
582    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
583
584    // Mapping from provider base names (first directory in content URI codePath)
585    // to the provider information.
586    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
587            new ArrayMap<String, PackageParser.Provider>();
588
589    // Mapping from instrumentation class names to info about them.
590    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
591            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
592
593    // Mapping from permission names to info about them.
594    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
595            new ArrayMap<String, PackageParser.PermissionGroup>();
596
597    // Packages whose data we have transfered into another package, thus
598    // should no longer exist.
599    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
600
601    // Broadcast actions that are only available to the system.
602    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
603
604    /** List of packages waiting for verification. */
605    final SparseArray<PackageVerificationState> mPendingVerification
606            = new SparseArray<PackageVerificationState>();
607
608    /** Set of packages associated with each app op permission. */
609    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
610
611    final PackageInstallerService mInstallerService;
612
613    private final PackageDexOptimizer mPackageDexOptimizer;
614
615    private AtomicInteger mNextMoveId = new AtomicInteger();
616    private final MoveCallbacks mMoveCallbacks;
617
618    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
619
620    // Cache of users who need badging.
621    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
622
623    /** Token for keys in mPendingVerification. */
624    private int mPendingVerificationToken = 0;
625
626    volatile boolean mSystemReady;
627    volatile boolean mSafeMode;
628    volatile boolean mHasSystemUidErrors;
629
630    ApplicationInfo mAndroidApplication;
631    final ActivityInfo mResolveActivity = new ActivityInfo();
632    final ResolveInfo mResolveInfo = new ResolveInfo();
633    ComponentName mResolveComponentName;
634    PackageParser.Package mPlatformPackage;
635    ComponentName mCustomResolverComponentName;
636
637    boolean mResolverReplaced = false;
638
639    private final @Nullable ComponentName mIntentFilterVerifierComponent;
640    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
641
642    private int mIntentFilterVerificationToken = 0;
643
644    /** Component that knows whether or not an ephemeral application exists */
645    final ComponentName mEphemeralResolverComponent;
646    /** The service connection to the ephemeral resolver */
647    final EphemeralResolverConnection mEphemeralResolverConnection;
648
649    /** Component used to install ephemeral applications */
650    final ComponentName mEphemeralInstallerComponent;
651    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
652    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
653
654    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
655            = new SparseArray<IntentFilterVerificationState>();
656
657    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
658            new DefaultPermissionGrantPolicy(this);
659
660    // List of packages names to keep cached, even if they are uninstalled for all users
661    private List<String> mKeepUninstalledPackages;
662
663    private static class IFVerificationParams {
664        PackageParser.Package pkg;
665        boolean replacing;
666        int userId;
667        int verifierUid;
668
669        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
670                int _userId, int _verifierUid) {
671            pkg = _pkg;
672            replacing = _replacing;
673            userId = _userId;
674            replacing = _replacing;
675            verifierUid = _verifierUid;
676        }
677    }
678
679    private interface IntentFilterVerifier<T extends IntentFilter> {
680        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
681                                               T filter, String packageName);
682        void startVerifications(int userId);
683        void receiveVerificationResponse(int verificationId);
684    }
685
686    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
687        private Context mContext;
688        private ComponentName mIntentFilterVerifierComponent;
689        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
690
691        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
692            mContext = context;
693            mIntentFilterVerifierComponent = verifierComponent;
694        }
695
696        private String getDefaultScheme() {
697            return IntentFilter.SCHEME_HTTPS;
698        }
699
700        @Override
701        public void startVerifications(int userId) {
702            // Launch verifications requests
703            int count = mCurrentIntentFilterVerifications.size();
704            for (int n=0; n<count; n++) {
705                int verificationId = mCurrentIntentFilterVerifications.get(n);
706                final IntentFilterVerificationState ivs =
707                        mIntentFilterVerificationStates.get(verificationId);
708
709                String packageName = ivs.getPackageName();
710
711                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
712                final int filterCount = filters.size();
713                ArraySet<String> domainsSet = new ArraySet<>();
714                for (int m=0; m<filterCount; m++) {
715                    PackageParser.ActivityIntentInfo filter = filters.get(m);
716                    domainsSet.addAll(filter.getHostsList());
717                }
718                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
719                synchronized (mPackages) {
720                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
721                            packageName, domainsList) != null) {
722                        scheduleWriteSettingsLocked();
723                    }
724                }
725                sendVerificationRequest(userId, verificationId, ivs);
726            }
727            mCurrentIntentFilterVerifications.clear();
728        }
729
730        private void sendVerificationRequest(int userId, int verificationId,
731                IntentFilterVerificationState ivs) {
732
733            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
734            verificationIntent.putExtra(
735                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
736                    verificationId);
737            verificationIntent.putExtra(
738                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
739                    getDefaultScheme());
740            verificationIntent.putExtra(
741                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
742                    ivs.getHostsString());
743            verificationIntent.putExtra(
744                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
745                    ivs.getPackageName());
746            verificationIntent.setComponent(mIntentFilterVerifierComponent);
747            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
748
749            UserHandle user = new UserHandle(userId);
750            mContext.sendBroadcastAsUser(verificationIntent, user);
751            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
752                    "Sending IntentFilter verification broadcast");
753        }
754
755        public void receiveVerificationResponse(int verificationId) {
756            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
757
758            final boolean verified = ivs.isVerified();
759
760            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
761            final int count = filters.size();
762            if (DEBUG_DOMAIN_VERIFICATION) {
763                Slog.i(TAG, "Received verification response " + verificationId
764                        + " for " + count + " filters, verified=" + verified);
765            }
766            for (int n=0; n<count; n++) {
767                PackageParser.ActivityIntentInfo filter = filters.get(n);
768                filter.setVerified(verified);
769
770                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
771                        + " verified with result:" + verified + " and hosts:"
772                        + ivs.getHostsString());
773            }
774
775            mIntentFilterVerificationStates.remove(verificationId);
776
777            final String packageName = ivs.getPackageName();
778            IntentFilterVerificationInfo ivi = null;
779
780            synchronized (mPackages) {
781                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
782            }
783            if (ivi == null) {
784                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
785                        + verificationId + " packageName:" + packageName);
786                return;
787            }
788            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
789                    "Updating IntentFilterVerificationInfo for package " + packageName
790                            +" verificationId:" + verificationId);
791
792            synchronized (mPackages) {
793                if (verified) {
794                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
795                } else {
796                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
797                }
798                scheduleWriteSettingsLocked();
799
800                final int userId = ivs.getUserId();
801                if (userId != UserHandle.USER_ALL) {
802                    final int userStatus =
803                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
804
805                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
806                    boolean needUpdate = false;
807
808                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
809                    // already been set by the User thru the Disambiguation dialog
810                    switch (userStatus) {
811                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
812                            if (verified) {
813                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
814                            } else {
815                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
816                            }
817                            needUpdate = true;
818                            break;
819
820                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
821                            if (verified) {
822                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
823                                needUpdate = true;
824                            }
825                            break;
826
827                        default:
828                            // Nothing to do
829                    }
830
831                    if (needUpdate) {
832                        mSettings.updateIntentFilterVerificationStatusLPw(
833                                packageName, updatedStatus, userId);
834                        scheduleWritePackageRestrictionsLocked(userId);
835                    }
836                }
837            }
838        }
839
840        @Override
841        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
842                    ActivityIntentInfo filter, String packageName) {
843            if (!hasValidDomains(filter)) {
844                return false;
845            }
846            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
847            if (ivs == null) {
848                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
849                        packageName);
850            }
851            if (DEBUG_DOMAIN_VERIFICATION) {
852                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
853            }
854            ivs.addFilter(filter);
855            return true;
856        }
857
858        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
859                int userId, int verificationId, String packageName) {
860            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
861                    verifierUid, userId, packageName);
862            ivs.setPendingState();
863            synchronized (mPackages) {
864                mIntentFilterVerificationStates.append(verificationId, ivs);
865                mCurrentIntentFilterVerifications.add(verificationId);
866            }
867            return ivs;
868        }
869    }
870
871    private static boolean hasValidDomains(ActivityIntentInfo filter) {
872        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
873                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
874                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
875    }
876
877    // Set of pending broadcasts for aggregating enable/disable of components.
878    static class PendingPackageBroadcasts {
879        // for each user id, a map of <package name -> components within that package>
880        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
881
882        public PendingPackageBroadcasts() {
883            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
884        }
885
886        public ArrayList<String> get(int userId, String packageName) {
887            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
888            return packages.get(packageName);
889        }
890
891        public void put(int userId, String packageName, ArrayList<String> components) {
892            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
893            packages.put(packageName, components);
894        }
895
896        public void remove(int userId, String packageName) {
897            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
898            if (packages != null) {
899                packages.remove(packageName);
900            }
901        }
902
903        public void remove(int userId) {
904            mUidMap.remove(userId);
905        }
906
907        public int userIdCount() {
908            return mUidMap.size();
909        }
910
911        public int userIdAt(int n) {
912            return mUidMap.keyAt(n);
913        }
914
915        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
916            return mUidMap.get(userId);
917        }
918
919        public int size() {
920            // total number of pending broadcast entries across all userIds
921            int num = 0;
922            for (int i = 0; i< mUidMap.size(); i++) {
923                num += mUidMap.valueAt(i).size();
924            }
925            return num;
926        }
927
928        public void clear() {
929            mUidMap.clear();
930        }
931
932        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
933            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
934            if (map == null) {
935                map = new ArrayMap<String, ArrayList<String>>();
936                mUidMap.put(userId, map);
937            }
938            return map;
939        }
940    }
941    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
942
943    // Service Connection to remote media container service to copy
944    // package uri's from external media onto secure containers
945    // or internal storage.
946    private IMediaContainerService mContainerService = null;
947
948    static final int SEND_PENDING_BROADCAST = 1;
949    static final int MCS_BOUND = 3;
950    static final int END_COPY = 4;
951    static final int INIT_COPY = 5;
952    static final int MCS_UNBIND = 6;
953    static final int START_CLEANING_PACKAGE = 7;
954    static final int FIND_INSTALL_LOC = 8;
955    static final int POST_INSTALL = 9;
956    static final int MCS_RECONNECT = 10;
957    static final int MCS_GIVE_UP = 11;
958    static final int UPDATED_MEDIA_STATUS = 12;
959    static final int WRITE_SETTINGS = 13;
960    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
961    static final int PACKAGE_VERIFIED = 15;
962    static final int CHECK_PENDING_VERIFICATION = 16;
963    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
964    static final int INTENT_FILTER_VERIFIED = 18;
965
966    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
967
968    // Delay time in millisecs
969    static final int BROADCAST_DELAY = 10 * 1000;
970
971    static UserManagerService sUserManager;
972
973    // Stores a list of users whose package restrictions file needs to be updated
974    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
975
976    final private DefaultContainerConnection mDefContainerConn =
977            new DefaultContainerConnection();
978    class DefaultContainerConnection implements ServiceConnection {
979        public void onServiceConnected(ComponentName name, IBinder service) {
980            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
981            IMediaContainerService imcs =
982                IMediaContainerService.Stub.asInterface(service);
983            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
984        }
985
986        public void onServiceDisconnected(ComponentName name) {
987            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
988        }
989    }
990
991    // Recordkeeping of restore-after-install operations that are currently in flight
992    // between the Package Manager and the Backup Manager
993    static class PostInstallData {
994        public InstallArgs args;
995        public PackageInstalledInfo res;
996
997        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
998            args = _a;
999            res = _r;
1000        }
1001    }
1002
1003    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1004    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1005
1006    // XML tags for backup/restore of various bits of state
1007    private static final String TAG_PREFERRED_BACKUP = "pa";
1008    private static final String TAG_DEFAULT_APPS = "da";
1009    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1010
1011    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1012    private static final String TAG_ALL_GRANTS = "rt-grants";
1013    private static final String TAG_GRANT = "grant";
1014    private static final String ATTR_PACKAGE_NAME = "pkg";
1015
1016    private static final String TAG_PERMISSION = "perm";
1017    private static final String ATTR_PERMISSION_NAME = "name";
1018    private static final String ATTR_IS_GRANTED = "g";
1019    private static final String ATTR_USER_SET = "set";
1020    private static final String ATTR_USER_FIXED = "fixed";
1021    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1022
1023    // System/policy permission grants are not backed up
1024    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1025            FLAG_PERMISSION_POLICY_FIXED
1026            | FLAG_PERMISSION_SYSTEM_FIXED
1027            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1028
1029    // And we back up these user-adjusted states
1030    private static final int USER_RUNTIME_GRANT_MASK =
1031            FLAG_PERMISSION_USER_SET
1032            | FLAG_PERMISSION_USER_FIXED
1033            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1034
1035    final @Nullable String mRequiredVerifierPackage;
1036    final @Nullable String mRequiredInstallerPackage;
1037
1038    private final PackageUsage mPackageUsage = new PackageUsage();
1039
1040    private class PackageUsage {
1041        private static final int WRITE_INTERVAL
1042            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1043
1044        private final Object mFileLock = new Object();
1045        private final AtomicLong mLastWritten = new AtomicLong(0);
1046        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1047
1048        private boolean mIsHistoricalPackageUsageAvailable = true;
1049
1050        boolean isHistoricalPackageUsageAvailable() {
1051            return mIsHistoricalPackageUsageAvailable;
1052        }
1053
1054        void write(boolean force) {
1055            if (force) {
1056                writeInternal();
1057                return;
1058            }
1059            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1060                && !DEBUG_DEXOPT) {
1061                return;
1062            }
1063            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1064                new Thread("PackageUsage_DiskWriter") {
1065                    @Override
1066                    public void run() {
1067                        try {
1068                            writeInternal();
1069                        } finally {
1070                            mBackgroundWriteRunning.set(false);
1071                        }
1072                    }
1073                }.start();
1074            }
1075        }
1076
1077        private void writeInternal() {
1078            synchronized (mPackages) {
1079                synchronized (mFileLock) {
1080                    AtomicFile file = getFile();
1081                    FileOutputStream f = null;
1082                    try {
1083                        f = file.startWrite();
1084                        BufferedOutputStream out = new BufferedOutputStream(f);
1085                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1086                        StringBuilder sb = new StringBuilder();
1087                        for (PackageParser.Package pkg : mPackages.values()) {
1088                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1089                                continue;
1090                            }
1091                            sb.setLength(0);
1092                            sb.append(pkg.packageName);
1093                            sb.append(' ');
1094                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1095                            sb.append('\n');
1096                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1097                        }
1098                        out.flush();
1099                        file.finishWrite(f);
1100                    } catch (IOException e) {
1101                        if (f != null) {
1102                            file.failWrite(f);
1103                        }
1104                        Log.e(TAG, "Failed to write package usage times", e);
1105                    }
1106                }
1107            }
1108            mLastWritten.set(SystemClock.elapsedRealtime());
1109        }
1110
1111        void readLP() {
1112            synchronized (mFileLock) {
1113                AtomicFile file = getFile();
1114                BufferedInputStream in = null;
1115                try {
1116                    in = new BufferedInputStream(file.openRead());
1117                    StringBuffer sb = new StringBuffer();
1118                    while (true) {
1119                        String packageName = readToken(in, sb, ' ');
1120                        if (packageName == null) {
1121                            break;
1122                        }
1123                        String timeInMillisString = readToken(in, sb, '\n');
1124                        if (timeInMillisString == null) {
1125                            throw new IOException("Failed to find last usage time for package "
1126                                                  + packageName);
1127                        }
1128                        PackageParser.Package pkg = mPackages.get(packageName);
1129                        if (pkg == null) {
1130                            continue;
1131                        }
1132                        long timeInMillis;
1133                        try {
1134                            timeInMillis = Long.parseLong(timeInMillisString);
1135                        } catch (NumberFormatException e) {
1136                            throw new IOException("Failed to parse " + timeInMillisString
1137                                                  + " as a long.", e);
1138                        }
1139                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1140                    }
1141                } catch (FileNotFoundException expected) {
1142                    mIsHistoricalPackageUsageAvailable = false;
1143                } catch (IOException e) {
1144                    Log.w(TAG, "Failed to read package usage times", e);
1145                } finally {
1146                    IoUtils.closeQuietly(in);
1147                }
1148            }
1149            mLastWritten.set(SystemClock.elapsedRealtime());
1150        }
1151
1152        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1153                throws IOException {
1154            sb.setLength(0);
1155            while (true) {
1156                int ch = in.read();
1157                if (ch == -1) {
1158                    if (sb.length() == 0) {
1159                        return null;
1160                    }
1161                    throw new IOException("Unexpected EOF");
1162                }
1163                if (ch == endOfToken) {
1164                    return sb.toString();
1165                }
1166                sb.append((char)ch);
1167            }
1168        }
1169
1170        private AtomicFile getFile() {
1171            File dataDir = Environment.getDataDirectory();
1172            File systemDir = new File(dataDir, "system");
1173            File fname = new File(systemDir, "package-usage.list");
1174            return new AtomicFile(fname);
1175        }
1176    }
1177
1178    class PackageHandler extends Handler {
1179        private boolean mBound = false;
1180        final ArrayList<HandlerParams> mPendingInstalls =
1181            new ArrayList<HandlerParams>();
1182
1183        private boolean connectToService() {
1184            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1185                    " DefaultContainerService");
1186            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1187            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1188            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1189                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1190                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1191                mBound = true;
1192                return true;
1193            }
1194            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1195            return false;
1196        }
1197
1198        private void disconnectService() {
1199            mContainerService = null;
1200            mBound = false;
1201            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1202            mContext.unbindService(mDefContainerConn);
1203            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1204        }
1205
1206        PackageHandler(Looper looper) {
1207            super(looper);
1208        }
1209
1210        public void handleMessage(Message msg) {
1211            try {
1212                doHandleMessage(msg);
1213            } finally {
1214                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1215            }
1216        }
1217
1218        void doHandleMessage(Message msg) {
1219            switch (msg.what) {
1220                case INIT_COPY: {
1221                    HandlerParams params = (HandlerParams) msg.obj;
1222                    int idx = mPendingInstalls.size();
1223                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1224                    // If a bind was already initiated we dont really
1225                    // need to do anything. The pending install
1226                    // will be processed later on.
1227                    if (!mBound) {
1228                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1229                                System.identityHashCode(mHandler));
1230                        // If this is the only one pending we might
1231                        // have to bind to the service again.
1232                        if (!connectToService()) {
1233                            Slog.e(TAG, "Failed to bind to media container service");
1234                            params.serviceError();
1235                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1236                                    System.identityHashCode(mHandler));
1237                            if (params.traceMethod != null) {
1238                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1239                                        params.traceCookie);
1240                            }
1241                            return;
1242                        } else {
1243                            // Once we bind to the service, the first
1244                            // pending request will be processed.
1245                            mPendingInstalls.add(idx, params);
1246                        }
1247                    } else {
1248                        mPendingInstalls.add(idx, params);
1249                        // Already bound to the service. Just make
1250                        // sure we trigger off processing the first request.
1251                        if (idx == 0) {
1252                            mHandler.sendEmptyMessage(MCS_BOUND);
1253                        }
1254                    }
1255                    break;
1256                }
1257                case MCS_BOUND: {
1258                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1259                    if (msg.obj != null) {
1260                        mContainerService = (IMediaContainerService) msg.obj;
1261                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1262                                System.identityHashCode(mHandler));
1263                    }
1264                    if (mContainerService == null) {
1265                        if (!mBound) {
1266                            // Something seriously wrong since we are not bound and we are not
1267                            // waiting for connection. Bail out.
1268                            Slog.e(TAG, "Cannot bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                                if (params.traceMethod != null) {
1275                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1276                                            params.traceMethod, params.traceCookie);
1277                                }
1278                                return;
1279                            }
1280                            mPendingInstalls.clear();
1281                        } else {
1282                            Slog.w(TAG, "Waiting to connect to media container service");
1283                        }
1284                    } else if (mPendingInstalls.size() > 0) {
1285                        HandlerParams params = mPendingInstalls.get(0);
1286                        if (params != null) {
1287                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1288                                    System.identityHashCode(params));
1289                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1290                            if (params.startCopy()) {
1291                                // We are done...  look for more work or to
1292                                // go idle.
1293                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1294                                        "Checking for more work or unbind...");
1295                                // Delete pending install
1296                                if (mPendingInstalls.size() > 0) {
1297                                    mPendingInstalls.remove(0);
1298                                }
1299                                if (mPendingInstalls.size() == 0) {
1300                                    if (mBound) {
1301                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1302                                                "Posting delayed MCS_UNBIND");
1303                                        removeMessages(MCS_UNBIND);
1304                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1305                                        // Unbind after a little delay, to avoid
1306                                        // continual thrashing.
1307                                        sendMessageDelayed(ubmsg, 10000);
1308                                    }
1309                                } else {
1310                                    // There are more pending requests in queue.
1311                                    // Just post MCS_BOUND message to trigger processing
1312                                    // of next pending install.
1313                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1314                                            "Posting MCS_BOUND for next work");
1315                                    mHandler.sendEmptyMessage(MCS_BOUND);
1316                                }
1317                            }
1318                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1319                        }
1320                    } else {
1321                        // Should never happen ideally.
1322                        Slog.w(TAG, "Empty queue");
1323                    }
1324                    break;
1325                }
1326                case MCS_RECONNECT: {
1327                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1328                    if (mPendingInstalls.size() > 0) {
1329                        if (mBound) {
1330                            disconnectService();
1331                        }
1332                        if (!connectToService()) {
1333                            Slog.e(TAG, "Failed to bind to media container service");
1334                            for (HandlerParams params : mPendingInstalls) {
1335                                // Indicate service bind error
1336                                params.serviceError();
1337                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1338                                        System.identityHashCode(params));
1339                            }
1340                            mPendingInstalls.clear();
1341                        }
1342                    }
1343                    break;
1344                }
1345                case MCS_UNBIND: {
1346                    // If there is no actual work left, then time to unbind.
1347                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1348
1349                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1350                        if (mBound) {
1351                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1352
1353                            disconnectService();
1354                        }
1355                    } else if (mPendingInstalls.size() > 0) {
1356                        // There are more pending requests in queue.
1357                        // Just post MCS_BOUND message to trigger processing
1358                        // of next pending install.
1359                        mHandler.sendEmptyMessage(MCS_BOUND);
1360                    }
1361
1362                    break;
1363                }
1364                case MCS_GIVE_UP: {
1365                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1366                    HandlerParams params = mPendingInstalls.remove(0);
1367                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1368                            System.identityHashCode(params));
1369                    break;
1370                }
1371                case SEND_PENDING_BROADCAST: {
1372                    String packages[];
1373                    ArrayList<String> components[];
1374                    int size = 0;
1375                    int uids[];
1376                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1377                    synchronized (mPackages) {
1378                        if (mPendingBroadcasts == null) {
1379                            return;
1380                        }
1381                        size = mPendingBroadcasts.size();
1382                        if (size <= 0) {
1383                            // Nothing to be done. Just return
1384                            return;
1385                        }
1386                        packages = new String[size];
1387                        components = new ArrayList[size];
1388                        uids = new int[size];
1389                        int i = 0;  // filling out the above arrays
1390
1391                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1392                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1393                            Iterator<Map.Entry<String, ArrayList<String>>> it
1394                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1395                                            .entrySet().iterator();
1396                            while (it.hasNext() && i < size) {
1397                                Map.Entry<String, ArrayList<String>> ent = it.next();
1398                                packages[i] = ent.getKey();
1399                                components[i] = ent.getValue();
1400                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1401                                uids[i] = (ps != null)
1402                                        ? UserHandle.getUid(packageUserId, ps.appId)
1403                                        : -1;
1404                                i++;
1405                            }
1406                        }
1407                        size = i;
1408                        mPendingBroadcasts.clear();
1409                    }
1410                    // Send broadcasts
1411                    for (int i = 0; i < size; i++) {
1412                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1413                    }
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                    break;
1416                }
1417                case START_CLEANING_PACKAGE: {
1418                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1419                    final String packageName = (String)msg.obj;
1420                    final int userId = msg.arg1;
1421                    final boolean andCode = msg.arg2 != 0;
1422                    synchronized (mPackages) {
1423                        if (userId == UserHandle.USER_ALL) {
1424                            int[] users = sUserManager.getUserIds();
1425                            for (int user : users) {
1426                                mSettings.addPackageToCleanLPw(
1427                                        new PackageCleanItem(user, packageName, andCode));
1428                            }
1429                        } else {
1430                            mSettings.addPackageToCleanLPw(
1431                                    new PackageCleanItem(userId, packageName, andCode));
1432                        }
1433                    }
1434                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435                    startCleaningPackages();
1436                } break;
1437                case POST_INSTALL: {
1438                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1439
1440                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1441                    mRunningInstalls.delete(msg.arg1);
1442
1443                    if (data != null) {
1444                        InstallArgs args = data.args;
1445                        PackageInstalledInfo parentRes = data.res;
1446
1447                        final boolean grantPermissions = (args.installFlags
1448                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1449                        final boolean killApp = (args.installFlags
1450                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1451                        final String[] grantedPermissions = args.installGrantPermissions;
1452
1453                        // Handle the parent package
1454                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1455                                grantedPermissions, args.observer);
1456
1457                        // Handle the child packages
1458                        final int childCount = (parentRes.addedChildPackages != null)
1459                                ? parentRes.addedChildPackages.size() : 0;
1460                        for (int i = 0; i < childCount; i++) {
1461                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1462                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1463                                    grantedPermissions, args.observer);
1464                        }
1465
1466                        // Log tracing if needed
1467                        if (args.traceMethod != null) {
1468                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1469                                    args.traceCookie);
1470                        }
1471                    } else {
1472                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1473                    }
1474
1475                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1476                } break;
1477                case UPDATED_MEDIA_STATUS: {
1478                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1479                    boolean reportStatus = msg.arg1 == 1;
1480                    boolean doGc = msg.arg2 == 1;
1481                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1482                    if (doGc) {
1483                        // Force a gc to clear up stale containers.
1484                        Runtime.getRuntime().gc();
1485                    }
1486                    if (msg.obj != null) {
1487                        @SuppressWarnings("unchecked")
1488                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1489                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1490                        // Unload containers
1491                        unloadAllContainers(args);
1492                    }
1493                    if (reportStatus) {
1494                        try {
1495                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1496                            PackageHelper.getMountService().finishMediaUpdate();
1497                        } catch (RemoteException e) {
1498                            Log.e(TAG, "MountService not running?");
1499                        }
1500                    }
1501                } break;
1502                case WRITE_SETTINGS: {
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1504                    synchronized (mPackages) {
1505                        removeMessages(WRITE_SETTINGS);
1506                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1507                        mSettings.writeLPr();
1508                        mDirtyUsers.clear();
1509                    }
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1511                } break;
1512                case WRITE_PACKAGE_RESTRICTIONS: {
1513                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1514                    synchronized (mPackages) {
1515                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1516                        for (int userId : mDirtyUsers) {
1517                            mSettings.writePackageRestrictionsLPr(userId);
1518                        }
1519                        mDirtyUsers.clear();
1520                    }
1521                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1522                } break;
1523                case CHECK_PENDING_VERIFICATION: {
1524                    final int verificationId = msg.arg1;
1525                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1526
1527                    if ((state != null) && !state.timeoutExtended()) {
1528                        final InstallArgs args = state.getInstallArgs();
1529                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1530
1531                        Slog.i(TAG, "Verification timed out for " + originUri);
1532                        mPendingVerification.remove(verificationId);
1533
1534                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1535
1536                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1537                            Slog.i(TAG, "Continuing with installation of " + originUri);
1538                            state.setVerifierResponse(Binder.getCallingUid(),
1539                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1540                            broadcastPackageVerified(verificationId, originUri,
1541                                    PackageManager.VERIFICATION_ALLOW,
1542                                    state.getInstallArgs().getUser());
1543                            try {
1544                                ret = args.copyApk(mContainerService, true);
1545                            } catch (RemoteException e) {
1546                                Slog.e(TAG, "Could not contact the ContainerService");
1547                            }
1548                        } else {
1549                            broadcastPackageVerified(verificationId, originUri,
1550                                    PackageManager.VERIFICATION_REJECT,
1551                                    state.getInstallArgs().getUser());
1552                        }
1553
1554                        Trace.asyncTraceEnd(
1555                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1556
1557                        processPendingInstall(args, ret);
1558                        mHandler.sendEmptyMessage(MCS_UNBIND);
1559                    }
1560                    break;
1561                }
1562                case PACKAGE_VERIFIED: {
1563                    final int verificationId = msg.arg1;
1564
1565                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1566                    if (state == null) {
1567                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1568                        break;
1569                    }
1570
1571                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1572
1573                    state.setVerifierResponse(response.callerUid, response.code);
1574
1575                    if (state.isVerificationComplete()) {
1576                        mPendingVerification.remove(verificationId);
1577
1578                        final InstallArgs args = state.getInstallArgs();
1579                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1580
1581                        int ret;
1582                        if (state.isInstallAllowed()) {
1583                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1584                            broadcastPackageVerified(verificationId, originUri,
1585                                    response.code, state.getInstallArgs().getUser());
1586                            try {
1587                                ret = args.copyApk(mContainerService, true);
1588                            } catch (RemoteException e) {
1589                                Slog.e(TAG, "Could not contact the ContainerService");
1590                            }
1591                        } else {
1592                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1593                        }
1594
1595                        Trace.asyncTraceEnd(
1596                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1597
1598                        processPendingInstall(args, ret);
1599                        mHandler.sendEmptyMessage(MCS_UNBIND);
1600                    }
1601
1602                    break;
1603                }
1604                case START_INTENT_FILTER_VERIFICATIONS: {
1605                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1606                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1607                            params.replacing, params.pkg);
1608                    break;
1609                }
1610                case INTENT_FILTER_VERIFIED: {
1611                    final int verificationId = msg.arg1;
1612
1613                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1614                            verificationId);
1615                    if (state == null) {
1616                        Slog.w(TAG, "Invalid IntentFilter verification token "
1617                                + verificationId + " received");
1618                        break;
1619                    }
1620
1621                    final int userId = state.getUserId();
1622
1623                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1624                            "Processing IntentFilter verification with token:"
1625                            + verificationId + " and userId:" + userId);
1626
1627                    final IntentFilterVerificationResponse response =
1628                            (IntentFilterVerificationResponse) msg.obj;
1629
1630                    state.setVerifierResponse(response.callerUid, response.code);
1631
1632                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1633                            "IntentFilter verification with token:" + verificationId
1634                            + " and userId:" + userId
1635                            + " is settings verifier response with response code:"
1636                            + response.code);
1637
1638                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1639                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1640                                + response.getFailedDomainsString());
1641                    }
1642
1643                    if (state.isVerificationComplete()) {
1644                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1645                    } else {
1646                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1647                                "IntentFilter verification with token:" + verificationId
1648                                + " was not said to be complete");
1649                    }
1650
1651                    break;
1652                }
1653            }
1654        }
1655    }
1656
1657    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1658            boolean killApp, String[] grantedPermissions,
1659            IPackageInstallObserver2 installObserver) {
1660        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1661            // Send the removed broadcasts
1662            if (res.removedInfo != null) {
1663                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1664            }
1665
1666            // Now that we successfully installed the package, grant runtime
1667            // permissions if requested before broadcasting the install.
1668            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1669                    >= Build.VERSION_CODES.M) {
1670                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1671            }
1672
1673            final boolean update = res.removedInfo != null
1674                    && res.removedInfo.removedPackage != null;
1675
1676            // If this is the first time we have child packages for a disabled privileged
1677            // app that had no children, we grant requested runtime permissions to the new
1678            // children if the parent on the system image had them already granted.
1679            if (res.pkg.parentPackage != null) {
1680                synchronized (mPackages) {
1681                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1682                }
1683            }
1684
1685            synchronized (mPackages) {
1686                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1687            }
1688
1689            final String packageName = res.pkg.applicationInfo.packageName;
1690            Bundle extras = new Bundle(1);
1691            extras.putInt(Intent.EXTRA_UID, res.uid);
1692
1693            // Determine the set of users who are adding this package for
1694            // the first time vs. those who are seeing an update.
1695            int[] firstUsers = EMPTY_INT_ARRAY;
1696            int[] updateUsers = EMPTY_INT_ARRAY;
1697            if (res.origUsers == null || res.origUsers.length == 0) {
1698                firstUsers = res.newUsers;
1699            } else {
1700                for (int newUser : res.newUsers) {
1701                    boolean isNew = true;
1702                    for (int origUser : res.origUsers) {
1703                        if (origUser == newUser) {
1704                            isNew = false;
1705                            break;
1706                        }
1707                    }
1708                    if (isNew) {
1709                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1710                    } else {
1711                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1712                    }
1713                }
1714            }
1715
1716            // Send installed broadcasts if the install/update is not ephemeral
1717            if (!isEphemeral(res.pkg)) {
1718                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1719
1720                // Send added for users that see the package for the first time
1721                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1722                        extras, 0 /*flags*/, null /*targetPackage*/,
1723                        null /*finishedReceiver*/, firstUsers);
1724
1725                // Send added for users that don't see the package for the first time
1726                if (update) {
1727                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1728                }
1729                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1730                        extras, 0 /*flags*/, null /*targetPackage*/,
1731                        null /*finishedReceiver*/, updateUsers);
1732
1733                // Send replaced for users that don't see the package for the first time
1734                if (update) {
1735                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1736                            packageName, extras, 0 /*flags*/,
1737                            null /*targetPackage*/, null /*finishedReceiver*/,
1738                            updateUsers);
1739                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1740                            null /*package*/, null /*extras*/, 0 /*flags*/,
1741                            packageName /*targetPackage*/,
1742                            null /*finishedReceiver*/, updateUsers);
1743                }
1744
1745                // Send broadcast package appeared if forward locked/external for all users
1746                // treat asec-hosted packages like removable media on upgrade
1747                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1748                    if (DEBUG_INSTALL) {
1749                        Slog.i(TAG, "upgrading pkg " + res.pkg
1750                                + " is ASEC-hosted -> AVAILABLE");
1751                    }
1752                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1753                    ArrayList<String> pkgList = new ArrayList<>(1);
1754                    pkgList.add(packageName);
1755                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1756                }
1757            }
1758
1759            // Work that needs to happen on first install within each user
1760            if (firstUsers != null && firstUsers.length > 0) {
1761                synchronized (mPackages) {
1762                    for (int userId : firstUsers) {
1763                        // If this app is a browser and it's newly-installed for some
1764                        // users, clear any default-browser state in those users. The
1765                        // app's nature doesn't depend on the user, so we can just check
1766                        // its browser nature in any user and generalize.
1767                        if (packageIsBrowser(packageName, userId)) {
1768                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1769                        }
1770
1771                        // We may also need to apply pending (restored) runtime
1772                        // permission grants within these users.
1773                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1774                    }
1775                }
1776            }
1777
1778            // Log current value of "unknown sources" setting
1779            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1780                    getUnknownSourcesSettings());
1781
1782            // Force a gc to clear up things
1783            Runtime.getRuntime().gc();
1784
1785            // Remove the replaced package's older resources safely now
1786            // We delete after a gc for applications  on sdcard.
1787            if (res.removedInfo != null && res.removedInfo.args != null) {
1788                synchronized (mInstallLock) {
1789                    res.removedInfo.args.doPostDeleteLI(true);
1790                }
1791            }
1792        }
1793
1794        // If someone is watching installs - notify them
1795        if (installObserver != null) {
1796            try {
1797                Bundle extras = extrasForInstallResult(res);
1798                installObserver.onPackageInstalled(res.name, res.returnCode,
1799                        res.returnMsg, extras);
1800            } catch (RemoteException e) {
1801                Slog.i(TAG, "Observer no longer exists.");
1802            }
1803        }
1804    }
1805
1806    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1807            PackageParser.Package pkg) {
1808        if (pkg.parentPackage == null) {
1809            return;
1810        }
1811        if (pkg.requestedPermissions == null) {
1812            return;
1813        }
1814        final PackageSetting disabledSysParentPs = mSettings
1815                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1816        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1817                || !disabledSysParentPs.isPrivileged()
1818                || (disabledSysParentPs.childPackageNames != null
1819                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1820            return;
1821        }
1822        final int[] allUserIds = sUserManager.getUserIds();
1823        final int permCount = pkg.requestedPermissions.size();
1824        for (int i = 0; i < permCount; i++) {
1825            String permission = pkg.requestedPermissions.get(i);
1826            BasePermission bp = mSettings.mPermissions.get(permission);
1827            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1828                continue;
1829            }
1830            for (int userId : allUserIds) {
1831                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1832                        permission, userId)) {
1833                    grantRuntimePermission(pkg.packageName, permission, userId);
1834                }
1835            }
1836        }
1837    }
1838
1839    private StorageEventListener mStorageListener = new StorageEventListener() {
1840        @Override
1841        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1842            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1843                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1844                    final String volumeUuid = vol.getFsUuid();
1845
1846                    // Clean up any users or apps that were removed or recreated
1847                    // while this volume was missing
1848                    reconcileUsers(volumeUuid);
1849                    reconcileApps(volumeUuid);
1850
1851                    // Clean up any install sessions that expired or were
1852                    // cancelled while this volume was missing
1853                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1854
1855                    loadPrivatePackages(vol);
1856
1857                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1858                    unloadPrivatePackages(vol);
1859                }
1860            }
1861
1862            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1863                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1864                    updateExternalMediaStatus(true, false);
1865                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1866                    updateExternalMediaStatus(false, false);
1867                }
1868            }
1869        }
1870
1871        @Override
1872        public void onVolumeForgotten(String fsUuid) {
1873            if (TextUtils.isEmpty(fsUuid)) {
1874                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1875                return;
1876            }
1877
1878            // Remove any apps installed on the forgotten volume
1879            synchronized (mPackages) {
1880                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1881                for (PackageSetting ps : packages) {
1882                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1883                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1884                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1885                }
1886
1887                mSettings.onVolumeForgotten(fsUuid);
1888                mSettings.writeLPr();
1889            }
1890        }
1891    };
1892
1893    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1894            String[] grantedPermissions) {
1895        for (int userId : userIds) {
1896            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1897        }
1898
1899        // We could have touched GID membership, so flush out packages.list
1900        synchronized (mPackages) {
1901            mSettings.writePackageListLPr();
1902        }
1903    }
1904
1905    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1906            String[] grantedPermissions) {
1907        SettingBase sb = (SettingBase) pkg.mExtras;
1908        if (sb == null) {
1909            return;
1910        }
1911
1912        PermissionsState permissionsState = sb.getPermissionsState();
1913
1914        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1915                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1916
1917        synchronized (mPackages) {
1918            for (String permission : pkg.requestedPermissions) {
1919                BasePermission bp = mSettings.mPermissions.get(permission);
1920                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1921                        && (grantedPermissions == null
1922                               || ArrayUtils.contains(grantedPermissions, permission))) {
1923                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1924                    // Installer cannot change immutable permissions.
1925                    if ((flags & immutableFlags) == 0) {
1926                        grantRuntimePermission(pkg.packageName, permission, userId);
1927                    }
1928                }
1929            }
1930        }
1931    }
1932
1933    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1934        Bundle extras = null;
1935        switch (res.returnCode) {
1936            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1937                extras = new Bundle();
1938                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1939                        res.origPermission);
1940                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1941                        res.origPackage);
1942                break;
1943            }
1944            case PackageManager.INSTALL_SUCCEEDED: {
1945                extras = new Bundle();
1946                extras.putBoolean(Intent.EXTRA_REPLACING,
1947                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1948                break;
1949            }
1950        }
1951        return extras;
1952    }
1953
1954    void scheduleWriteSettingsLocked() {
1955        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1956            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1957        }
1958    }
1959
1960    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1961        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1962        scheduleWritePackageRestrictionsLocked(userId);
1963    }
1964
1965    void scheduleWritePackageRestrictionsLocked(int userId) {
1966        final int[] userIds = (userId == UserHandle.USER_ALL)
1967                ? sUserManager.getUserIds() : new int[]{userId};
1968        for (int nextUserId : userIds) {
1969            if (!sUserManager.exists(nextUserId)) return;
1970            mDirtyUsers.add(nextUserId);
1971            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1972                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1973            }
1974        }
1975    }
1976
1977    public static PackageManagerService main(Context context, Installer installer,
1978            boolean factoryTest, boolean onlyCore) {
1979        // Self-check for initial settings.
1980        PackageManagerServiceCompilerMapping.checkProperties();
1981
1982        PackageManagerService m = new PackageManagerService(context, installer,
1983                factoryTest, onlyCore);
1984        m.enableSystemUserPackages();
1985        ServiceManager.addService("package", m);
1986        return m;
1987    }
1988
1989    private void enableSystemUserPackages() {
1990        if (!UserManager.isSplitSystemUser()) {
1991            return;
1992        }
1993        // For system user, enable apps based on the following conditions:
1994        // - app is whitelisted or belong to one of these groups:
1995        //   -- system app which has no launcher icons
1996        //   -- system app which has INTERACT_ACROSS_USERS permission
1997        //   -- system IME app
1998        // - app is not in the blacklist
1999        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2000        Set<String> enableApps = new ArraySet<>();
2001        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2002                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2003                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2004        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2005        enableApps.addAll(wlApps);
2006        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2007                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2008        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2009        enableApps.removeAll(blApps);
2010        Log.i(TAG, "Applications installed for system user: " + enableApps);
2011        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2012                UserHandle.SYSTEM);
2013        final int allAppsSize = allAps.size();
2014        synchronized (mPackages) {
2015            for (int i = 0; i < allAppsSize; i++) {
2016                String pName = allAps.get(i);
2017                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2018                // Should not happen, but we shouldn't be failing if it does
2019                if (pkgSetting == null) {
2020                    continue;
2021                }
2022                boolean install = enableApps.contains(pName);
2023                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2024                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2025                            + " for system user");
2026                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2027                }
2028            }
2029        }
2030    }
2031
2032    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2033        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2034                Context.DISPLAY_SERVICE);
2035        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2036    }
2037
2038    public PackageManagerService(Context context, Installer installer,
2039            boolean factoryTest, boolean onlyCore) {
2040        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2041                SystemClock.uptimeMillis());
2042
2043        if (mSdkVersion <= 0) {
2044            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2045        }
2046
2047        mContext = context;
2048        mFactoryTest = factoryTest;
2049        mOnlyCore = onlyCore;
2050        mMetrics = new DisplayMetrics();
2051        mSettings = new Settings(mPackages);
2052        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2053                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2054        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2055                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2056        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2057                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2058        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2059                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2060        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2061                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2062        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2063                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2064
2065        String separateProcesses = SystemProperties.get("debug.separate_processes");
2066        if (separateProcesses != null && separateProcesses.length() > 0) {
2067            if ("*".equals(separateProcesses)) {
2068                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2069                mSeparateProcesses = null;
2070                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2071            } else {
2072                mDefParseFlags = 0;
2073                mSeparateProcesses = separateProcesses.split(",");
2074                Slog.w(TAG, "Running with debug.separate_processes: "
2075                        + separateProcesses);
2076            }
2077        } else {
2078            mDefParseFlags = 0;
2079            mSeparateProcesses = null;
2080        }
2081
2082        mInstaller = installer;
2083        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2084                "*dexopt*");
2085        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2086
2087        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2088                FgThread.get().getLooper());
2089
2090        getDefaultDisplayMetrics(context, mMetrics);
2091
2092        SystemConfig systemConfig = SystemConfig.getInstance();
2093        mGlobalGids = systemConfig.getGlobalGids();
2094        mSystemPermissions = systemConfig.getSystemPermissions();
2095        mAvailableFeatures = systemConfig.getAvailableFeatures();
2096
2097        synchronized (mInstallLock) {
2098        // writer
2099        synchronized (mPackages) {
2100            mHandlerThread = new ServiceThread(TAG,
2101                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2102            mHandlerThread.start();
2103            mHandler = new PackageHandler(mHandlerThread.getLooper());
2104            mProcessLoggingHandler = new ProcessLoggingHandler();
2105            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2106
2107            File dataDir = Environment.getDataDirectory();
2108            mAppInstallDir = new File(dataDir, "app");
2109            mAppLib32InstallDir = new File(dataDir, "app-lib");
2110            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2111            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2112            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2113
2114            sUserManager = new UserManagerService(context, this, mPackages);
2115
2116            // Propagate permission configuration in to package manager.
2117            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2118                    = systemConfig.getPermissions();
2119            for (int i=0; i<permConfig.size(); i++) {
2120                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2121                BasePermission bp = mSettings.mPermissions.get(perm.name);
2122                if (bp == null) {
2123                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2124                    mSettings.mPermissions.put(perm.name, bp);
2125                }
2126                if (perm.gids != null) {
2127                    bp.setGids(perm.gids, perm.perUser);
2128                }
2129            }
2130
2131            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2132            for (int i=0; i<libConfig.size(); i++) {
2133                mSharedLibraries.put(libConfig.keyAt(i),
2134                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2135            }
2136
2137            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2138
2139            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2140
2141            String customResolverActivity = Resources.getSystem().getString(
2142                    R.string.config_customResolverActivity);
2143            if (TextUtils.isEmpty(customResolverActivity)) {
2144                customResolverActivity = null;
2145            } else {
2146                mCustomResolverComponentName = ComponentName.unflattenFromString(
2147                        customResolverActivity);
2148            }
2149
2150            long startTime = SystemClock.uptimeMillis();
2151
2152            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2153                    startTime);
2154
2155            // Set flag to monitor and not change apk file paths when
2156            // scanning install directories.
2157            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2158
2159            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2160            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2161
2162            if (bootClassPath == null) {
2163                Slog.w(TAG, "No BOOTCLASSPATH found!");
2164            }
2165
2166            if (systemServerClassPath == null) {
2167                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2168            }
2169
2170            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2171            final String[] dexCodeInstructionSets =
2172                    getDexCodeInstructionSets(
2173                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2174
2175            /**
2176             * Ensure all external libraries have had dexopt run on them.
2177             */
2178            if (mSharedLibraries.size() > 0) {
2179                // NOTE: For now, we're compiling these system "shared libraries"
2180                // (and framework jars) into all available architectures. It's possible
2181                // to compile them only when we come across an app that uses them (there's
2182                // already logic for that in scanPackageLI) but that adds some complexity.
2183                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2184                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2185                        final String lib = libEntry.path;
2186                        if (lib == null) {
2187                            continue;
2188                        }
2189
2190                        try {
2191                            // Shared libraries do not have profiles so we perform a full
2192                            // AOT compilation (if needed).
2193                            int dexoptNeeded = DexFile.getDexOptNeeded(
2194                                    lib, dexCodeInstructionSet,
2195                                    getCompilerFilterForReason(REASON_SHARED_APK),
2196                                    false /* newProfile */);
2197                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2198                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2199                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2200                                        getCompilerFilterForReason(REASON_SHARED_APK),
2201                                        StorageManager.UUID_PRIVATE_INTERNAL);
2202                            }
2203                        } catch (FileNotFoundException e) {
2204                            Slog.w(TAG, "Library not found: " + lib);
2205                        } catch (IOException | InstallerException e) {
2206                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2207                                    + e.getMessage());
2208                        }
2209                    }
2210                }
2211            }
2212
2213            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2214
2215            final VersionInfo ver = mSettings.getInternalVersion();
2216            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2217
2218            // when upgrading from pre-M, promote system app permissions from install to runtime
2219            mPromoteSystemApps =
2220                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2221
2222            // save off the names of pre-existing system packages prior to scanning; we don't
2223            // want to automatically grant runtime permissions for new system apps
2224            if (mPromoteSystemApps) {
2225                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2226                while (pkgSettingIter.hasNext()) {
2227                    PackageSetting ps = pkgSettingIter.next();
2228                    if (isSystemApp(ps)) {
2229                        mExistingSystemPackages.add(ps.name);
2230                    }
2231                }
2232            }
2233
2234            // When upgrading from pre-N, we need to handle package extraction like first boot,
2235            // as there is no profiling data available.
2236            mIsPreNUpgrade = !mSettings.isNWorkDone();
2237            mSettings.setNWorkDone();
2238
2239            // Collect vendor overlay packages.
2240            // (Do this before scanning any apps.)
2241            // For security and version matching reason, only consider
2242            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2243            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2244            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2245                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2246
2247            // Find base frameworks (resource packages without code).
2248            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2249                    | PackageParser.PARSE_IS_SYSTEM_DIR
2250                    | PackageParser.PARSE_IS_PRIVILEGED,
2251                    scanFlags | SCAN_NO_DEX, 0);
2252
2253            // Collected privileged system packages.
2254            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2255            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2256                    | PackageParser.PARSE_IS_SYSTEM_DIR
2257                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2258
2259            // Collect ordinary system packages.
2260            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2261            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2262                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2263
2264            // Collect all vendor packages.
2265            File vendorAppDir = new File("/vendor/app");
2266            try {
2267                vendorAppDir = vendorAppDir.getCanonicalFile();
2268            } catch (IOException e) {
2269                // failed to look up canonical path, continue with original one
2270            }
2271            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2272                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2273
2274            // Collect all OEM packages.
2275            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2276            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2277                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2278
2279            // Prune any system packages that no longer exist.
2280            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2281            if (!mOnlyCore) {
2282                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2283                while (psit.hasNext()) {
2284                    PackageSetting ps = psit.next();
2285
2286                    /*
2287                     * If this is not a system app, it can't be a
2288                     * disable system app.
2289                     */
2290                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2291                        continue;
2292                    }
2293
2294                    /*
2295                     * If the package is scanned, it's not erased.
2296                     */
2297                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2298                    if (scannedPkg != null) {
2299                        /*
2300                         * If the system app is both scanned and in the
2301                         * disabled packages list, then it must have been
2302                         * added via OTA. Remove it from the currently
2303                         * scanned package so the previously user-installed
2304                         * application can be scanned.
2305                         */
2306                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2307                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2308                                    + ps.name + "; removing system app.  Last known codePath="
2309                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2310                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2311                                    + scannedPkg.mVersionCode);
2312                            removePackageLI(scannedPkg, true);
2313                            mExpectingBetter.put(ps.name, ps.codePath);
2314                        }
2315
2316                        continue;
2317                    }
2318
2319                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2320                        psit.remove();
2321                        logCriticalInfo(Log.WARN, "System package " + ps.name
2322                                + " no longer exists; wiping its data");
2323                        removeDataDirsLI(null, ps.name);
2324                    } else {
2325                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2326                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2327                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2328                        }
2329                    }
2330                }
2331            }
2332
2333            //look for any incomplete package installations
2334            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2335            //clean up list
2336            for(int i = 0; i < deletePkgsList.size(); i++) {
2337                //clean up here
2338                cleanupInstallFailedPackage(deletePkgsList.get(i));
2339            }
2340            //delete tmp files
2341            deleteTempPackageFiles();
2342
2343            // Remove any shared userIDs that have no associated packages
2344            mSettings.pruneSharedUsersLPw();
2345
2346            if (!mOnlyCore) {
2347                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2348                        SystemClock.uptimeMillis());
2349                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2350
2351                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2352                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2353
2354                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2355                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2356
2357                /**
2358                 * Remove disable package settings for any updated system
2359                 * apps that were removed via an OTA. If they're not a
2360                 * previously-updated app, remove them completely.
2361                 * Otherwise, just revoke their system-level permissions.
2362                 */
2363                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2364                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2365                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2366
2367                    String msg;
2368                    if (deletedPkg == null) {
2369                        msg = "Updated system package " + deletedAppName
2370                                + " no longer exists; wiping its data";
2371                        removeDataDirsLI(null, deletedAppName);
2372                    } else {
2373                        msg = "Updated system app + " + deletedAppName
2374                                + " no longer present; removing system privileges for "
2375                                + deletedAppName;
2376
2377                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2378
2379                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2380                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2381                    }
2382                    logCriticalInfo(Log.WARN, msg);
2383                }
2384
2385                /**
2386                 * Make sure all system apps that we expected to appear on
2387                 * the userdata partition actually showed up. If they never
2388                 * appeared, crawl back and revive the system version.
2389                 */
2390                for (int i = 0; i < mExpectingBetter.size(); i++) {
2391                    final String packageName = mExpectingBetter.keyAt(i);
2392                    if (!mPackages.containsKey(packageName)) {
2393                        final File scanFile = mExpectingBetter.valueAt(i);
2394
2395                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2396                                + " but never showed up; reverting to system");
2397
2398                        final int reparseFlags;
2399                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2400                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2401                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2402                                    | PackageParser.PARSE_IS_PRIVILEGED;
2403                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2404                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2405                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2406                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2407                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2408                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2409                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2410                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2411                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2412                        } else {
2413                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2414                            continue;
2415                        }
2416
2417                        mSettings.enableSystemPackageLPw(packageName);
2418
2419                        try {
2420                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2421                        } catch (PackageManagerException e) {
2422                            Slog.e(TAG, "Failed to parse original system package: "
2423                                    + e.getMessage());
2424                        }
2425                    }
2426                }
2427            }
2428            mExpectingBetter.clear();
2429
2430            // Now that we know all of the shared libraries, update all clients to have
2431            // the correct library paths.
2432            updateAllSharedLibrariesLPw();
2433
2434            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2435                // NOTE: We ignore potential failures here during a system scan (like
2436                // the rest of the commands above) because there's precious little we
2437                // can do about it. A settings error is reported, though.
2438                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2439                        false /* boot complete */);
2440            }
2441
2442            // Now that we know all the packages we are keeping,
2443            // read and update their last usage times.
2444            mPackageUsage.readLP();
2445
2446            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2447                    SystemClock.uptimeMillis());
2448            Slog.i(TAG, "Time to scan packages: "
2449                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2450                    + " seconds");
2451
2452            // If the platform SDK has changed since the last time we booted,
2453            // we need to re-grant app permission to catch any new ones that
2454            // appear.  This is really a hack, and means that apps can in some
2455            // cases get permissions that the user didn't initially explicitly
2456            // allow...  it would be nice to have some better way to handle
2457            // this situation.
2458            int updateFlags = UPDATE_PERMISSIONS_ALL;
2459            if (ver.sdkVersion != mSdkVersion) {
2460                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2461                        + mSdkVersion + "; regranting permissions for internal storage");
2462                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2463            }
2464            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2465            ver.sdkVersion = mSdkVersion;
2466
2467            // If this is the first boot or an update from pre-M, and it is a normal
2468            // boot, then we need to initialize the default preferred apps across
2469            // all defined users.
2470            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2471                for (UserInfo user : sUserManager.getUsers(true)) {
2472                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2473                    applyFactoryDefaultBrowserLPw(user.id);
2474                    primeDomainVerificationsLPw(user.id);
2475                }
2476            }
2477
2478            // Prepare storage for system user really early during boot,
2479            // since core system apps like SettingsProvider and SystemUI
2480            // can't wait for user to start
2481            final int storageFlags;
2482            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2483                storageFlags = StorageManager.FLAG_STORAGE_DE;
2484            } else {
2485                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2486            }
2487            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2488                    storageFlags);
2489
2490            // If this is first boot after an OTA, and a normal boot, then
2491            // we need to clear code cache directories.
2492            if (mIsUpgrade && !onlyCore) {
2493                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2494                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2495                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2496                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2497                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2498                    }
2499                }
2500                ver.fingerprint = Build.FINGERPRINT;
2501            }
2502
2503            checkDefaultBrowser();
2504
2505            // clear only after permissions and other defaults have been updated
2506            mExistingSystemPackages.clear();
2507            mPromoteSystemApps = false;
2508
2509            // All the changes are done during package scanning.
2510            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2511
2512            // can downgrade to reader
2513            mSettings.writeLPr();
2514
2515            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2516                    SystemClock.uptimeMillis());
2517
2518            if (!mOnlyCore) {
2519                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2520                mRequiredInstallerPackage = getRequiredInstallerLPr();
2521                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2522                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2523                        mIntentFilterVerifierComponent);
2524            } else {
2525                mRequiredVerifierPackage = null;
2526                mRequiredInstallerPackage = null;
2527                mIntentFilterVerifierComponent = null;
2528                mIntentFilterVerifier = null;
2529            }
2530
2531            mInstallerService = new PackageInstallerService(context, this);
2532
2533            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2534            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2535            // both the installer and resolver must be present to enable ephemeral
2536            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2537                if (DEBUG_EPHEMERAL) {
2538                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2539                            + " installer:" + ephemeralInstallerComponent);
2540                }
2541                mEphemeralResolverComponent = ephemeralResolverComponent;
2542                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2543                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2544                mEphemeralResolverConnection =
2545                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2546            } else {
2547                if (DEBUG_EPHEMERAL) {
2548                    final String missingComponent =
2549                            (ephemeralResolverComponent == null)
2550                            ? (ephemeralInstallerComponent == null)
2551                                    ? "resolver and installer"
2552                                    : "resolver"
2553                            : "installer";
2554                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2555                }
2556                mEphemeralResolverComponent = null;
2557                mEphemeralInstallerComponent = null;
2558                mEphemeralResolverConnection = null;
2559            }
2560
2561            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2562        } // synchronized (mPackages)
2563        } // synchronized (mInstallLock)
2564
2565        // Now after opening every single application zip, make sure they
2566        // are all flushed.  Not really needed, but keeps things nice and
2567        // tidy.
2568        Runtime.getRuntime().gc();
2569
2570        // The initial scanning above does many calls into installd while
2571        // holding the mPackages lock, but we're mostly interested in yelling
2572        // once we have a booted system.
2573        mInstaller.setWarnIfHeld(mPackages);
2574
2575        // Expose private service for system components to use.
2576        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2577    }
2578
2579    @Override
2580    public boolean isFirstBoot() {
2581        return !mRestoredSettings;
2582    }
2583
2584    @Override
2585    public boolean isOnlyCoreApps() {
2586        return mOnlyCore;
2587    }
2588
2589    @Override
2590    public boolean isUpgrade() {
2591        return mIsUpgrade;
2592    }
2593
2594    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2595        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2596
2597        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2598                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2599                UserHandle.USER_SYSTEM);
2600        if (matches.size() == 1) {
2601            return matches.get(0).getComponentInfo().packageName;
2602        } else {
2603            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2604            return null;
2605        }
2606    }
2607
2608    private @NonNull String getRequiredInstallerLPr() {
2609        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2610        intent.addCategory(Intent.CATEGORY_DEFAULT);
2611        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2612
2613        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2614                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2615                UserHandle.USER_SYSTEM);
2616        if (matches.size() == 1) {
2617            return matches.get(0).getComponentInfo().packageName;
2618        } else {
2619            throw new RuntimeException("There must be exactly one installer; found " + matches);
2620        }
2621    }
2622
2623    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2624        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2625
2626        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2627                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2628                UserHandle.USER_SYSTEM);
2629        ResolveInfo best = null;
2630        final int N = matches.size();
2631        for (int i = 0; i < N; i++) {
2632            final ResolveInfo cur = matches.get(i);
2633            final String packageName = cur.getComponentInfo().packageName;
2634            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2635                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2636                continue;
2637            }
2638
2639            if (best == null || cur.priority > best.priority) {
2640                best = cur;
2641            }
2642        }
2643
2644        if (best != null) {
2645            return best.getComponentInfo().getComponentName();
2646        } else {
2647            throw new RuntimeException("There must be at least one intent filter verifier");
2648        }
2649    }
2650
2651    private @Nullable ComponentName getEphemeralResolverLPr() {
2652        final String[] packageArray =
2653                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2654        if (packageArray.length == 0) {
2655            if (DEBUG_EPHEMERAL) {
2656                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2657            }
2658            return null;
2659        }
2660
2661        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2662        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2663                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2664                UserHandle.USER_SYSTEM);
2665
2666        final int N = resolvers.size();
2667        if (N == 0) {
2668            if (DEBUG_EPHEMERAL) {
2669                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2670            }
2671            return null;
2672        }
2673
2674        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2675        for (int i = 0; i < N; i++) {
2676            final ResolveInfo info = resolvers.get(i);
2677
2678            if (info.serviceInfo == null) {
2679                continue;
2680            }
2681
2682            final String packageName = info.serviceInfo.packageName;
2683            if (!possiblePackages.contains(packageName)) {
2684                if (DEBUG_EPHEMERAL) {
2685                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2686                            + " pkg: " + packageName + ", info:" + info);
2687                }
2688                continue;
2689            }
2690
2691            if (DEBUG_EPHEMERAL) {
2692                Slog.v(TAG, "Ephemeral resolver found;"
2693                        + " pkg: " + packageName + ", info:" + info);
2694            }
2695            return new ComponentName(packageName, info.serviceInfo.name);
2696        }
2697        if (DEBUG_EPHEMERAL) {
2698            Slog.v(TAG, "Ephemeral resolver NOT found");
2699        }
2700        return null;
2701    }
2702
2703    private @Nullable ComponentName getEphemeralInstallerLPr() {
2704        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2705        intent.addCategory(Intent.CATEGORY_DEFAULT);
2706        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2707
2708        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2709                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2710                UserHandle.USER_SYSTEM);
2711        if (matches.size() == 0) {
2712            return null;
2713        } else if (matches.size() == 1) {
2714            return matches.get(0).getComponentInfo().getComponentName();
2715        } else {
2716            throw new RuntimeException(
2717                    "There must be at most one ephemeral installer; found " + matches);
2718        }
2719    }
2720
2721    private void primeDomainVerificationsLPw(int userId) {
2722        if (DEBUG_DOMAIN_VERIFICATION) {
2723            Slog.d(TAG, "Priming domain verifications in user " + userId);
2724        }
2725
2726        SystemConfig systemConfig = SystemConfig.getInstance();
2727        ArraySet<String> packages = systemConfig.getLinkedApps();
2728        ArraySet<String> domains = new ArraySet<String>();
2729
2730        for (String packageName : packages) {
2731            PackageParser.Package pkg = mPackages.get(packageName);
2732            if (pkg != null) {
2733                if (!pkg.isSystemApp()) {
2734                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2735                    continue;
2736                }
2737
2738                domains.clear();
2739                for (PackageParser.Activity a : pkg.activities) {
2740                    for (ActivityIntentInfo filter : a.intents) {
2741                        if (hasValidDomains(filter)) {
2742                            domains.addAll(filter.getHostsList());
2743                        }
2744                    }
2745                }
2746
2747                if (domains.size() > 0) {
2748                    if (DEBUG_DOMAIN_VERIFICATION) {
2749                        Slog.v(TAG, "      + " + packageName);
2750                    }
2751                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2752                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2753                    // and then 'always' in the per-user state actually used for intent resolution.
2754                    final IntentFilterVerificationInfo ivi;
2755                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2756                            new ArrayList<String>(domains));
2757                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2758                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2759                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2760                } else {
2761                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2762                            + "' does not handle web links");
2763                }
2764            } else {
2765                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2766            }
2767        }
2768
2769        scheduleWritePackageRestrictionsLocked(userId);
2770        scheduleWriteSettingsLocked();
2771    }
2772
2773    private void applyFactoryDefaultBrowserLPw(int userId) {
2774        // The default browser app's package name is stored in a string resource,
2775        // with a product-specific overlay used for vendor customization.
2776        String browserPkg = mContext.getResources().getString(
2777                com.android.internal.R.string.default_browser);
2778        if (!TextUtils.isEmpty(browserPkg)) {
2779            // non-empty string => required to be a known package
2780            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2781            if (ps == null) {
2782                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2783                browserPkg = null;
2784            } else {
2785                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2786            }
2787        }
2788
2789        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2790        // default.  If there's more than one, just leave everything alone.
2791        if (browserPkg == null) {
2792            calculateDefaultBrowserLPw(userId);
2793        }
2794    }
2795
2796    private void calculateDefaultBrowserLPw(int userId) {
2797        List<String> allBrowsers = resolveAllBrowserApps(userId);
2798        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2799        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2800    }
2801
2802    private List<String> resolveAllBrowserApps(int userId) {
2803        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2804        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2805                PackageManager.MATCH_ALL, userId);
2806
2807        final int count = list.size();
2808        List<String> result = new ArrayList<String>(count);
2809        for (int i=0; i<count; i++) {
2810            ResolveInfo info = list.get(i);
2811            if (info.activityInfo == null
2812                    || !info.handleAllWebDataURI
2813                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2814                    || result.contains(info.activityInfo.packageName)) {
2815                continue;
2816            }
2817            result.add(info.activityInfo.packageName);
2818        }
2819
2820        return result;
2821    }
2822
2823    private boolean packageIsBrowser(String packageName, int userId) {
2824        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2825                PackageManager.MATCH_ALL, userId);
2826        final int N = list.size();
2827        for (int i = 0; i < N; i++) {
2828            ResolveInfo info = list.get(i);
2829            if (packageName.equals(info.activityInfo.packageName)) {
2830                return true;
2831            }
2832        }
2833        return false;
2834    }
2835
2836    private void checkDefaultBrowser() {
2837        final int myUserId = UserHandle.myUserId();
2838        final String packageName = getDefaultBrowserPackageName(myUserId);
2839        if (packageName != null) {
2840            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2841            if (info == null) {
2842                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2843                synchronized (mPackages) {
2844                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2845                }
2846            }
2847        }
2848    }
2849
2850    @Override
2851    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2852            throws RemoteException {
2853        try {
2854            return super.onTransact(code, data, reply, flags);
2855        } catch (RuntimeException e) {
2856            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2857                Slog.wtf(TAG, "Package Manager Crash", e);
2858            }
2859            throw e;
2860        }
2861    }
2862
2863    void cleanupInstallFailedPackage(PackageSetting ps) {
2864        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2865
2866        removeDataDirsLI(ps.volumeUuid, ps.name);
2867        if (ps.codePath != null) {
2868            removeCodePathLI(ps.codePath);
2869        }
2870        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2871            if (ps.resourcePath.isDirectory()) {
2872                FileUtils.deleteContents(ps.resourcePath);
2873            }
2874            ps.resourcePath.delete();
2875        }
2876        mSettings.removePackageLPw(ps.name);
2877    }
2878
2879    static int[] appendInts(int[] cur, int[] add) {
2880        if (add == null) return cur;
2881        if (cur == null) return add;
2882        final int N = add.length;
2883        for (int i=0; i<N; i++) {
2884            cur = appendInt(cur, add[i]);
2885        }
2886        return cur;
2887    }
2888
2889    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        final PackageSetting ps = (PackageSetting) p.mExtras;
2892        if (ps == null) {
2893            return null;
2894        }
2895
2896        final PermissionsState permissionsState = ps.getPermissionsState();
2897
2898        final int[] gids = permissionsState.computeGids(userId);
2899        final Set<String> permissions = permissionsState.getPermissions(userId);
2900        final PackageUserState state = ps.readUserState(userId);
2901
2902        return PackageParser.generatePackageInfo(p, gids, flags,
2903                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2904    }
2905
2906    @Override
2907    public void checkPackageStartable(String packageName, int userId) {
2908        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2909
2910        synchronized (mPackages) {
2911            final PackageSetting ps = mSettings.mPackages.get(packageName);
2912            if (ps == null) {
2913                throw new SecurityException("Package " + packageName + " was not found!");
2914            }
2915
2916            if (!ps.getInstalled(userId)) {
2917                throw new SecurityException(
2918                        "Package " + packageName + " was not installed for user " + userId + "!");
2919            }
2920
2921            if (mSafeMode && !ps.isSystem()) {
2922                throw new SecurityException("Package " + packageName + " not a system app!");
2923            }
2924
2925            if (ps.frozen) {
2926                throw new SecurityException("Package " + packageName + " is currently frozen!");
2927            }
2928
2929            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
2930                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
2931                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2932            }
2933        }
2934    }
2935
2936    @Override
2937    public boolean isPackageAvailable(String packageName, int userId) {
2938        if (!sUserManager.exists(userId)) return false;
2939        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2940                false /* requireFullPermission */, false /* checkShell */, "is package available");
2941        synchronized (mPackages) {
2942            PackageParser.Package p = mPackages.get(packageName);
2943            if (p != null) {
2944                final PackageSetting ps = (PackageSetting) p.mExtras;
2945                if (ps != null) {
2946                    final PackageUserState state = ps.readUserState(userId);
2947                    if (state != null) {
2948                        return PackageParser.isAvailable(state);
2949                    }
2950                }
2951            }
2952        }
2953        return false;
2954    }
2955
2956    @Override
2957    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2958        if (!sUserManager.exists(userId)) return null;
2959        flags = updateFlagsForPackage(flags, userId, packageName);
2960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2961                false /* requireFullPermission */, false /* checkShell */, "get package info");
2962        // reader
2963        synchronized (mPackages) {
2964            PackageParser.Package p = mPackages.get(packageName);
2965            if (DEBUG_PACKAGE_INFO)
2966                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2967            if (p != null) {
2968                return generatePackageInfo(p, flags, userId);
2969            }
2970            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2971                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2972            }
2973        }
2974        return null;
2975    }
2976
2977    @Override
2978    public String[] currentToCanonicalPackageNames(String[] names) {
2979        String[] out = new String[names.length];
2980        // reader
2981        synchronized (mPackages) {
2982            for (int i=names.length-1; i>=0; i--) {
2983                PackageSetting ps = mSettings.mPackages.get(names[i]);
2984                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2985            }
2986        }
2987        return out;
2988    }
2989
2990    @Override
2991    public String[] canonicalToCurrentPackageNames(String[] names) {
2992        String[] out = new String[names.length];
2993        // reader
2994        synchronized (mPackages) {
2995            for (int i=names.length-1; i>=0; i--) {
2996                String cur = mSettings.mRenamedPackages.get(names[i]);
2997                out[i] = cur != null ? cur : names[i];
2998            }
2999        }
3000        return out;
3001    }
3002
3003    @Override
3004    public int getPackageUid(String packageName, int flags, int userId) {
3005        if (!sUserManager.exists(userId)) return -1;
3006        flags = updateFlagsForPackage(flags, userId, packageName);
3007        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3008                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3009
3010        // reader
3011        synchronized (mPackages) {
3012            final PackageParser.Package p = mPackages.get(packageName);
3013            if (p != null && p.isMatch(flags)) {
3014                return UserHandle.getUid(userId, p.applicationInfo.uid);
3015            }
3016            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3017                final PackageSetting ps = mSettings.mPackages.get(packageName);
3018                if (ps != null && ps.isMatch(flags)) {
3019                    return UserHandle.getUid(userId, ps.appId);
3020                }
3021            }
3022        }
3023
3024        return -1;
3025    }
3026
3027    @Override
3028    public int[] getPackageGids(String packageName, int flags, int userId) {
3029        if (!sUserManager.exists(userId)) return null;
3030        flags = updateFlagsForPackage(flags, userId, packageName);
3031        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3032                false /* requireFullPermission */, false /* checkShell */,
3033                "getPackageGids");
3034
3035        // reader
3036        synchronized (mPackages) {
3037            final PackageParser.Package p = mPackages.get(packageName);
3038            if (p != null && p.isMatch(flags)) {
3039                PackageSetting ps = (PackageSetting) p.mExtras;
3040                return ps.getPermissionsState().computeGids(userId);
3041            }
3042            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3043                final PackageSetting ps = mSettings.mPackages.get(packageName);
3044                if (ps != null && ps.isMatch(flags)) {
3045                    return ps.getPermissionsState().computeGids(userId);
3046                }
3047            }
3048        }
3049
3050        return null;
3051    }
3052
3053    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3054        if (bp.perm != null) {
3055            return PackageParser.generatePermissionInfo(bp.perm, flags);
3056        }
3057        PermissionInfo pi = new PermissionInfo();
3058        pi.name = bp.name;
3059        pi.packageName = bp.sourcePackage;
3060        pi.nonLocalizedLabel = bp.name;
3061        pi.protectionLevel = bp.protectionLevel;
3062        return pi;
3063    }
3064
3065    @Override
3066    public PermissionInfo getPermissionInfo(String name, int flags) {
3067        // reader
3068        synchronized (mPackages) {
3069            final BasePermission p = mSettings.mPermissions.get(name);
3070            if (p != null) {
3071                return generatePermissionInfo(p, flags);
3072            }
3073            return null;
3074        }
3075    }
3076
3077    @Override
3078    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3079            int flags) {
3080        // reader
3081        synchronized (mPackages) {
3082            if (group != null && !mPermissionGroups.containsKey(group)) {
3083                // This is thrown as NameNotFoundException
3084                return null;
3085            }
3086
3087            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3088            for (BasePermission p : mSettings.mPermissions.values()) {
3089                if (group == null) {
3090                    if (p.perm == null || p.perm.info.group == null) {
3091                        out.add(generatePermissionInfo(p, flags));
3092                    }
3093                } else {
3094                    if (p.perm != null && group.equals(p.perm.info.group)) {
3095                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3096                    }
3097                }
3098            }
3099            return new ParceledListSlice<>(out);
3100        }
3101    }
3102
3103    @Override
3104    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3105        // reader
3106        synchronized (mPackages) {
3107            return PackageParser.generatePermissionGroupInfo(
3108                    mPermissionGroups.get(name), flags);
3109        }
3110    }
3111
3112    @Override
3113    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3114        // reader
3115        synchronized (mPackages) {
3116            final int N = mPermissionGroups.size();
3117            ArrayList<PermissionGroupInfo> out
3118                    = new ArrayList<PermissionGroupInfo>(N);
3119            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3120                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3121            }
3122            return new ParceledListSlice<>(out);
3123        }
3124    }
3125
3126    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3127            int userId) {
3128        if (!sUserManager.exists(userId)) return null;
3129        PackageSetting ps = mSettings.mPackages.get(packageName);
3130        if (ps != null) {
3131            if (ps.pkg == null) {
3132                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3133                        flags, userId);
3134                if (pInfo != null) {
3135                    return pInfo.applicationInfo;
3136                }
3137                return null;
3138            }
3139            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3140                    ps.readUserState(userId), userId);
3141        }
3142        return null;
3143    }
3144
3145    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3146            int userId) {
3147        if (!sUserManager.exists(userId)) return null;
3148        PackageSetting ps = mSettings.mPackages.get(packageName);
3149        if (ps != null) {
3150            PackageParser.Package pkg = ps.pkg;
3151            if (pkg == null) {
3152                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3153                    return null;
3154                }
3155                // Only data remains, so we aren't worried about code paths
3156                pkg = new PackageParser.Package(packageName);
3157                pkg.applicationInfo.packageName = packageName;
3158                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3159                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3160                pkg.applicationInfo.uid = ps.appId;
3161                pkg.applicationInfo.initForUser(userId);
3162                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3163                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3164            }
3165            return generatePackageInfo(pkg, flags, userId);
3166        }
3167        return null;
3168    }
3169
3170    @Override
3171    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3172        if (!sUserManager.exists(userId)) return null;
3173        flags = updateFlagsForApplication(flags, userId, packageName);
3174        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3175                false /* requireFullPermission */, false /* checkShell */, "get application info");
3176        // writer
3177        synchronized (mPackages) {
3178            PackageParser.Package p = mPackages.get(packageName);
3179            if (DEBUG_PACKAGE_INFO) Log.v(
3180                    TAG, "getApplicationInfo " + packageName
3181                    + ": " + p);
3182            if (p != null) {
3183                PackageSetting ps = mSettings.mPackages.get(packageName);
3184                if (ps == null) return null;
3185                // Note: isEnabledLP() does not apply here - always return info
3186                return PackageParser.generateApplicationInfo(
3187                        p, flags, ps.readUserState(userId), userId);
3188            }
3189            if ("android".equals(packageName)||"system".equals(packageName)) {
3190                return mAndroidApplication;
3191            }
3192            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3193                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3194            }
3195        }
3196        return null;
3197    }
3198
3199    @Override
3200    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3201            final IPackageDataObserver observer) {
3202        mContext.enforceCallingOrSelfPermission(
3203                android.Manifest.permission.CLEAR_APP_CACHE, null);
3204        // Queue up an async operation since clearing cache may take a little while.
3205        mHandler.post(new Runnable() {
3206            public void run() {
3207                mHandler.removeCallbacks(this);
3208                boolean success = true;
3209                synchronized (mInstallLock) {
3210                    try {
3211                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3212                    } catch (InstallerException e) {
3213                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3214                        success = false;
3215                    }
3216                }
3217                if (observer != null) {
3218                    try {
3219                        observer.onRemoveCompleted(null, success);
3220                    } catch (RemoteException e) {
3221                        Slog.w(TAG, "RemoveException when invoking call back");
3222                    }
3223                }
3224            }
3225        });
3226    }
3227
3228    @Override
3229    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3230            final IntentSender pi) {
3231        mContext.enforceCallingOrSelfPermission(
3232                android.Manifest.permission.CLEAR_APP_CACHE, null);
3233        // Queue up an async operation since clearing cache may take a little while.
3234        mHandler.post(new Runnable() {
3235            public void run() {
3236                mHandler.removeCallbacks(this);
3237                boolean success = true;
3238                synchronized (mInstallLock) {
3239                    try {
3240                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3241                    } catch (InstallerException e) {
3242                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3243                        success = false;
3244                    }
3245                }
3246                if(pi != null) {
3247                    try {
3248                        // Callback via pending intent
3249                        int code = success ? 1 : 0;
3250                        pi.sendIntent(null, code, null,
3251                                null, null);
3252                    } catch (SendIntentException e1) {
3253                        Slog.i(TAG, "Failed to send pending intent");
3254                    }
3255                }
3256            }
3257        });
3258    }
3259
3260    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3261        synchronized (mInstallLock) {
3262            try {
3263                mInstaller.freeCache(volumeUuid, freeStorageSize);
3264            } catch (InstallerException e) {
3265                throw new IOException("Failed to free enough space", e);
3266            }
3267        }
3268    }
3269
3270    /**
3271     * Return if the user key is currently unlocked.
3272     */
3273    private boolean isUserKeyUnlocked(int userId) {
3274        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3275            final IMountService mount = IMountService.Stub
3276                    .asInterface(ServiceManager.getService("mount"));
3277            if (mount == null) {
3278                Slog.w(TAG, "Early during boot, assuming locked");
3279                return false;
3280            }
3281            final long token = Binder.clearCallingIdentity();
3282            try {
3283                return mount.isUserKeyUnlocked(userId);
3284            } catch (RemoteException e) {
3285                throw e.rethrowAsRuntimeException();
3286            } finally {
3287                Binder.restoreCallingIdentity(token);
3288            }
3289        } else {
3290            return true;
3291        }
3292    }
3293
3294    /**
3295     * Update given flags based on encryption status of current user.
3296     */
3297    private int updateFlags(int flags, int userId) {
3298        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3299                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3300            // Caller expressed an explicit opinion about what encryption
3301            // aware/unaware components they want to see, so fall through and
3302            // give them what they want
3303        } else {
3304            // Caller expressed no opinion, so match based on user state
3305            if (isUserKeyUnlocked(userId)) {
3306                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3307            } else {
3308                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3309            }
3310        }
3311        return flags;
3312    }
3313
3314    /**
3315     * Update given flags when being used to request {@link PackageInfo}.
3316     */
3317    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3318        boolean triaged = true;
3319        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3320                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3321            // Caller is asking for component details, so they'd better be
3322            // asking for specific encryption matching behavior, or be triaged
3323            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3324                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3325                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3326                triaged = false;
3327            }
3328        }
3329        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3330                | PackageManager.MATCH_SYSTEM_ONLY
3331                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3332            triaged = false;
3333        }
3334        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3335            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3336                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3337        }
3338        return updateFlags(flags, userId);
3339    }
3340
3341    /**
3342     * Update given flags when being used to request {@link ApplicationInfo}.
3343     */
3344    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3345        return updateFlagsForPackage(flags, userId, cookie);
3346    }
3347
3348    /**
3349     * Update given flags when being used to request {@link ComponentInfo}.
3350     */
3351    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3352        if (cookie instanceof Intent) {
3353            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3354                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3355            }
3356        }
3357
3358        boolean triaged = true;
3359        // Caller is asking for component details, so they'd better be
3360        // asking for specific encryption matching behavior, or be triaged
3361        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3362                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3363                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3364            triaged = false;
3365        }
3366        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3367            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3368                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3369        }
3370
3371        return updateFlags(flags, userId);
3372    }
3373
3374    /**
3375     * Update given flags when being used to request {@link ResolveInfo}.
3376     */
3377    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3378        // Safe mode means we shouldn't match any third-party components
3379        if (mSafeMode) {
3380            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3381        }
3382
3383        return updateFlagsForComponent(flags, userId, cookie);
3384    }
3385
3386    @Override
3387    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3388        if (!sUserManager.exists(userId)) return null;
3389        flags = updateFlagsForComponent(flags, userId, component);
3390        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3391                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3392        synchronized (mPackages) {
3393            PackageParser.Activity a = mActivities.mActivities.get(component);
3394
3395            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3396            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3397                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3398                if (ps == null) return null;
3399                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3400                        userId);
3401            }
3402            if (mResolveComponentName.equals(component)) {
3403                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3404                        new PackageUserState(), userId);
3405            }
3406        }
3407        return null;
3408    }
3409
3410    @Override
3411    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3412            String resolvedType) {
3413        synchronized (mPackages) {
3414            if (component.equals(mResolveComponentName)) {
3415                // The resolver supports EVERYTHING!
3416                return true;
3417            }
3418            PackageParser.Activity a = mActivities.mActivities.get(component);
3419            if (a == null) {
3420                return false;
3421            }
3422            for (int i=0; i<a.intents.size(); i++) {
3423                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3424                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3425                    return true;
3426                }
3427            }
3428            return false;
3429        }
3430    }
3431
3432    @Override
3433    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3434        if (!sUserManager.exists(userId)) return null;
3435        flags = updateFlagsForComponent(flags, userId, component);
3436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3437                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3438        synchronized (mPackages) {
3439            PackageParser.Activity a = mReceivers.mActivities.get(component);
3440            if (DEBUG_PACKAGE_INFO) Log.v(
3441                TAG, "getReceiverInfo " + component + ": " + a);
3442            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3443                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3444                if (ps == null) return null;
3445                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3446                        userId);
3447            }
3448        }
3449        return null;
3450    }
3451
3452    @Override
3453    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3454        if (!sUserManager.exists(userId)) return null;
3455        flags = updateFlagsForComponent(flags, userId, component);
3456        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3457                false /* requireFullPermission */, false /* checkShell */, "get service info");
3458        synchronized (mPackages) {
3459            PackageParser.Service s = mServices.mServices.get(component);
3460            if (DEBUG_PACKAGE_INFO) Log.v(
3461                TAG, "getServiceInfo " + component + ": " + s);
3462            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3463                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3464                if (ps == null) return null;
3465                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3466                        userId);
3467            }
3468        }
3469        return null;
3470    }
3471
3472    @Override
3473    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3474        if (!sUserManager.exists(userId)) return null;
3475        flags = updateFlagsForComponent(flags, userId, component);
3476        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3477                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3478        synchronized (mPackages) {
3479            PackageParser.Provider p = mProviders.mProviders.get(component);
3480            if (DEBUG_PACKAGE_INFO) Log.v(
3481                TAG, "getProviderInfo " + component + ": " + p);
3482            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3483                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3484                if (ps == null) return null;
3485                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3486                        userId);
3487            }
3488        }
3489        return null;
3490    }
3491
3492    @Override
3493    public String[] getSystemSharedLibraryNames() {
3494        Set<String> libSet;
3495        synchronized (mPackages) {
3496            libSet = mSharedLibraries.keySet();
3497            int size = libSet.size();
3498            if (size > 0) {
3499                String[] libs = new String[size];
3500                libSet.toArray(libs);
3501                return libs;
3502            }
3503        }
3504        return null;
3505    }
3506
3507    @Override
3508    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3509        synchronized (mPackages) {
3510            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3511                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3512            if (libraryEntry != null) {
3513                return libraryEntry.apk;
3514            }
3515        }
3516        return null;
3517    }
3518
3519    @Override
3520    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3521        synchronized (mPackages) {
3522            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3523
3524            final FeatureInfo fi = new FeatureInfo();
3525            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3526                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3527            res.add(fi);
3528
3529            return new ParceledListSlice<>(res);
3530        }
3531    }
3532
3533    @Override
3534    public boolean hasSystemFeature(String name, int version) {
3535        synchronized (mPackages) {
3536            final FeatureInfo feat = mAvailableFeatures.get(name);
3537            if (feat == null) {
3538                return false;
3539            } else {
3540                return feat.version >= version;
3541            }
3542        }
3543    }
3544
3545    @Override
3546    public int checkPermission(String permName, String pkgName, int userId) {
3547        if (!sUserManager.exists(userId)) {
3548            return PackageManager.PERMISSION_DENIED;
3549        }
3550
3551        synchronized (mPackages) {
3552            final PackageParser.Package p = mPackages.get(pkgName);
3553            if (p != null && p.mExtras != null) {
3554                final PackageSetting ps = (PackageSetting) p.mExtras;
3555                final PermissionsState permissionsState = ps.getPermissionsState();
3556                if (permissionsState.hasPermission(permName, userId)) {
3557                    return PackageManager.PERMISSION_GRANTED;
3558                }
3559                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3560                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3561                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3562                    return PackageManager.PERMISSION_GRANTED;
3563                }
3564            }
3565        }
3566
3567        return PackageManager.PERMISSION_DENIED;
3568    }
3569
3570    @Override
3571    public int checkUidPermission(String permName, int uid) {
3572        final int userId = UserHandle.getUserId(uid);
3573
3574        if (!sUserManager.exists(userId)) {
3575            return PackageManager.PERMISSION_DENIED;
3576        }
3577
3578        synchronized (mPackages) {
3579            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3580            if (obj != null) {
3581                final SettingBase ps = (SettingBase) obj;
3582                final PermissionsState permissionsState = ps.getPermissionsState();
3583                if (permissionsState.hasPermission(permName, userId)) {
3584                    return PackageManager.PERMISSION_GRANTED;
3585                }
3586                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3587                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3588                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3589                    return PackageManager.PERMISSION_GRANTED;
3590                }
3591            } else {
3592                ArraySet<String> perms = mSystemPermissions.get(uid);
3593                if (perms != null) {
3594                    if (perms.contains(permName)) {
3595                        return PackageManager.PERMISSION_GRANTED;
3596                    }
3597                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3598                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3599                        return PackageManager.PERMISSION_GRANTED;
3600                    }
3601                }
3602            }
3603        }
3604
3605        return PackageManager.PERMISSION_DENIED;
3606    }
3607
3608    @Override
3609    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3610        if (UserHandle.getCallingUserId() != userId) {
3611            mContext.enforceCallingPermission(
3612                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3613                    "isPermissionRevokedByPolicy for user " + userId);
3614        }
3615
3616        if (checkPermission(permission, packageName, userId)
3617                == PackageManager.PERMISSION_GRANTED) {
3618            return false;
3619        }
3620
3621        final long identity = Binder.clearCallingIdentity();
3622        try {
3623            final int flags = getPermissionFlags(permission, packageName, userId);
3624            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3625        } finally {
3626            Binder.restoreCallingIdentity(identity);
3627        }
3628    }
3629
3630    @Override
3631    public String getPermissionControllerPackageName() {
3632        synchronized (mPackages) {
3633            return mRequiredInstallerPackage;
3634        }
3635    }
3636
3637    /**
3638     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3639     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3640     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3641     * @param message the message to log on security exception
3642     */
3643    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3644            boolean checkShell, String message) {
3645        if (userId < 0) {
3646            throw new IllegalArgumentException("Invalid userId " + userId);
3647        }
3648        if (checkShell) {
3649            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3650        }
3651        if (userId == UserHandle.getUserId(callingUid)) return;
3652        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3653            if (requireFullPermission) {
3654                mContext.enforceCallingOrSelfPermission(
3655                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3656            } else {
3657                try {
3658                    mContext.enforceCallingOrSelfPermission(
3659                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3660                } catch (SecurityException se) {
3661                    mContext.enforceCallingOrSelfPermission(
3662                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3663                }
3664            }
3665        }
3666    }
3667
3668    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3669        if (callingUid == Process.SHELL_UID) {
3670            if (userHandle >= 0
3671                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3672                throw new SecurityException("Shell does not have permission to access user "
3673                        + userHandle);
3674            } else if (userHandle < 0) {
3675                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3676                        + Debug.getCallers(3));
3677            }
3678        }
3679    }
3680
3681    private BasePermission findPermissionTreeLP(String permName) {
3682        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3683            if (permName.startsWith(bp.name) &&
3684                    permName.length() > bp.name.length() &&
3685                    permName.charAt(bp.name.length()) == '.') {
3686                return bp;
3687            }
3688        }
3689        return null;
3690    }
3691
3692    private BasePermission checkPermissionTreeLP(String permName) {
3693        if (permName != null) {
3694            BasePermission bp = findPermissionTreeLP(permName);
3695            if (bp != null) {
3696                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3697                    return bp;
3698                }
3699                throw new SecurityException("Calling uid "
3700                        + Binder.getCallingUid()
3701                        + " is not allowed to add to permission tree "
3702                        + bp.name + " owned by uid " + bp.uid);
3703            }
3704        }
3705        throw new SecurityException("No permission tree found for " + permName);
3706    }
3707
3708    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3709        if (s1 == null) {
3710            return s2 == null;
3711        }
3712        if (s2 == null) {
3713            return false;
3714        }
3715        if (s1.getClass() != s2.getClass()) {
3716            return false;
3717        }
3718        return s1.equals(s2);
3719    }
3720
3721    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3722        if (pi1.icon != pi2.icon) return false;
3723        if (pi1.logo != pi2.logo) return false;
3724        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3725        if (!compareStrings(pi1.name, pi2.name)) return false;
3726        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3727        // We'll take care of setting this one.
3728        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3729        // These are not currently stored in settings.
3730        //if (!compareStrings(pi1.group, pi2.group)) return false;
3731        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3732        //if (pi1.labelRes != pi2.labelRes) return false;
3733        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3734        return true;
3735    }
3736
3737    int permissionInfoFootprint(PermissionInfo info) {
3738        int size = info.name.length();
3739        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3740        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3741        return size;
3742    }
3743
3744    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3745        int size = 0;
3746        for (BasePermission perm : mSettings.mPermissions.values()) {
3747            if (perm.uid == tree.uid) {
3748                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3749            }
3750        }
3751        return size;
3752    }
3753
3754    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3755        // We calculate the max size of permissions defined by this uid and throw
3756        // if that plus the size of 'info' would exceed our stated maximum.
3757        if (tree.uid != Process.SYSTEM_UID) {
3758            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3759            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3760                throw new SecurityException("Permission tree size cap exceeded");
3761            }
3762        }
3763    }
3764
3765    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3766        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3767            throw new SecurityException("Label must be specified in permission");
3768        }
3769        BasePermission tree = checkPermissionTreeLP(info.name);
3770        BasePermission bp = mSettings.mPermissions.get(info.name);
3771        boolean added = bp == null;
3772        boolean changed = true;
3773        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3774        if (added) {
3775            enforcePermissionCapLocked(info, tree);
3776            bp = new BasePermission(info.name, tree.sourcePackage,
3777                    BasePermission.TYPE_DYNAMIC);
3778        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3779            throw new SecurityException(
3780                    "Not allowed to modify non-dynamic permission "
3781                    + info.name);
3782        } else {
3783            if (bp.protectionLevel == fixedLevel
3784                    && bp.perm.owner.equals(tree.perm.owner)
3785                    && bp.uid == tree.uid
3786                    && comparePermissionInfos(bp.perm.info, info)) {
3787                changed = false;
3788            }
3789        }
3790        bp.protectionLevel = fixedLevel;
3791        info = new PermissionInfo(info);
3792        info.protectionLevel = fixedLevel;
3793        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3794        bp.perm.info.packageName = tree.perm.info.packageName;
3795        bp.uid = tree.uid;
3796        if (added) {
3797            mSettings.mPermissions.put(info.name, bp);
3798        }
3799        if (changed) {
3800            if (!async) {
3801                mSettings.writeLPr();
3802            } else {
3803                scheduleWriteSettingsLocked();
3804            }
3805        }
3806        return added;
3807    }
3808
3809    @Override
3810    public boolean addPermission(PermissionInfo info) {
3811        synchronized (mPackages) {
3812            return addPermissionLocked(info, false);
3813        }
3814    }
3815
3816    @Override
3817    public boolean addPermissionAsync(PermissionInfo info) {
3818        synchronized (mPackages) {
3819            return addPermissionLocked(info, true);
3820        }
3821    }
3822
3823    @Override
3824    public void removePermission(String name) {
3825        synchronized (mPackages) {
3826            checkPermissionTreeLP(name);
3827            BasePermission bp = mSettings.mPermissions.get(name);
3828            if (bp != null) {
3829                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3830                    throw new SecurityException(
3831                            "Not allowed to modify non-dynamic permission "
3832                            + name);
3833                }
3834                mSettings.mPermissions.remove(name);
3835                mSettings.writeLPr();
3836            }
3837        }
3838    }
3839
3840    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3841            BasePermission bp) {
3842        int index = pkg.requestedPermissions.indexOf(bp.name);
3843        if (index == -1) {
3844            throw new SecurityException("Package " + pkg.packageName
3845                    + " has not requested permission " + bp.name);
3846        }
3847        if (!bp.isRuntime() && !bp.isDevelopment()) {
3848            throw new SecurityException("Permission " + bp.name
3849                    + " is not a changeable permission type");
3850        }
3851    }
3852
3853    @Override
3854    public void grantRuntimePermission(String packageName, String name, final int userId) {
3855        if (!sUserManager.exists(userId)) {
3856            Log.e(TAG, "No such user:" + userId);
3857            return;
3858        }
3859
3860        mContext.enforceCallingOrSelfPermission(
3861                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3862                "grantRuntimePermission");
3863
3864        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3865                true /* requireFullPermission */, true /* checkShell */,
3866                "grantRuntimePermission");
3867
3868        final int uid;
3869        final SettingBase sb;
3870
3871        synchronized (mPackages) {
3872            final PackageParser.Package pkg = mPackages.get(packageName);
3873            if (pkg == null) {
3874                throw new IllegalArgumentException("Unknown package: " + packageName);
3875            }
3876
3877            final BasePermission bp = mSettings.mPermissions.get(name);
3878            if (bp == null) {
3879                throw new IllegalArgumentException("Unknown permission: " + name);
3880            }
3881
3882            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3883
3884            // If a permission review is required for legacy apps we represent
3885            // their permissions as always granted runtime ones since we need
3886            // to keep the review required permission flag per user while an
3887            // install permission's state is shared across all users.
3888            if (Build.PERMISSIONS_REVIEW_REQUIRED
3889                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3890                    && bp.isRuntime()) {
3891                return;
3892            }
3893
3894            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3895            sb = (SettingBase) pkg.mExtras;
3896            if (sb == null) {
3897                throw new IllegalArgumentException("Unknown package: " + packageName);
3898            }
3899
3900            final PermissionsState permissionsState = sb.getPermissionsState();
3901
3902            final int flags = permissionsState.getPermissionFlags(name, userId);
3903            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3904                throw new SecurityException("Cannot grant system fixed permission "
3905                        + name + " for package " + packageName);
3906            }
3907
3908            if (bp.isDevelopment()) {
3909                // Development permissions must be handled specially, since they are not
3910                // normal runtime permissions.  For now they apply to all users.
3911                if (permissionsState.grantInstallPermission(bp) !=
3912                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3913                    scheduleWriteSettingsLocked();
3914                }
3915                return;
3916            }
3917
3918            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3919                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3920                return;
3921            }
3922
3923            final int result = permissionsState.grantRuntimePermission(bp, userId);
3924            switch (result) {
3925                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3926                    return;
3927                }
3928
3929                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3930                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3931                    mHandler.post(new Runnable() {
3932                        @Override
3933                        public void run() {
3934                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3935                        }
3936                    });
3937                }
3938                break;
3939            }
3940
3941            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3942
3943            // Not critical if that is lost - app has to request again.
3944            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3945        }
3946
3947        // Only need to do this if user is initialized. Otherwise it's a new user
3948        // and there are no processes running as the user yet and there's no need
3949        // to make an expensive call to remount processes for the changed permissions.
3950        if (READ_EXTERNAL_STORAGE.equals(name)
3951                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3952            final long token = Binder.clearCallingIdentity();
3953            try {
3954                if (sUserManager.isInitialized(userId)) {
3955                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3956                            MountServiceInternal.class);
3957                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3958                }
3959            } finally {
3960                Binder.restoreCallingIdentity(token);
3961            }
3962        }
3963    }
3964
3965    @Override
3966    public void revokeRuntimePermission(String packageName, String name, int userId) {
3967        if (!sUserManager.exists(userId)) {
3968            Log.e(TAG, "No such user:" + userId);
3969            return;
3970        }
3971
3972        mContext.enforceCallingOrSelfPermission(
3973                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3974                "revokeRuntimePermission");
3975
3976        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3977                true /* requireFullPermission */, true /* checkShell */,
3978                "revokeRuntimePermission");
3979
3980        final int appId;
3981
3982        synchronized (mPackages) {
3983            final PackageParser.Package pkg = mPackages.get(packageName);
3984            if (pkg == null) {
3985                throw new IllegalArgumentException("Unknown package: " + packageName);
3986            }
3987
3988            final BasePermission bp = mSettings.mPermissions.get(name);
3989            if (bp == null) {
3990                throw new IllegalArgumentException("Unknown permission: " + name);
3991            }
3992
3993            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3994
3995            // If a permission review is required for legacy apps we represent
3996            // their permissions as always granted runtime ones since we need
3997            // to keep the review required permission flag per user while an
3998            // install permission's state is shared across all users.
3999            if (Build.PERMISSIONS_REVIEW_REQUIRED
4000                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4001                    && bp.isRuntime()) {
4002                return;
4003            }
4004
4005            SettingBase sb = (SettingBase) pkg.mExtras;
4006            if (sb == null) {
4007                throw new IllegalArgumentException("Unknown package: " + packageName);
4008            }
4009
4010            final PermissionsState permissionsState = sb.getPermissionsState();
4011
4012            final int flags = permissionsState.getPermissionFlags(name, userId);
4013            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4014                throw new SecurityException("Cannot revoke system fixed permission "
4015                        + name + " for package " + packageName);
4016            }
4017
4018            if (bp.isDevelopment()) {
4019                // Development permissions must be handled specially, since they are not
4020                // normal runtime permissions.  For now they apply to all users.
4021                if (permissionsState.revokeInstallPermission(bp) !=
4022                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4023                    scheduleWriteSettingsLocked();
4024                }
4025                return;
4026            }
4027
4028            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4029                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4030                return;
4031            }
4032
4033            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4034
4035            // Critical, after this call app should never have the permission.
4036            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4037
4038            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4039        }
4040
4041        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4042    }
4043
4044    @Override
4045    public void resetRuntimePermissions() {
4046        mContext.enforceCallingOrSelfPermission(
4047                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4048                "revokeRuntimePermission");
4049
4050        int callingUid = Binder.getCallingUid();
4051        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4052            mContext.enforceCallingOrSelfPermission(
4053                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4054                    "resetRuntimePermissions");
4055        }
4056
4057        synchronized (mPackages) {
4058            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4059            for (int userId : UserManagerService.getInstance().getUserIds()) {
4060                final int packageCount = mPackages.size();
4061                for (int i = 0; i < packageCount; i++) {
4062                    PackageParser.Package pkg = mPackages.valueAt(i);
4063                    if (!(pkg.mExtras instanceof PackageSetting)) {
4064                        continue;
4065                    }
4066                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4067                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4068                }
4069            }
4070        }
4071    }
4072
4073    @Override
4074    public int getPermissionFlags(String name, String packageName, int userId) {
4075        if (!sUserManager.exists(userId)) {
4076            return 0;
4077        }
4078
4079        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4080
4081        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4082                true /* requireFullPermission */, false /* checkShell */,
4083                "getPermissionFlags");
4084
4085        synchronized (mPackages) {
4086            final PackageParser.Package pkg = mPackages.get(packageName);
4087            if (pkg == null) {
4088                throw new IllegalArgumentException("Unknown package: " + packageName);
4089            }
4090
4091            final BasePermission bp = mSettings.mPermissions.get(name);
4092            if (bp == null) {
4093                throw new IllegalArgumentException("Unknown permission: " + name);
4094            }
4095
4096            SettingBase sb = (SettingBase) pkg.mExtras;
4097            if (sb == null) {
4098                throw new IllegalArgumentException("Unknown package: " + packageName);
4099            }
4100
4101            PermissionsState permissionsState = sb.getPermissionsState();
4102            return permissionsState.getPermissionFlags(name, userId);
4103        }
4104    }
4105
4106    @Override
4107    public void updatePermissionFlags(String name, String packageName, int flagMask,
4108            int flagValues, int userId) {
4109        if (!sUserManager.exists(userId)) {
4110            return;
4111        }
4112
4113        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4114
4115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4116                true /* requireFullPermission */, true /* checkShell */,
4117                "updatePermissionFlags");
4118
4119        // Only the system can change these flags and nothing else.
4120        if (getCallingUid() != Process.SYSTEM_UID) {
4121            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4122            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4123            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4124            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4125            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4126        }
4127
4128        synchronized (mPackages) {
4129            final PackageParser.Package pkg = mPackages.get(packageName);
4130            if (pkg == null) {
4131                throw new IllegalArgumentException("Unknown package: " + packageName);
4132            }
4133
4134            final BasePermission bp = mSettings.mPermissions.get(name);
4135            if (bp == null) {
4136                throw new IllegalArgumentException("Unknown permission: " + name);
4137            }
4138
4139            SettingBase sb = (SettingBase) pkg.mExtras;
4140            if (sb == null) {
4141                throw new IllegalArgumentException("Unknown package: " + packageName);
4142            }
4143
4144            PermissionsState permissionsState = sb.getPermissionsState();
4145
4146            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4147
4148            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4149                // Install and runtime permissions are stored in different places,
4150                // so figure out what permission changed and persist the change.
4151                if (permissionsState.getInstallPermissionState(name) != null) {
4152                    scheduleWriteSettingsLocked();
4153                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4154                        || hadState) {
4155                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4156                }
4157            }
4158        }
4159    }
4160
4161    /**
4162     * Update the permission flags for all packages and runtime permissions of a user in order
4163     * to allow device or profile owner to remove POLICY_FIXED.
4164     */
4165    @Override
4166    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4167        if (!sUserManager.exists(userId)) {
4168            return;
4169        }
4170
4171        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4172
4173        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4174                true /* requireFullPermission */, true /* checkShell */,
4175                "updatePermissionFlagsForAllApps");
4176
4177        // Only the system can change system fixed flags.
4178        if (getCallingUid() != Process.SYSTEM_UID) {
4179            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4180            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4181        }
4182
4183        synchronized (mPackages) {
4184            boolean changed = false;
4185            final int packageCount = mPackages.size();
4186            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4187                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4188                SettingBase sb = (SettingBase) pkg.mExtras;
4189                if (sb == null) {
4190                    continue;
4191                }
4192                PermissionsState permissionsState = sb.getPermissionsState();
4193                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4194                        userId, flagMask, flagValues);
4195            }
4196            if (changed) {
4197                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4198            }
4199        }
4200    }
4201
4202    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4203        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4204                != PackageManager.PERMISSION_GRANTED
4205            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4206                != PackageManager.PERMISSION_GRANTED) {
4207            throw new SecurityException(message + " requires "
4208                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4209                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4210        }
4211    }
4212
4213    @Override
4214    public boolean shouldShowRequestPermissionRationale(String permissionName,
4215            String packageName, int userId) {
4216        if (UserHandle.getCallingUserId() != userId) {
4217            mContext.enforceCallingPermission(
4218                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4219                    "canShowRequestPermissionRationale for user " + userId);
4220        }
4221
4222        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4223        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4224            return false;
4225        }
4226
4227        if (checkPermission(permissionName, packageName, userId)
4228                == PackageManager.PERMISSION_GRANTED) {
4229            return false;
4230        }
4231
4232        final int flags;
4233
4234        final long identity = Binder.clearCallingIdentity();
4235        try {
4236            flags = getPermissionFlags(permissionName,
4237                    packageName, userId);
4238        } finally {
4239            Binder.restoreCallingIdentity(identity);
4240        }
4241
4242        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4243                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4244                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4245
4246        if ((flags & fixedFlags) != 0) {
4247            return false;
4248        }
4249
4250        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4251    }
4252
4253    @Override
4254    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4255        mContext.enforceCallingOrSelfPermission(
4256                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4257                "addOnPermissionsChangeListener");
4258
4259        synchronized (mPackages) {
4260            mOnPermissionChangeListeners.addListenerLocked(listener);
4261        }
4262    }
4263
4264    @Override
4265    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4266        synchronized (mPackages) {
4267            mOnPermissionChangeListeners.removeListenerLocked(listener);
4268        }
4269    }
4270
4271    @Override
4272    public boolean isProtectedBroadcast(String actionName) {
4273        synchronized (mPackages) {
4274            if (mProtectedBroadcasts.contains(actionName)) {
4275                return true;
4276            } else if (actionName != null) {
4277                // TODO: remove these terrible hacks
4278                if (actionName.startsWith("android.net.netmon.lingerExpired")
4279                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4280                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4281                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4282                    return true;
4283                }
4284            }
4285        }
4286        return false;
4287    }
4288
4289    @Override
4290    public int checkSignatures(String pkg1, String pkg2) {
4291        synchronized (mPackages) {
4292            final PackageParser.Package p1 = mPackages.get(pkg1);
4293            final PackageParser.Package p2 = mPackages.get(pkg2);
4294            if (p1 == null || p1.mExtras == null
4295                    || p2 == null || p2.mExtras == null) {
4296                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4297            }
4298            return compareSignatures(p1.mSignatures, p2.mSignatures);
4299        }
4300    }
4301
4302    @Override
4303    public int checkUidSignatures(int uid1, int uid2) {
4304        // Map to base uids.
4305        uid1 = UserHandle.getAppId(uid1);
4306        uid2 = UserHandle.getAppId(uid2);
4307        // reader
4308        synchronized (mPackages) {
4309            Signature[] s1;
4310            Signature[] s2;
4311            Object obj = mSettings.getUserIdLPr(uid1);
4312            if (obj != null) {
4313                if (obj instanceof SharedUserSetting) {
4314                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4315                } else if (obj instanceof PackageSetting) {
4316                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4317                } else {
4318                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4319                }
4320            } else {
4321                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4322            }
4323            obj = mSettings.getUserIdLPr(uid2);
4324            if (obj != null) {
4325                if (obj instanceof SharedUserSetting) {
4326                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4327                } else if (obj instanceof PackageSetting) {
4328                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4329                } else {
4330                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4331                }
4332            } else {
4333                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4334            }
4335            return compareSignatures(s1, s2);
4336        }
4337    }
4338
4339    private void killUid(int appId, int userId, String reason) {
4340        final long identity = Binder.clearCallingIdentity();
4341        try {
4342            IActivityManager am = ActivityManagerNative.getDefault();
4343            if (am != null) {
4344                try {
4345                    am.killUid(appId, userId, reason);
4346                } catch (RemoteException e) {
4347                    /* ignore - same process */
4348                }
4349            }
4350        } finally {
4351            Binder.restoreCallingIdentity(identity);
4352        }
4353    }
4354
4355    /**
4356     * Compares two sets of signatures. Returns:
4357     * <br />
4358     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4359     * <br />
4360     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4361     * <br />
4362     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4363     * <br />
4364     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4365     * <br />
4366     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4367     */
4368    static int compareSignatures(Signature[] s1, Signature[] s2) {
4369        if (s1 == null) {
4370            return s2 == null
4371                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4372                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4373        }
4374
4375        if (s2 == null) {
4376            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4377        }
4378
4379        if (s1.length != s2.length) {
4380            return PackageManager.SIGNATURE_NO_MATCH;
4381        }
4382
4383        // Since both signature sets are of size 1, we can compare without HashSets.
4384        if (s1.length == 1) {
4385            return s1[0].equals(s2[0]) ?
4386                    PackageManager.SIGNATURE_MATCH :
4387                    PackageManager.SIGNATURE_NO_MATCH;
4388        }
4389
4390        ArraySet<Signature> set1 = new ArraySet<Signature>();
4391        for (Signature sig : s1) {
4392            set1.add(sig);
4393        }
4394        ArraySet<Signature> set2 = new ArraySet<Signature>();
4395        for (Signature sig : s2) {
4396            set2.add(sig);
4397        }
4398        // Make sure s2 contains all signatures in s1.
4399        if (set1.equals(set2)) {
4400            return PackageManager.SIGNATURE_MATCH;
4401        }
4402        return PackageManager.SIGNATURE_NO_MATCH;
4403    }
4404
4405    /**
4406     * If the database version for this type of package (internal storage or
4407     * external storage) is less than the version where package signatures
4408     * were updated, return true.
4409     */
4410    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4411        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4412        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4413    }
4414
4415    /**
4416     * Used for backward compatibility to make sure any packages with
4417     * certificate chains get upgraded to the new style. {@code existingSigs}
4418     * will be in the old format (since they were stored on disk from before the
4419     * system upgrade) and {@code scannedSigs} will be in the newer format.
4420     */
4421    private int compareSignaturesCompat(PackageSignatures existingSigs,
4422            PackageParser.Package scannedPkg) {
4423        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4424            return PackageManager.SIGNATURE_NO_MATCH;
4425        }
4426
4427        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4428        for (Signature sig : existingSigs.mSignatures) {
4429            existingSet.add(sig);
4430        }
4431        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4432        for (Signature sig : scannedPkg.mSignatures) {
4433            try {
4434                Signature[] chainSignatures = sig.getChainSignatures();
4435                for (Signature chainSig : chainSignatures) {
4436                    scannedCompatSet.add(chainSig);
4437                }
4438            } catch (CertificateEncodingException e) {
4439                scannedCompatSet.add(sig);
4440            }
4441        }
4442        /*
4443         * Make sure the expanded scanned set contains all signatures in the
4444         * existing one.
4445         */
4446        if (scannedCompatSet.equals(existingSet)) {
4447            // Migrate the old signatures to the new scheme.
4448            existingSigs.assignSignatures(scannedPkg.mSignatures);
4449            // The new KeySets will be re-added later in the scanning process.
4450            synchronized (mPackages) {
4451                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4452            }
4453            return PackageManager.SIGNATURE_MATCH;
4454        }
4455        return PackageManager.SIGNATURE_NO_MATCH;
4456    }
4457
4458    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4459        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4460        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4461    }
4462
4463    private int compareSignaturesRecover(PackageSignatures existingSigs,
4464            PackageParser.Package scannedPkg) {
4465        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4466            return PackageManager.SIGNATURE_NO_MATCH;
4467        }
4468
4469        String msg = null;
4470        try {
4471            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4472                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4473                        + scannedPkg.packageName);
4474                return PackageManager.SIGNATURE_MATCH;
4475            }
4476        } catch (CertificateException e) {
4477            msg = e.getMessage();
4478        }
4479
4480        logCriticalInfo(Log.INFO,
4481                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4482        return PackageManager.SIGNATURE_NO_MATCH;
4483    }
4484
4485    @Override
4486    public List<String> getAllPackages() {
4487        synchronized (mPackages) {
4488            return new ArrayList<String>(mPackages.keySet());
4489        }
4490    }
4491
4492    @Override
4493    public String[] getPackagesForUid(int uid) {
4494        uid = UserHandle.getAppId(uid);
4495        // reader
4496        synchronized (mPackages) {
4497            Object obj = mSettings.getUserIdLPr(uid);
4498            if (obj instanceof SharedUserSetting) {
4499                final SharedUserSetting sus = (SharedUserSetting) obj;
4500                final int N = sus.packages.size();
4501                final String[] res = new String[N];
4502                final Iterator<PackageSetting> it = sus.packages.iterator();
4503                int i = 0;
4504                while (it.hasNext()) {
4505                    res[i++] = it.next().name;
4506                }
4507                return res;
4508            } else if (obj instanceof PackageSetting) {
4509                final PackageSetting ps = (PackageSetting) obj;
4510                return new String[] { ps.name };
4511            }
4512        }
4513        return null;
4514    }
4515
4516    @Override
4517    public String getNameForUid(int uid) {
4518        // reader
4519        synchronized (mPackages) {
4520            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4521            if (obj instanceof SharedUserSetting) {
4522                final SharedUserSetting sus = (SharedUserSetting) obj;
4523                return sus.name + ":" + sus.userId;
4524            } else if (obj instanceof PackageSetting) {
4525                final PackageSetting ps = (PackageSetting) obj;
4526                return ps.name;
4527            }
4528        }
4529        return null;
4530    }
4531
4532    @Override
4533    public int getUidForSharedUser(String sharedUserName) {
4534        if(sharedUserName == null) {
4535            return -1;
4536        }
4537        // reader
4538        synchronized (mPackages) {
4539            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4540            if (suid == null) {
4541                return -1;
4542            }
4543            return suid.userId;
4544        }
4545    }
4546
4547    @Override
4548    public int getFlagsForUid(int uid) {
4549        synchronized (mPackages) {
4550            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4551            if (obj instanceof SharedUserSetting) {
4552                final SharedUserSetting sus = (SharedUserSetting) obj;
4553                return sus.pkgFlags;
4554            } else if (obj instanceof PackageSetting) {
4555                final PackageSetting ps = (PackageSetting) obj;
4556                return ps.pkgFlags;
4557            }
4558        }
4559        return 0;
4560    }
4561
4562    @Override
4563    public int getPrivateFlagsForUid(int uid) {
4564        synchronized (mPackages) {
4565            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4566            if (obj instanceof SharedUserSetting) {
4567                final SharedUserSetting sus = (SharedUserSetting) obj;
4568                return sus.pkgPrivateFlags;
4569            } else if (obj instanceof PackageSetting) {
4570                final PackageSetting ps = (PackageSetting) obj;
4571                return ps.pkgPrivateFlags;
4572            }
4573        }
4574        return 0;
4575    }
4576
4577    @Override
4578    public boolean isUidPrivileged(int uid) {
4579        uid = UserHandle.getAppId(uid);
4580        // reader
4581        synchronized (mPackages) {
4582            Object obj = mSettings.getUserIdLPr(uid);
4583            if (obj instanceof SharedUserSetting) {
4584                final SharedUserSetting sus = (SharedUserSetting) obj;
4585                final Iterator<PackageSetting> it = sus.packages.iterator();
4586                while (it.hasNext()) {
4587                    if (it.next().isPrivileged()) {
4588                        return true;
4589                    }
4590                }
4591            } else if (obj instanceof PackageSetting) {
4592                final PackageSetting ps = (PackageSetting) obj;
4593                return ps.isPrivileged();
4594            }
4595        }
4596        return false;
4597    }
4598
4599    @Override
4600    public String[] getAppOpPermissionPackages(String permissionName) {
4601        synchronized (mPackages) {
4602            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4603            if (pkgs == null) {
4604                return null;
4605            }
4606            return pkgs.toArray(new String[pkgs.size()]);
4607        }
4608    }
4609
4610    @Override
4611    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4612            int flags, int userId) {
4613        if (!sUserManager.exists(userId)) return null;
4614        flags = updateFlagsForResolve(flags, userId, intent);
4615        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4616                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4617        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4618                userId);
4619        final ResolveInfo bestChoice =
4620                chooseBestActivity(intent, resolvedType, flags, query, userId);
4621
4622        if (isEphemeralAllowed(intent, query, userId)) {
4623            final EphemeralResolveInfo ai =
4624                    getEphemeralResolveInfo(intent, resolvedType, userId);
4625            if (ai != null) {
4626                if (DEBUG_EPHEMERAL) {
4627                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4628                }
4629                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4630                bestChoice.ephemeralResolveInfo = ai;
4631            }
4632        }
4633        return bestChoice;
4634    }
4635
4636    @Override
4637    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4638            IntentFilter filter, int match, ComponentName activity) {
4639        final int userId = UserHandle.getCallingUserId();
4640        if (DEBUG_PREFERRED) {
4641            Log.v(TAG, "setLastChosenActivity intent=" + intent
4642                + " resolvedType=" + resolvedType
4643                + " flags=" + flags
4644                + " filter=" + filter
4645                + " match=" + match
4646                + " activity=" + activity);
4647            filter.dump(new PrintStreamPrinter(System.out), "    ");
4648        }
4649        intent.setComponent(null);
4650        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4651                userId);
4652        // Find any earlier preferred or last chosen entries and nuke them
4653        findPreferredActivity(intent, resolvedType,
4654                flags, query, 0, false, true, false, userId);
4655        // Add the new activity as the last chosen for this filter
4656        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4657                "Setting last chosen");
4658    }
4659
4660    @Override
4661    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4662        final int userId = UserHandle.getCallingUserId();
4663        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4664        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4665                userId);
4666        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4667                false, false, false, userId);
4668    }
4669
4670
4671    private boolean isEphemeralAllowed(
4672            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4673        // Short circuit and return early if possible.
4674        if (DISABLE_EPHEMERAL_APPS) {
4675            return false;
4676        }
4677        final int callingUser = UserHandle.getCallingUserId();
4678        if (callingUser != UserHandle.USER_SYSTEM) {
4679            return false;
4680        }
4681        if (mEphemeralResolverConnection == null) {
4682            return false;
4683        }
4684        if (intent.getComponent() != null) {
4685            return false;
4686        }
4687        if (intent.getPackage() != null) {
4688            return false;
4689        }
4690        final boolean isWebUri = hasWebURI(intent);
4691        if (!isWebUri) {
4692            return false;
4693        }
4694        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4695        synchronized (mPackages) {
4696            final int count = resolvedActivites.size();
4697            for (int n = 0; n < count; n++) {
4698                ResolveInfo info = resolvedActivites.get(n);
4699                String packageName = info.activityInfo.packageName;
4700                PackageSetting ps = mSettings.mPackages.get(packageName);
4701                if (ps != null) {
4702                    // Try to get the status from User settings first
4703                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4704                    int status = (int) (packedStatus >> 32);
4705                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4706                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4707                        if (DEBUG_EPHEMERAL) {
4708                            Slog.v(TAG, "DENY ephemeral apps;"
4709                                + " pkg: " + packageName + ", status: " + status);
4710                        }
4711                        return false;
4712                    }
4713                }
4714            }
4715        }
4716        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4717        return true;
4718    }
4719
4720    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4721            int userId) {
4722        MessageDigest digest = null;
4723        try {
4724            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4725        } catch (NoSuchAlgorithmException e) {
4726            // If we can't create a digest, ignore ephemeral apps.
4727            return null;
4728        }
4729
4730        final byte[] hostBytes = intent.getData().getHost().getBytes();
4731        final byte[] digestBytes = digest.digest(hostBytes);
4732        int shaPrefix =
4733                digestBytes[0] << 24
4734                | digestBytes[1] << 16
4735                | digestBytes[2] << 8
4736                | digestBytes[3] << 0;
4737        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4738                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4739        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4740            // No hash prefix match; there are no ephemeral apps for this domain.
4741            return null;
4742        }
4743        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4744            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4745            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4746                continue;
4747            }
4748            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4749            // No filters; this should never happen.
4750            if (filters.isEmpty()) {
4751                continue;
4752            }
4753            // We have a domain match; resolve the filters to see if anything matches.
4754            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4755            for (int j = filters.size() - 1; j >= 0; --j) {
4756                final EphemeralResolveIntentInfo intentInfo =
4757                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4758                ephemeralResolver.addFilter(intentInfo);
4759            }
4760            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4761                    intent, resolvedType, false /*defaultOnly*/, userId);
4762            if (!matchedResolveInfoList.isEmpty()) {
4763                return matchedResolveInfoList.get(0);
4764            }
4765        }
4766        // Hash or filter mis-match; no ephemeral apps for this domain.
4767        return null;
4768    }
4769
4770    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4771            int flags, List<ResolveInfo> query, int userId) {
4772        if (query != null) {
4773            final int N = query.size();
4774            if (N == 1) {
4775                return query.get(0);
4776            } else if (N > 1) {
4777                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4778                // If there is more than one activity with the same priority,
4779                // then let the user decide between them.
4780                ResolveInfo r0 = query.get(0);
4781                ResolveInfo r1 = query.get(1);
4782                if (DEBUG_INTENT_MATCHING || debug) {
4783                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4784                            + r1.activityInfo.name + "=" + r1.priority);
4785                }
4786                // If the first activity has a higher priority, or a different
4787                // default, then it is always desirable to pick it.
4788                if (r0.priority != r1.priority
4789                        || r0.preferredOrder != r1.preferredOrder
4790                        || r0.isDefault != r1.isDefault) {
4791                    return query.get(0);
4792                }
4793                // If we have saved a preference for a preferred activity for
4794                // this Intent, use that.
4795                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4796                        flags, query, r0.priority, true, false, debug, userId);
4797                if (ri != null) {
4798                    return ri;
4799                }
4800                ri = new ResolveInfo(mResolveInfo);
4801                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4802                ri.activityInfo.applicationInfo = new ApplicationInfo(
4803                        ri.activityInfo.applicationInfo);
4804                if (userId != 0) {
4805                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4806                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4807                }
4808                // Make sure that the resolver is displayable in car mode
4809                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4810                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4811                return ri;
4812            }
4813        }
4814        return null;
4815    }
4816
4817    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4818            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4819        final int N = query.size();
4820        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4821                .get(userId);
4822        // Get the list of persistent preferred activities that handle the intent
4823        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4824        List<PersistentPreferredActivity> pprefs = ppir != null
4825                ? ppir.queryIntent(intent, resolvedType,
4826                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4827                : null;
4828        if (pprefs != null && pprefs.size() > 0) {
4829            final int M = pprefs.size();
4830            for (int i=0; i<M; i++) {
4831                final PersistentPreferredActivity ppa = pprefs.get(i);
4832                if (DEBUG_PREFERRED || debug) {
4833                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4834                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4835                            + "\n  component=" + ppa.mComponent);
4836                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4837                }
4838                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4839                        flags | MATCH_DISABLED_COMPONENTS, userId);
4840                if (DEBUG_PREFERRED || debug) {
4841                    Slog.v(TAG, "Found persistent preferred activity:");
4842                    if (ai != null) {
4843                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4844                    } else {
4845                        Slog.v(TAG, "  null");
4846                    }
4847                }
4848                if (ai == null) {
4849                    // This previously registered persistent preferred activity
4850                    // component is no longer known. Ignore it and do NOT remove it.
4851                    continue;
4852                }
4853                for (int j=0; j<N; j++) {
4854                    final ResolveInfo ri = query.get(j);
4855                    if (!ri.activityInfo.applicationInfo.packageName
4856                            .equals(ai.applicationInfo.packageName)) {
4857                        continue;
4858                    }
4859                    if (!ri.activityInfo.name.equals(ai.name)) {
4860                        continue;
4861                    }
4862                    //  Found a persistent preference that can handle the intent.
4863                    if (DEBUG_PREFERRED || debug) {
4864                        Slog.v(TAG, "Returning persistent preferred activity: " +
4865                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4866                    }
4867                    return ri;
4868                }
4869            }
4870        }
4871        return null;
4872    }
4873
4874    // TODO: handle preferred activities missing while user has amnesia
4875    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4876            List<ResolveInfo> query, int priority, boolean always,
4877            boolean removeMatches, boolean debug, int userId) {
4878        if (!sUserManager.exists(userId)) return null;
4879        flags = updateFlagsForResolve(flags, userId, intent);
4880        // writer
4881        synchronized (mPackages) {
4882            if (intent.getSelector() != null) {
4883                intent = intent.getSelector();
4884            }
4885            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4886
4887            // Try to find a matching persistent preferred activity.
4888            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4889                    debug, userId);
4890
4891            // If a persistent preferred activity matched, use it.
4892            if (pri != null) {
4893                return pri;
4894            }
4895
4896            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4897            // Get the list of preferred activities that handle the intent
4898            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4899            List<PreferredActivity> prefs = pir != null
4900                    ? pir.queryIntent(intent, resolvedType,
4901                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4902                    : null;
4903            if (prefs != null && prefs.size() > 0) {
4904                boolean changed = false;
4905                try {
4906                    // First figure out how good the original match set is.
4907                    // We will only allow preferred activities that came
4908                    // from the same match quality.
4909                    int match = 0;
4910
4911                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4912
4913                    final int N = query.size();
4914                    for (int j=0; j<N; j++) {
4915                        final ResolveInfo ri = query.get(j);
4916                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4917                                + ": 0x" + Integer.toHexString(match));
4918                        if (ri.match > match) {
4919                            match = ri.match;
4920                        }
4921                    }
4922
4923                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4924                            + Integer.toHexString(match));
4925
4926                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4927                    final int M = prefs.size();
4928                    for (int i=0; i<M; i++) {
4929                        final PreferredActivity pa = prefs.get(i);
4930                        if (DEBUG_PREFERRED || debug) {
4931                            Slog.v(TAG, "Checking PreferredActivity ds="
4932                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4933                                    + "\n  component=" + pa.mPref.mComponent);
4934                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4935                        }
4936                        if (pa.mPref.mMatch != match) {
4937                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4938                                    + Integer.toHexString(pa.mPref.mMatch));
4939                            continue;
4940                        }
4941                        // If it's not an "always" type preferred activity and that's what we're
4942                        // looking for, skip it.
4943                        if (always && !pa.mPref.mAlways) {
4944                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4945                            continue;
4946                        }
4947                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4948                                flags | MATCH_DISABLED_COMPONENTS, userId);
4949                        if (DEBUG_PREFERRED || debug) {
4950                            Slog.v(TAG, "Found preferred activity:");
4951                            if (ai != null) {
4952                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4953                            } else {
4954                                Slog.v(TAG, "  null");
4955                            }
4956                        }
4957                        if (ai == null) {
4958                            // This previously registered preferred activity
4959                            // component is no longer known.  Most likely an update
4960                            // to the app was installed and in the new version this
4961                            // component no longer exists.  Clean it up by removing
4962                            // it from the preferred activities list, and skip it.
4963                            Slog.w(TAG, "Removing dangling preferred activity: "
4964                                    + pa.mPref.mComponent);
4965                            pir.removeFilter(pa);
4966                            changed = true;
4967                            continue;
4968                        }
4969                        for (int j=0; j<N; j++) {
4970                            final ResolveInfo ri = query.get(j);
4971                            if (!ri.activityInfo.applicationInfo.packageName
4972                                    .equals(ai.applicationInfo.packageName)) {
4973                                continue;
4974                            }
4975                            if (!ri.activityInfo.name.equals(ai.name)) {
4976                                continue;
4977                            }
4978
4979                            if (removeMatches) {
4980                                pir.removeFilter(pa);
4981                                changed = true;
4982                                if (DEBUG_PREFERRED) {
4983                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4984                                }
4985                                break;
4986                            }
4987
4988                            // Okay we found a previously set preferred or last chosen app.
4989                            // If the result set is different from when this
4990                            // was created, we need to clear it and re-ask the
4991                            // user their preference, if we're looking for an "always" type entry.
4992                            if (always && !pa.mPref.sameSet(query)) {
4993                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4994                                        + intent + " type " + resolvedType);
4995                                if (DEBUG_PREFERRED) {
4996                                    Slog.v(TAG, "Removing preferred activity since set changed "
4997                                            + pa.mPref.mComponent);
4998                                }
4999                                pir.removeFilter(pa);
5000                                // Re-add the filter as a "last chosen" entry (!always)
5001                                PreferredActivity lastChosen = new PreferredActivity(
5002                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5003                                pir.addFilter(lastChosen);
5004                                changed = true;
5005                                return null;
5006                            }
5007
5008                            // Yay! Either the set matched or we're looking for the last chosen
5009                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5010                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5011                            return ri;
5012                        }
5013                    }
5014                } finally {
5015                    if (changed) {
5016                        if (DEBUG_PREFERRED) {
5017                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5018                        }
5019                        scheduleWritePackageRestrictionsLocked(userId);
5020                    }
5021                }
5022            }
5023        }
5024        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5025        return null;
5026    }
5027
5028    /*
5029     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5030     */
5031    @Override
5032    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5033            int targetUserId) {
5034        mContext.enforceCallingOrSelfPermission(
5035                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5036        List<CrossProfileIntentFilter> matches =
5037                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5038        if (matches != null) {
5039            int size = matches.size();
5040            for (int i = 0; i < size; i++) {
5041                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5042            }
5043        }
5044        if (hasWebURI(intent)) {
5045            // cross-profile app linking works only towards the parent.
5046            final UserInfo parent = getProfileParent(sourceUserId);
5047            synchronized(mPackages) {
5048                int flags = updateFlagsForResolve(0, parent.id, intent);
5049                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5050                        intent, resolvedType, flags, sourceUserId, parent.id);
5051                return xpDomainInfo != null;
5052            }
5053        }
5054        return false;
5055    }
5056
5057    private UserInfo getProfileParent(int userId) {
5058        final long identity = Binder.clearCallingIdentity();
5059        try {
5060            return sUserManager.getProfileParent(userId);
5061        } finally {
5062            Binder.restoreCallingIdentity(identity);
5063        }
5064    }
5065
5066    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5067            String resolvedType, int userId) {
5068        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5069        if (resolver != null) {
5070            return resolver.queryIntent(intent, resolvedType, false, userId);
5071        }
5072        return null;
5073    }
5074
5075    @Override
5076    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5077            String resolvedType, int flags, int userId) {
5078        return new ParceledListSlice<>(
5079                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5080    }
5081
5082    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5083            String resolvedType, int flags, int userId) {
5084        if (!sUserManager.exists(userId)) return Collections.emptyList();
5085        flags = updateFlagsForResolve(flags, userId, intent);
5086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5087                false /* requireFullPermission */, false /* checkShell */,
5088                "query intent activities");
5089        ComponentName comp = intent.getComponent();
5090        if (comp == null) {
5091            if (intent.getSelector() != null) {
5092                intent = intent.getSelector();
5093                comp = intent.getComponent();
5094            }
5095        }
5096
5097        if (comp != null) {
5098            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5099            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5100            if (ai != null) {
5101                final ResolveInfo ri = new ResolveInfo();
5102                ri.activityInfo = ai;
5103                list.add(ri);
5104            }
5105            return list;
5106        }
5107
5108        // reader
5109        synchronized (mPackages) {
5110            final String pkgName = intent.getPackage();
5111            if (pkgName == null) {
5112                List<CrossProfileIntentFilter> matchingFilters =
5113                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5114                // Check for results that need to skip the current profile.
5115                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5116                        resolvedType, flags, userId);
5117                if (xpResolveInfo != null) {
5118                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5119                    result.add(xpResolveInfo);
5120                    return filterIfNotSystemUser(result, userId);
5121                }
5122
5123                // Check for results in the current profile.
5124                List<ResolveInfo> result = mActivities.queryIntent(
5125                        intent, resolvedType, flags, userId);
5126                result = filterIfNotSystemUser(result, userId);
5127
5128                // Check for cross profile results.
5129                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5130                xpResolveInfo = queryCrossProfileIntents(
5131                        matchingFilters, intent, resolvedType, flags, userId,
5132                        hasNonNegativePriorityResult);
5133                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5134                    boolean isVisibleToUser = filterIfNotSystemUser(
5135                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5136                    if (isVisibleToUser) {
5137                        result.add(xpResolveInfo);
5138                        Collections.sort(result, mResolvePrioritySorter);
5139                    }
5140                }
5141                if (hasWebURI(intent)) {
5142                    CrossProfileDomainInfo xpDomainInfo = null;
5143                    final UserInfo parent = getProfileParent(userId);
5144                    if (parent != null) {
5145                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5146                                flags, userId, parent.id);
5147                    }
5148                    if (xpDomainInfo != null) {
5149                        if (xpResolveInfo != null) {
5150                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5151                            // in the result.
5152                            result.remove(xpResolveInfo);
5153                        }
5154                        if (result.size() == 0) {
5155                            result.add(xpDomainInfo.resolveInfo);
5156                            return result;
5157                        }
5158                    } else if (result.size() <= 1) {
5159                        return result;
5160                    }
5161                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5162                            xpDomainInfo, userId);
5163                    Collections.sort(result, mResolvePrioritySorter);
5164                }
5165                return result;
5166            }
5167            final PackageParser.Package pkg = mPackages.get(pkgName);
5168            if (pkg != null) {
5169                return filterIfNotSystemUser(
5170                        mActivities.queryIntentForPackage(
5171                                intent, resolvedType, flags, pkg.activities, userId),
5172                        userId);
5173            }
5174            return new ArrayList<ResolveInfo>();
5175        }
5176    }
5177
5178    private static class CrossProfileDomainInfo {
5179        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5180        ResolveInfo resolveInfo;
5181        /* Best domain verification status of the activities found in the other profile */
5182        int bestDomainVerificationStatus;
5183    }
5184
5185    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5186            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5187        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5188                sourceUserId)) {
5189            return null;
5190        }
5191        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5192                resolvedType, flags, parentUserId);
5193
5194        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5195            return null;
5196        }
5197        CrossProfileDomainInfo result = null;
5198        int size = resultTargetUser.size();
5199        for (int i = 0; i < size; i++) {
5200            ResolveInfo riTargetUser = resultTargetUser.get(i);
5201            // Intent filter verification is only for filters that specify a host. So don't return
5202            // those that handle all web uris.
5203            if (riTargetUser.handleAllWebDataURI) {
5204                continue;
5205            }
5206            String packageName = riTargetUser.activityInfo.packageName;
5207            PackageSetting ps = mSettings.mPackages.get(packageName);
5208            if (ps == null) {
5209                continue;
5210            }
5211            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5212            int status = (int)(verificationState >> 32);
5213            if (result == null) {
5214                result = new CrossProfileDomainInfo();
5215                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5216                        sourceUserId, parentUserId);
5217                result.bestDomainVerificationStatus = status;
5218            } else {
5219                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5220                        result.bestDomainVerificationStatus);
5221            }
5222        }
5223        // Don't consider matches with status NEVER across profiles.
5224        if (result != null && result.bestDomainVerificationStatus
5225                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5226            return null;
5227        }
5228        return result;
5229    }
5230
5231    /**
5232     * Verification statuses are ordered from the worse to the best, except for
5233     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5234     */
5235    private int bestDomainVerificationStatus(int status1, int status2) {
5236        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5237            return status2;
5238        }
5239        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5240            return status1;
5241        }
5242        return (int) MathUtils.max(status1, status2);
5243    }
5244
5245    private boolean isUserEnabled(int userId) {
5246        long callingId = Binder.clearCallingIdentity();
5247        try {
5248            UserInfo userInfo = sUserManager.getUserInfo(userId);
5249            return userInfo != null && userInfo.isEnabled();
5250        } finally {
5251            Binder.restoreCallingIdentity(callingId);
5252        }
5253    }
5254
5255    /**
5256     * Filter out activities with systemUserOnly flag set, when current user is not System.
5257     *
5258     * @return filtered list
5259     */
5260    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5261        if (userId == UserHandle.USER_SYSTEM) {
5262            return resolveInfos;
5263        }
5264        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5265            ResolveInfo info = resolveInfos.get(i);
5266            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5267                resolveInfos.remove(i);
5268            }
5269        }
5270        return resolveInfos;
5271    }
5272
5273    /**
5274     * @param resolveInfos list of resolve infos in descending priority order
5275     * @return if the list contains a resolve info with non-negative priority
5276     */
5277    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5278        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5279    }
5280
5281    private static boolean hasWebURI(Intent intent) {
5282        if (intent.getData() == null) {
5283            return false;
5284        }
5285        final String scheme = intent.getScheme();
5286        if (TextUtils.isEmpty(scheme)) {
5287            return false;
5288        }
5289        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5290    }
5291
5292    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5293            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5294            int userId) {
5295        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5296
5297        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5298            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5299                    candidates.size());
5300        }
5301
5302        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5303        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5304        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5305        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5306        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5307        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5308
5309        synchronized (mPackages) {
5310            final int count = candidates.size();
5311            // First, try to use linked apps. Partition the candidates into four lists:
5312            // one for the final results, one for the "do not use ever", one for "undefined status"
5313            // and finally one for "browser app type".
5314            for (int n=0; n<count; n++) {
5315                ResolveInfo info = candidates.get(n);
5316                String packageName = info.activityInfo.packageName;
5317                PackageSetting ps = mSettings.mPackages.get(packageName);
5318                if (ps != null) {
5319                    // Add to the special match all list (Browser use case)
5320                    if (info.handleAllWebDataURI) {
5321                        matchAllList.add(info);
5322                        continue;
5323                    }
5324                    // Try to get the status from User settings first
5325                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5326                    int status = (int)(packedStatus >> 32);
5327                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5328                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5329                        if (DEBUG_DOMAIN_VERIFICATION) {
5330                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5331                                    + " : linkgen=" + linkGeneration);
5332                        }
5333                        // Use link-enabled generation as preferredOrder, i.e.
5334                        // prefer newly-enabled over earlier-enabled.
5335                        info.preferredOrder = linkGeneration;
5336                        alwaysList.add(info);
5337                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5338                        if (DEBUG_DOMAIN_VERIFICATION) {
5339                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5340                        }
5341                        neverList.add(info);
5342                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5343                        if (DEBUG_DOMAIN_VERIFICATION) {
5344                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5345                        }
5346                        alwaysAskList.add(info);
5347                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5348                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5349                        if (DEBUG_DOMAIN_VERIFICATION) {
5350                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5351                        }
5352                        undefinedList.add(info);
5353                    }
5354                }
5355            }
5356
5357            // We'll want to include browser possibilities in a few cases
5358            boolean includeBrowser = false;
5359
5360            // First try to add the "always" resolution(s) for the current user, if any
5361            if (alwaysList.size() > 0) {
5362                result.addAll(alwaysList);
5363            } else {
5364                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5365                result.addAll(undefinedList);
5366                // Maybe add one for the other profile.
5367                if (xpDomainInfo != null && (
5368                        xpDomainInfo.bestDomainVerificationStatus
5369                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5370                    result.add(xpDomainInfo.resolveInfo);
5371                }
5372                includeBrowser = true;
5373            }
5374
5375            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5376            // If there were 'always' entries their preferred order has been set, so we also
5377            // back that off to make the alternatives equivalent
5378            if (alwaysAskList.size() > 0) {
5379                for (ResolveInfo i : result) {
5380                    i.preferredOrder = 0;
5381                }
5382                result.addAll(alwaysAskList);
5383                includeBrowser = true;
5384            }
5385
5386            if (includeBrowser) {
5387                // Also add browsers (all of them or only the default one)
5388                if (DEBUG_DOMAIN_VERIFICATION) {
5389                    Slog.v(TAG, "   ...including browsers in candidate set");
5390                }
5391                if ((matchFlags & MATCH_ALL) != 0) {
5392                    result.addAll(matchAllList);
5393                } else {
5394                    // Browser/generic handling case.  If there's a default browser, go straight
5395                    // to that (but only if there is no other higher-priority match).
5396                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5397                    int maxMatchPrio = 0;
5398                    ResolveInfo defaultBrowserMatch = null;
5399                    final int numCandidates = matchAllList.size();
5400                    for (int n = 0; n < numCandidates; n++) {
5401                        ResolveInfo info = matchAllList.get(n);
5402                        // track the highest overall match priority...
5403                        if (info.priority > maxMatchPrio) {
5404                            maxMatchPrio = info.priority;
5405                        }
5406                        // ...and the highest-priority default browser match
5407                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5408                            if (defaultBrowserMatch == null
5409                                    || (defaultBrowserMatch.priority < info.priority)) {
5410                                if (debug) {
5411                                    Slog.v(TAG, "Considering default browser match " + info);
5412                                }
5413                                defaultBrowserMatch = info;
5414                            }
5415                        }
5416                    }
5417                    if (defaultBrowserMatch != null
5418                            && defaultBrowserMatch.priority >= maxMatchPrio
5419                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5420                    {
5421                        if (debug) {
5422                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5423                        }
5424                        result.add(defaultBrowserMatch);
5425                    } else {
5426                        result.addAll(matchAllList);
5427                    }
5428                }
5429
5430                // If there is nothing selected, add all candidates and remove the ones that the user
5431                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5432                if (result.size() == 0) {
5433                    result.addAll(candidates);
5434                    result.removeAll(neverList);
5435                }
5436            }
5437        }
5438        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5439            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5440                    result.size());
5441            for (ResolveInfo info : result) {
5442                Slog.v(TAG, "  + " + info.activityInfo);
5443            }
5444        }
5445        return result;
5446    }
5447
5448    // Returns a packed value as a long:
5449    //
5450    // high 'int'-sized word: link status: undefined/ask/never/always.
5451    // low 'int'-sized word: relative priority among 'always' results.
5452    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5453        long result = ps.getDomainVerificationStatusForUser(userId);
5454        // if none available, get the master status
5455        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5456            if (ps.getIntentFilterVerificationInfo() != null) {
5457                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5458            }
5459        }
5460        return result;
5461    }
5462
5463    private ResolveInfo querySkipCurrentProfileIntents(
5464            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5465            int flags, int sourceUserId) {
5466        if (matchingFilters != null) {
5467            int size = matchingFilters.size();
5468            for (int i = 0; i < size; i ++) {
5469                CrossProfileIntentFilter filter = matchingFilters.get(i);
5470                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5471                    // Checking if there are activities in the target user that can handle the
5472                    // intent.
5473                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5474                            resolvedType, flags, sourceUserId);
5475                    if (resolveInfo != null) {
5476                        return resolveInfo;
5477                    }
5478                }
5479            }
5480        }
5481        return null;
5482    }
5483
5484    // Return matching ResolveInfo in target user if any.
5485    private ResolveInfo queryCrossProfileIntents(
5486            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5487            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5488        if (matchingFilters != null) {
5489            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5490            // match the same intent. For performance reasons, it is better not to
5491            // run queryIntent twice for the same userId
5492            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5493            int size = matchingFilters.size();
5494            for (int i = 0; i < size; i++) {
5495                CrossProfileIntentFilter filter = matchingFilters.get(i);
5496                int targetUserId = filter.getTargetUserId();
5497                boolean skipCurrentProfile =
5498                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5499                boolean skipCurrentProfileIfNoMatchFound =
5500                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5501                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5502                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5503                    // Checking if there are activities in the target user that can handle the
5504                    // intent.
5505                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5506                            resolvedType, flags, sourceUserId);
5507                    if (resolveInfo != null) return resolveInfo;
5508                    alreadyTriedUserIds.put(targetUserId, true);
5509                }
5510            }
5511        }
5512        return null;
5513    }
5514
5515    /**
5516     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5517     * will forward the intent to the filter's target user.
5518     * Otherwise, returns null.
5519     */
5520    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5521            String resolvedType, int flags, int sourceUserId) {
5522        int targetUserId = filter.getTargetUserId();
5523        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5524                resolvedType, flags, targetUserId);
5525        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5526            // If all the matches in the target profile are suspended, return null.
5527            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5528                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5529                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5530                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5531                            targetUserId);
5532                }
5533            }
5534        }
5535        return null;
5536    }
5537
5538    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5539            int sourceUserId, int targetUserId) {
5540        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5541        long ident = Binder.clearCallingIdentity();
5542        boolean targetIsProfile;
5543        try {
5544            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5545        } finally {
5546            Binder.restoreCallingIdentity(ident);
5547        }
5548        String className;
5549        if (targetIsProfile) {
5550            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5551        } else {
5552            className = FORWARD_INTENT_TO_PARENT;
5553        }
5554        ComponentName forwardingActivityComponentName = new ComponentName(
5555                mAndroidApplication.packageName, className);
5556        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5557                sourceUserId);
5558        if (!targetIsProfile) {
5559            forwardingActivityInfo.showUserIcon = targetUserId;
5560            forwardingResolveInfo.noResourceId = true;
5561        }
5562        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5563        forwardingResolveInfo.priority = 0;
5564        forwardingResolveInfo.preferredOrder = 0;
5565        forwardingResolveInfo.match = 0;
5566        forwardingResolveInfo.isDefault = true;
5567        forwardingResolveInfo.filter = filter;
5568        forwardingResolveInfo.targetUserId = targetUserId;
5569        return forwardingResolveInfo;
5570    }
5571
5572    @Override
5573    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5574            Intent[] specifics, String[] specificTypes, Intent intent,
5575            String resolvedType, int flags, int userId) {
5576        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5577                specificTypes, intent, resolvedType, flags, userId));
5578    }
5579
5580    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5581            Intent[] specifics, String[] specificTypes, Intent intent,
5582            String resolvedType, int flags, int userId) {
5583        if (!sUserManager.exists(userId)) return Collections.emptyList();
5584        flags = updateFlagsForResolve(flags, userId, intent);
5585        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5586                false /* requireFullPermission */, false /* checkShell */,
5587                "query intent activity options");
5588        final String resultsAction = intent.getAction();
5589
5590        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5591                | PackageManager.GET_RESOLVED_FILTER, userId);
5592
5593        if (DEBUG_INTENT_MATCHING) {
5594            Log.v(TAG, "Query " + intent + ": " + results);
5595        }
5596
5597        int specificsPos = 0;
5598        int N;
5599
5600        // todo: note that the algorithm used here is O(N^2).  This
5601        // isn't a problem in our current environment, but if we start running
5602        // into situations where we have more than 5 or 10 matches then this
5603        // should probably be changed to something smarter...
5604
5605        // First we go through and resolve each of the specific items
5606        // that were supplied, taking care of removing any corresponding
5607        // duplicate items in the generic resolve list.
5608        if (specifics != null) {
5609            for (int i=0; i<specifics.length; i++) {
5610                final Intent sintent = specifics[i];
5611                if (sintent == null) {
5612                    continue;
5613                }
5614
5615                if (DEBUG_INTENT_MATCHING) {
5616                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5617                }
5618
5619                String action = sintent.getAction();
5620                if (resultsAction != null && resultsAction.equals(action)) {
5621                    // If this action was explicitly requested, then don't
5622                    // remove things that have it.
5623                    action = null;
5624                }
5625
5626                ResolveInfo ri = null;
5627                ActivityInfo ai = null;
5628
5629                ComponentName comp = sintent.getComponent();
5630                if (comp == null) {
5631                    ri = resolveIntent(
5632                        sintent,
5633                        specificTypes != null ? specificTypes[i] : null,
5634                            flags, userId);
5635                    if (ri == null) {
5636                        continue;
5637                    }
5638                    if (ri == mResolveInfo) {
5639                        // ACK!  Must do something better with this.
5640                    }
5641                    ai = ri.activityInfo;
5642                    comp = new ComponentName(ai.applicationInfo.packageName,
5643                            ai.name);
5644                } else {
5645                    ai = getActivityInfo(comp, flags, userId);
5646                    if (ai == null) {
5647                        continue;
5648                    }
5649                }
5650
5651                // Look for any generic query activities that are duplicates
5652                // of this specific one, and remove them from the results.
5653                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5654                N = results.size();
5655                int j;
5656                for (j=specificsPos; j<N; j++) {
5657                    ResolveInfo sri = results.get(j);
5658                    if ((sri.activityInfo.name.equals(comp.getClassName())
5659                            && sri.activityInfo.applicationInfo.packageName.equals(
5660                                    comp.getPackageName()))
5661                        || (action != null && sri.filter.matchAction(action))) {
5662                        results.remove(j);
5663                        if (DEBUG_INTENT_MATCHING) Log.v(
5664                            TAG, "Removing duplicate item from " + j
5665                            + " due to specific " + specificsPos);
5666                        if (ri == null) {
5667                            ri = sri;
5668                        }
5669                        j--;
5670                        N--;
5671                    }
5672                }
5673
5674                // Add this specific item to its proper place.
5675                if (ri == null) {
5676                    ri = new ResolveInfo();
5677                    ri.activityInfo = ai;
5678                }
5679                results.add(specificsPos, ri);
5680                ri.specificIndex = i;
5681                specificsPos++;
5682            }
5683        }
5684
5685        // Now we go through the remaining generic results and remove any
5686        // duplicate actions that are found here.
5687        N = results.size();
5688        for (int i=specificsPos; i<N-1; i++) {
5689            final ResolveInfo rii = results.get(i);
5690            if (rii.filter == null) {
5691                continue;
5692            }
5693
5694            // Iterate over all of the actions of this result's intent
5695            // filter...  typically this should be just one.
5696            final Iterator<String> it = rii.filter.actionsIterator();
5697            if (it == null) {
5698                continue;
5699            }
5700            while (it.hasNext()) {
5701                final String action = it.next();
5702                if (resultsAction != null && resultsAction.equals(action)) {
5703                    // If this action was explicitly requested, then don't
5704                    // remove things that have it.
5705                    continue;
5706                }
5707                for (int j=i+1; j<N; j++) {
5708                    final ResolveInfo rij = results.get(j);
5709                    if (rij.filter != null && rij.filter.hasAction(action)) {
5710                        results.remove(j);
5711                        if (DEBUG_INTENT_MATCHING) Log.v(
5712                            TAG, "Removing duplicate item from " + j
5713                            + " due to action " + action + " at " + i);
5714                        j--;
5715                        N--;
5716                    }
5717                }
5718            }
5719
5720            // If the caller didn't request filter information, drop it now
5721            // so we don't have to marshall/unmarshall it.
5722            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5723                rii.filter = null;
5724            }
5725        }
5726
5727        // Filter out the caller activity if so requested.
5728        if (caller != null) {
5729            N = results.size();
5730            for (int i=0; i<N; i++) {
5731                ActivityInfo ainfo = results.get(i).activityInfo;
5732                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5733                        && caller.getClassName().equals(ainfo.name)) {
5734                    results.remove(i);
5735                    break;
5736                }
5737            }
5738        }
5739
5740        // If the caller didn't request filter information,
5741        // drop them now so we don't have to
5742        // marshall/unmarshall it.
5743        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5744            N = results.size();
5745            for (int i=0; i<N; i++) {
5746                results.get(i).filter = null;
5747            }
5748        }
5749
5750        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5751        return results;
5752    }
5753
5754    @Override
5755    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5756            String resolvedType, int flags, int userId) {
5757        return new ParceledListSlice<>(
5758                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5759    }
5760
5761    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5762            String resolvedType, int flags, int userId) {
5763        if (!sUserManager.exists(userId)) return Collections.emptyList();
5764        flags = updateFlagsForResolve(flags, userId, intent);
5765        ComponentName comp = intent.getComponent();
5766        if (comp == null) {
5767            if (intent.getSelector() != null) {
5768                intent = intent.getSelector();
5769                comp = intent.getComponent();
5770            }
5771        }
5772        if (comp != null) {
5773            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5774            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5775            if (ai != null) {
5776                ResolveInfo ri = new ResolveInfo();
5777                ri.activityInfo = ai;
5778                list.add(ri);
5779            }
5780            return list;
5781        }
5782
5783        // reader
5784        synchronized (mPackages) {
5785            String pkgName = intent.getPackage();
5786            if (pkgName == null) {
5787                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5788            }
5789            final PackageParser.Package pkg = mPackages.get(pkgName);
5790            if (pkg != null) {
5791                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5792                        userId);
5793            }
5794            return Collections.emptyList();
5795        }
5796    }
5797
5798    @Override
5799    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5800        if (!sUserManager.exists(userId)) return null;
5801        flags = updateFlagsForResolve(flags, userId, intent);
5802        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5803        if (query != null) {
5804            if (query.size() >= 1) {
5805                // If there is more than one service with the same priority,
5806                // just arbitrarily pick the first one.
5807                return query.get(0);
5808            }
5809        }
5810        return null;
5811    }
5812
5813    @Override
5814    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5815            String resolvedType, int flags, int userId) {
5816        return new ParceledListSlice<>(
5817                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5818    }
5819
5820    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5821            String resolvedType, int flags, int userId) {
5822        if (!sUserManager.exists(userId)) return Collections.emptyList();
5823        flags = updateFlagsForResolve(flags, userId, intent);
5824        ComponentName comp = intent.getComponent();
5825        if (comp == null) {
5826            if (intent.getSelector() != null) {
5827                intent = intent.getSelector();
5828                comp = intent.getComponent();
5829            }
5830        }
5831        if (comp != null) {
5832            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5833            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5834            if (si != null) {
5835                final ResolveInfo ri = new ResolveInfo();
5836                ri.serviceInfo = si;
5837                list.add(ri);
5838            }
5839            return list;
5840        }
5841
5842        // reader
5843        synchronized (mPackages) {
5844            String pkgName = intent.getPackage();
5845            if (pkgName == null) {
5846                return mServices.queryIntent(intent, resolvedType, flags, userId);
5847            }
5848            final PackageParser.Package pkg = mPackages.get(pkgName);
5849            if (pkg != null) {
5850                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5851                        userId);
5852            }
5853            return Collections.emptyList();
5854        }
5855    }
5856
5857    @Override
5858    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5859            String resolvedType, int flags, int userId) {
5860        return new ParceledListSlice<>(
5861                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5862    }
5863
5864    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5865            Intent intent, String resolvedType, int flags, int userId) {
5866        if (!sUserManager.exists(userId)) return Collections.emptyList();
5867        flags = updateFlagsForResolve(flags, userId, intent);
5868        ComponentName comp = intent.getComponent();
5869        if (comp == null) {
5870            if (intent.getSelector() != null) {
5871                intent = intent.getSelector();
5872                comp = intent.getComponent();
5873            }
5874        }
5875        if (comp != null) {
5876            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5877            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5878            if (pi != null) {
5879                final ResolveInfo ri = new ResolveInfo();
5880                ri.providerInfo = pi;
5881                list.add(ri);
5882            }
5883            return list;
5884        }
5885
5886        // reader
5887        synchronized (mPackages) {
5888            String pkgName = intent.getPackage();
5889            if (pkgName == null) {
5890                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5891            }
5892            final PackageParser.Package pkg = mPackages.get(pkgName);
5893            if (pkg != null) {
5894                return mProviders.queryIntentForPackage(
5895                        intent, resolvedType, flags, pkg.providers, userId);
5896            }
5897            return Collections.emptyList();
5898        }
5899    }
5900
5901    @Override
5902    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5903        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5904        flags = updateFlagsForPackage(flags, userId, null);
5905        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5906        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5907                true /* requireFullPermission */, false /* checkShell */,
5908                "get installed packages");
5909
5910        // writer
5911        synchronized (mPackages) {
5912            ArrayList<PackageInfo> list;
5913            if (listUninstalled) {
5914                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5915                for (PackageSetting ps : mSettings.mPackages.values()) {
5916                    PackageInfo pi;
5917                    if (ps.pkg != null) {
5918                        pi = generatePackageInfo(ps.pkg, flags, userId);
5919                    } else {
5920                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5921                    }
5922                    if (pi != null) {
5923                        list.add(pi);
5924                    }
5925                }
5926            } else {
5927                list = new ArrayList<PackageInfo>(mPackages.size());
5928                for (PackageParser.Package p : mPackages.values()) {
5929                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5930                    if (pi != null) {
5931                        list.add(pi);
5932                    }
5933                }
5934            }
5935
5936            return new ParceledListSlice<PackageInfo>(list);
5937        }
5938    }
5939
5940    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5941            String[] permissions, boolean[] tmp, int flags, int userId) {
5942        int numMatch = 0;
5943        final PermissionsState permissionsState = ps.getPermissionsState();
5944        for (int i=0; i<permissions.length; i++) {
5945            final String permission = permissions[i];
5946            if (permissionsState.hasPermission(permission, userId)) {
5947                tmp[i] = true;
5948                numMatch++;
5949            } else {
5950                tmp[i] = false;
5951            }
5952        }
5953        if (numMatch == 0) {
5954            return;
5955        }
5956        PackageInfo pi;
5957        if (ps.pkg != null) {
5958            pi = generatePackageInfo(ps.pkg, flags, userId);
5959        } else {
5960            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5961        }
5962        // The above might return null in cases of uninstalled apps or install-state
5963        // skew across users/profiles.
5964        if (pi != null) {
5965            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5966                if (numMatch == permissions.length) {
5967                    pi.requestedPermissions = permissions;
5968                } else {
5969                    pi.requestedPermissions = new String[numMatch];
5970                    numMatch = 0;
5971                    for (int i=0; i<permissions.length; i++) {
5972                        if (tmp[i]) {
5973                            pi.requestedPermissions[numMatch] = permissions[i];
5974                            numMatch++;
5975                        }
5976                    }
5977                }
5978            }
5979            list.add(pi);
5980        }
5981    }
5982
5983    @Override
5984    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5985            String[] permissions, int flags, int userId) {
5986        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5987        flags = updateFlagsForPackage(flags, userId, permissions);
5988        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5989
5990        // writer
5991        synchronized (mPackages) {
5992            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5993            boolean[] tmpBools = new boolean[permissions.length];
5994            if (listUninstalled) {
5995                for (PackageSetting ps : mSettings.mPackages.values()) {
5996                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5997                }
5998            } else {
5999                for (PackageParser.Package pkg : mPackages.values()) {
6000                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6001                    if (ps != null) {
6002                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6003                                userId);
6004                    }
6005                }
6006            }
6007
6008            return new ParceledListSlice<PackageInfo>(list);
6009        }
6010    }
6011
6012    @Override
6013    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6014        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6015        flags = updateFlagsForApplication(flags, userId, null);
6016        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6017
6018        // writer
6019        synchronized (mPackages) {
6020            ArrayList<ApplicationInfo> list;
6021            if (listUninstalled) {
6022                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6023                for (PackageSetting ps : mSettings.mPackages.values()) {
6024                    ApplicationInfo ai;
6025                    if (ps.pkg != null) {
6026                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6027                                ps.readUserState(userId), userId);
6028                    } else {
6029                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6030                    }
6031                    if (ai != null) {
6032                        list.add(ai);
6033                    }
6034                }
6035            } else {
6036                list = new ArrayList<ApplicationInfo>(mPackages.size());
6037                for (PackageParser.Package p : mPackages.values()) {
6038                    if (p.mExtras != null) {
6039                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6040                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6041                        if (ai != null) {
6042                            list.add(ai);
6043                        }
6044                    }
6045                }
6046            }
6047
6048            return new ParceledListSlice<ApplicationInfo>(list);
6049        }
6050    }
6051
6052    @Override
6053    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6054        if (DISABLE_EPHEMERAL_APPS) {
6055            return null;
6056        }
6057
6058        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6059                "getEphemeralApplications");
6060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6061                true /* requireFullPermission */, false /* checkShell */,
6062                "getEphemeralApplications");
6063        synchronized (mPackages) {
6064            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6065                    .getEphemeralApplicationsLPw(userId);
6066            if (ephemeralApps != null) {
6067                return new ParceledListSlice<>(ephemeralApps);
6068            }
6069        }
6070        return null;
6071    }
6072
6073    @Override
6074    public boolean isEphemeralApplication(String packageName, int userId) {
6075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6076                true /* requireFullPermission */, false /* checkShell */,
6077                "isEphemeral");
6078        if (DISABLE_EPHEMERAL_APPS) {
6079            return false;
6080        }
6081
6082        if (!isCallerSameApp(packageName)) {
6083            return false;
6084        }
6085        synchronized (mPackages) {
6086            PackageParser.Package pkg = mPackages.get(packageName);
6087            if (pkg != null) {
6088                return pkg.applicationInfo.isEphemeralApp();
6089            }
6090        }
6091        return false;
6092    }
6093
6094    @Override
6095    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6096        if (DISABLE_EPHEMERAL_APPS) {
6097            return null;
6098        }
6099
6100        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6101                true /* requireFullPermission */, false /* checkShell */,
6102                "getCookie");
6103        if (!isCallerSameApp(packageName)) {
6104            return null;
6105        }
6106        synchronized (mPackages) {
6107            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6108                    packageName, userId);
6109        }
6110    }
6111
6112    @Override
6113    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6114        if (DISABLE_EPHEMERAL_APPS) {
6115            return true;
6116        }
6117
6118        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6119                true /* requireFullPermission */, true /* checkShell */,
6120                "setCookie");
6121        if (!isCallerSameApp(packageName)) {
6122            return false;
6123        }
6124        synchronized (mPackages) {
6125            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6126                    packageName, cookie, userId);
6127        }
6128    }
6129
6130    @Override
6131    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6132        if (DISABLE_EPHEMERAL_APPS) {
6133            return null;
6134        }
6135
6136        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6137                "getEphemeralApplicationIcon");
6138        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6139                true /* requireFullPermission */, false /* checkShell */,
6140                "getEphemeralApplicationIcon");
6141        synchronized (mPackages) {
6142            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6143                    packageName, userId);
6144        }
6145    }
6146
6147    private boolean isCallerSameApp(String packageName) {
6148        PackageParser.Package pkg = mPackages.get(packageName);
6149        return pkg != null
6150                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6151    }
6152
6153    @Override
6154    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6155        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6156    }
6157
6158    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6159        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6160
6161        // reader
6162        synchronized (mPackages) {
6163            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6164            final int userId = UserHandle.getCallingUserId();
6165            while (i.hasNext()) {
6166                final PackageParser.Package p = i.next();
6167                if (p.applicationInfo == null) continue;
6168
6169                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6170                        && !p.applicationInfo.isDirectBootAware();
6171                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6172                        && p.applicationInfo.isDirectBootAware();
6173
6174                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6175                        && (!mSafeMode || isSystemApp(p))
6176                        && (matchesUnaware || matchesAware)) {
6177                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6178                    if (ps != null) {
6179                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6180                                ps.readUserState(userId), userId);
6181                        if (ai != null) {
6182                            finalList.add(ai);
6183                        }
6184                    }
6185                }
6186            }
6187        }
6188
6189        return finalList;
6190    }
6191
6192    @Override
6193    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6194        if (!sUserManager.exists(userId)) return null;
6195        flags = updateFlagsForComponent(flags, userId, name);
6196        // reader
6197        synchronized (mPackages) {
6198            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6199            PackageSetting ps = provider != null
6200                    ? mSettings.mPackages.get(provider.owner.packageName)
6201                    : null;
6202            return ps != null
6203                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6204                    ? PackageParser.generateProviderInfo(provider, flags,
6205                            ps.readUserState(userId), userId)
6206                    : null;
6207        }
6208    }
6209
6210    /**
6211     * @deprecated
6212     */
6213    @Deprecated
6214    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6215        // reader
6216        synchronized (mPackages) {
6217            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6218                    .entrySet().iterator();
6219            final int userId = UserHandle.getCallingUserId();
6220            while (i.hasNext()) {
6221                Map.Entry<String, PackageParser.Provider> entry = i.next();
6222                PackageParser.Provider p = entry.getValue();
6223                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6224
6225                if (ps != null && p.syncable
6226                        && (!mSafeMode || (p.info.applicationInfo.flags
6227                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6228                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6229                            ps.readUserState(userId), userId);
6230                    if (info != null) {
6231                        outNames.add(entry.getKey());
6232                        outInfo.add(info);
6233                    }
6234                }
6235            }
6236        }
6237    }
6238
6239    @Override
6240    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6241            int uid, int flags) {
6242        final int userId = processName != null ? UserHandle.getUserId(uid)
6243                : UserHandle.getCallingUserId();
6244        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6245        flags = updateFlagsForComponent(flags, userId, processName);
6246
6247        ArrayList<ProviderInfo> finalList = null;
6248        // reader
6249        synchronized (mPackages) {
6250            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6251            while (i.hasNext()) {
6252                final PackageParser.Provider p = i.next();
6253                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6254                if (ps != null && p.info.authority != null
6255                        && (processName == null
6256                                || (p.info.processName.equals(processName)
6257                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6258                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6259                    if (finalList == null) {
6260                        finalList = new ArrayList<ProviderInfo>(3);
6261                    }
6262                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6263                            ps.readUserState(userId), userId);
6264                    if (info != null) {
6265                        finalList.add(info);
6266                    }
6267                }
6268            }
6269        }
6270
6271        if (finalList != null) {
6272            Collections.sort(finalList, mProviderInitOrderSorter);
6273            return new ParceledListSlice<ProviderInfo>(finalList);
6274        }
6275
6276        return ParceledListSlice.emptyList();
6277    }
6278
6279    @Override
6280    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6281        // reader
6282        synchronized (mPackages) {
6283            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6284            return PackageParser.generateInstrumentationInfo(i, flags);
6285        }
6286    }
6287
6288    @Override
6289    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6290            String targetPackage, int flags) {
6291        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6292    }
6293
6294    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6295            int flags) {
6296        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6297
6298        // reader
6299        synchronized (mPackages) {
6300            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6301            while (i.hasNext()) {
6302                final PackageParser.Instrumentation p = i.next();
6303                if (targetPackage == null
6304                        || targetPackage.equals(p.info.targetPackage)) {
6305                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6306                            flags);
6307                    if (ii != null) {
6308                        finalList.add(ii);
6309                    }
6310                }
6311            }
6312        }
6313
6314        return finalList;
6315    }
6316
6317    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6318        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6319        if (overlays == null) {
6320            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6321            return;
6322        }
6323        for (PackageParser.Package opkg : overlays.values()) {
6324            // Not much to do if idmap fails: we already logged the error
6325            // and we certainly don't want to abort installation of pkg simply
6326            // because an overlay didn't fit properly. For these reasons,
6327            // ignore the return value of createIdmapForPackagePairLI.
6328            createIdmapForPackagePairLI(pkg, opkg);
6329        }
6330    }
6331
6332    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6333            PackageParser.Package opkg) {
6334        if (!opkg.mTrustedOverlay) {
6335            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6336                    opkg.baseCodePath + ": overlay not trusted");
6337            return false;
6338        }
6339        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6340        if (overlaySet == null) {
6341            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6342                    opkg.baseCodePath + " but target package has no known overlays");
6343            return false;
6344        }
6345        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6346        // TODO: generate idmap for split APKs
6347        try {
6348            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6349        } catch (InstallerException e) {
6350            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6351                    + opkg.baseCodePath);
6352            return false;
6353        }
6354        PackageParser.Package[] overlayArray =
6355            overlaySet.values().toArray(new PackageParser.Package[0]);
6356        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6357            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6358                return p1.mOverlayPriority - p2.mOverlayPriority;
6359            }
6360        };
6361        Arrays.sort(overlayArray, cmp);
6362
6363        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6364        int i = 0;
6365        for (PackageParser.Package p : overlayArray) {
6366            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6367        }
6368        return true;
6369    }
6370
6371    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6372        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6373        try {
6374            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6375        } finally {
6376            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6377        }
6378    }
6379
6380    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6381        final File[] files = dir.listFiles();
6382        if (ArrayUtils.isEmpty(files)) {
6383            Log.d(TAG, "No files in app dir " + dir);
6384            return;
6385        }
6386
6387        if (DEBUG_PACKAGE_SCANNING) {
6388            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6389                    + " flags=0x" + Integer.toHexString(parseFlags));
6390        }
6391
6392        for (File file : files) {
6393            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6394                    && !PackageInstallerService.isStageName(file.getName());
6395            if (!isPackage) {
6396                // Ignore entries which are not packages
6397                continue;
6398            }
6399            try {
6400                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6401                        scanFlags, currentTime, null);
6402            } catch (PackageManagerException e) {
6403                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6404
6405                // Delete invalid userdata apps
6406                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6407                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6408                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6409                    removeCodePathLI(file);
6410                }
6411            }
6412        }
6413    }
6414
6415    private static File getSettingsProblemFile() {
6416        File dataDir = Environment.getDataDirectory();
6417        File systemDir = new File(dataDir, "system");
6418        File fname = new File(systemDir, "uiderrors.txt");
6419        return fname;
6420    }
6421
6422    static void reportSettingsProblem(int priority, String msg) {
6423        logCriticalInfo(priority, msg);
6424    }
6425
6426    static void logCriticalInfo(int priority, String msg) {
6427        Slog.println(priority, TAG, msg);
6428        EventLogTags.writePmCriticalInfo(msg);
6429        try {
6430            File fname = getSettingsProblemFile();
6431            FileOutputStream out = new FileOutputStream(fname, true);
6432            PrintWriter pw = new FastPrintWriter(out);
6433            SimpleDateFormat formatter = new SimpleDateFormat();
6434            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6435            pw.println(dateString + ": " + msg);
6436            pw.close();
6437            FileUtils.setPermissions(
6438                    fname.toString(),
6439                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6440                    -1, -1);
6441        } catch (java.io.IOException e) {
6442        }
6443    }
6444
6445    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6446            int parseFlags) throws PackageManagerException {
6447        if (ps != null
6448                && ps.codePath.equals(srcFile)
6449                && ps.timeStamp == srcFile.lastModified()
6450                && !isCompatSignatureUpdateNeeded(pkg)
6451                && !isRecoverSignatureUpdateNeeded(pkg)) {
6452            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6453            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6454            ArraySet<PublicKey> signingKs;
6455            synchronized (mPackages) {
6456                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6457            }
6458            if (ps.signatures.mSignatures != null
6459                    && ps.signatures.mSignatures.length != 0
6460                    && signingKs != null) {
6461                // Optimization: reuse the existing cached certificates
6462                // if the package appears to be unchanged.
6463                pkg.mSignatures = ps.signatures.mSignatures;
6464                pkg.mSigningKeys = signingKs;
6465                return;
6466            }
6467
6468            Slog.w(TAG, "PackageSetting for " + ps.name
6469                    + " is missing signatures.  Collecting certs again to recover them.");
6470        } else {
6471            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6472        }
6473
6474        try {
6475            PackageParser.collectCertificates(pkg, parseFlags);
6476        } catch (PackageParserException e) {
6477            throw PackageManagerException.from(e);
6478        }
6479    }
6480
6481    /**
6482     *  Traces a package scan.
6483     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6484     */
6485    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6486            long currentTime, UserHandle user) throws PackageManagerException {
6487        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6488        try {
6489            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6490        } finally {
6491            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6492        }
6493    }
6494
6495    /**
6496     *  Scans a package and returns the newly parsed package.
6497     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6498     */
6499    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6500            long currentTime, UserHandle user) throws PackageManagerException {
6501        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6502        parseFlags |= mDefParseFlags;
6503        PackageParser pp = new PackageParser();
6504        pp.setSeparateProcesses(mSeparateProcesses);
6505        pp.setOnlyCoreApps(mOnlyCore);
6506        pp.setDisplayMetrics(mMetrics);
6507
6508        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6509            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6510        }
6511
6512        final PackageParser.Package pkg;
6513        try {
6514            pkg = pp.parsePackage(scanFile, parseFlags);
6515        } catch (PackageParserException e) {
6516            throw PackageManagerException.from(e);
6517        }
6518
6519        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6520    }
6521
6522    /**
6523     *  Scans a package and returns the newly parsed package.
6524     *  @throws PackageManagerException on a parse error.
6525     */
6526    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6527            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6528            throws PackageManagerException {
6529        // If the package has children and this is the first dive in the function
6530        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6531        // packages (parent and children) would be successfully scanned before the
6532        // actual scan since scanning mutates internal state and we want to atomically
6533        // install the package and its children.
6534        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6535            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6536                scanFlags |= SCAN_CHECK_ONLY;
6537            }
6538        } else {
6539            scanFlags &= ~SCAN_CHECK_ONLY;
6540        }
6541
6542        // Scan the parent
6543        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6544                scanFlags, currentTime, user);
6545
6546        // Scan the children
6547        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6548        for (int i = 0; i < childCount; i++) {
6549            PackageParser.Package childPackage = pkg.childPackages.get(i);
6550            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6551                    currentTime, user);
6552        }
6553
6554
6555        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6556            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6557        }
6558
6559        return scannedPkg;
6560    }
6561
6562    /**
6563     *  Scans a package and returns the newly parsed package.
6564     *  @throws PackageManagerException on a parse error.
6565     */
6566    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6567            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6568            throws PackageManagerException {
6569        PackageSetting ps = null;
6570        PackageSetting updatedPkg;
6571        // reader
6572        synchronized (mPackages) {
6573            // Look to see if we already know about this package.
6574            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6575            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6576                // This package has been renamed to its original name.  Let's
6577                // use that.
6578                ps = mSettings.peekPackageLPr(oldName);
6579            }
6580            // If there was no original package, see one for the real package name.
6581            if (ps == null) {
6582                ps = mSettings.peekPackageLPr(pkg.packageName);
6583            }
6584            // Check to see if this package could be hiding/updating a system
6585            // package.  Must look for it either under the original or real
6586            // package name depending on our state.
6587            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6588            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6589
6590            // If this is a package we don't know about on the system partition, we
6591            // may need to remove disabled child packages on the system partition
6592            // or may need to not add child packages if the parent apk is updated
6593            // on the data partition and no longer defines this child package.
6594            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6595                // If this is a parent package for an updated system app and this system
6596                // app got an OTA update which no longer defines some of the child packages
6597                // we have to prune them from the disabled system packages.
6598                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6599                if (disabledPs != null) {
6600                    final int scannedChildCount = (pkg.childPackages != null)
6601                            ? pkg.childPackages.size() : 0;
6602                    final int disabledChildCount = disabledPs.childPackageNames != null
6603                            ? disabledPs.childPackageNames.size() : 0;
6604                    for (int i = 0; i < disabledChildCount; i++) {
6605                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6606                        boolean disabledPackageAvailable = false;
6607                        for (int j = 0; j < scannedChildCount; j++) {
6608                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6609                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6610                                disabledPackageAvailable = true;
6611                                break;
6612                            }
6613                         }
6614                         if (!disabledPackageAvailable) {
6615                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6616                         }
6617                    }
6618                }
6619            }
6620        }
6621
6622        boolean updatedPkgBetter = false;
6623        // First check if this is a system package that may involve an update
6624        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6625            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6626            // it needs to drop FLAG_PRIVILEGED.
6627            if (locationIsPrivileged(scanFile)) {
6628                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6629            } else {
6630                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6631            }
6632
6633            if (ps != null && !ps.codePath.equals(scanFile)) {
6634                // The path has changed from what was last scanned...  check the
6635                // version of the new path against what we have stored to determine
6636                // what to do.
6637                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6638                if (pkg.mVersionCode <= ps.versionCode) {
6639                    // The system package has been updated and the code path does not match
6640                    // Ignore entry. Skip it.
6641                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6642                            + " ignored: updated version " + ps.versionCode
6643                            + " better than this " + pkg.mVersionCode);
6644                    if (!updatedPkg.codePath.equals(scanFile)) {
6645                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6646                                + ps.name + " changing from " + updatedPkg.codePathString
6647                                + " to " + scanFile);
6648                        updatedPkg.codePath = scanFile;
6649                        updatedPkg.codePathString = scanFile.toString();
6650                        updatedPkg.resourcePath = scanFile;
6651                        updatedPkg.resourcePathString = scanFile.toString();
6652                    }
6653                    updatedPkg.pkg = pkg;
6654                    updatedPkg.versionCode = pkg.mVersionCode;
6655
6656                    // Update the disabled system child packages to point to the package too.
6657                    final int childCount = updatedPkg.childPackageNames != null
6658                            ? updatedPkg.childPackageNames.size() : 0;
6659                    for (int i = 0; i < childCount; i++) {
6660                        String childPackageName = updatedPkg.childPackageNames.get(i);
6661                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6662                                childPackageName);
6663                        if (updatedChildPkg != null) {
6664                            updatedChildPkg.pkg = pkg;
6665                            updatedChildPkg.versionCode = pkg.mVersionCode;
6666                        }
6667                    }
6668
6669                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6670                            + scanFile + " ignored: updated version " + ps.versionCode
6671                            + " better than this " + pkg.mVersionCode);
6672                } else {
6673                    // The current app on the system partition is better than
6674                    // what we have updated to on the data partition; switch
6675                    // back to the system partition version.
6676                    // At this point, its safely assumed that package installation for
6677                    // apps in system partition will go through. If not there won't be a working
6678                    // version of the app
6679                    // writer
6680                    synchronized (mPackages) {
6681                        // Just remove the loaded entries from package lists.
6682                        mPackages.remove(ps.name);
6683                    }
6684
6685                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6686                            + " reverting from " + ps.codePathString
6687                            + ": new version " + pkg.mVersionCode
6688                            + " better than installed " + ps.versionCode);
6689
6690                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6691                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6692                    synchronized (mInstallLock) {
6693                        args.cleanUpResourcesLI();
6694                    }
6695                    synchronized (mPackages) {
6696                        mSettings.enableSystemPackageLPw(ps.name);
6697                    }
6698                    updatedPkgBetter = true;
6699                }
6700            }
6701        }
6702
6703        if (updatedPkg != null) {
6704            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6705            // initially
6706            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6707
6708            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6709            // flag set initially
6710            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6711                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6712            }
6713        }
6714
6715        // Verify certificates against what was last scanned
6716        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6717
6718        /*
6719         * A new system app appeared, but we already had a non-system one of the
6720         * same name installed earlier.
6721         */
6722        boolean shouldHideSystemApp = false;
6723        if (updatedPkg == null && ps != null
6724                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6725            /*
6726             * Check to make sure the signatures match first. If they don't,
6727             * wipe the installed application and its data.
6728             */
6729            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6730                    != PackageManager.SIGNATURE_MATCH) {
6731                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6732                        + " signatures don't match existing userdata copy; removing");
6733                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6734                ps = null;
6735            } else {
6736                /*
6737                 * If the newly-added system app is an older version than the
6738                 * already installed version, hide it. It will be scanned later
6739                 * and re-added like an update.
6740                 */
6741                if (pkg.mVersionCode <= ps.versionCode) {
6742                    shouldHideSystemApp = true;
6743                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6744                            + " but new version " + pkg.mVersionCode + " better than installed "
6745                            + ps.versionCode + "; hiding system");
6746                } else {
6747                    /*
6748                     * The newly found system app is a newer version that the
6749                     * one previously installed. Simply remove the
6750                     * already-installed application and replace it with our own
6751                     * while keeping the application data.
6752                     */
6753                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6754                            + " reverting from " + ps.codePathString + ": new version "
6755                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6756                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6757                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6758                    synchronized (mInstallLock) {
6759                        args.cleanUpResourcesLI();
6760                    }
6761                }
6762            }
6763        }
6764
6765        // The apk is forward locked (not public) if its code and resources
6766        // are kept in different files. (except for app in either system or
6767        // vendor path).
6768        // TODO grab this value from PackageSettings
6769        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6770            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6771                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6772            }
6773        }
6774
6775        // TODO: extend to support forward-locked splits
6776        String resourcePath = null;
6777        String baseResourcePath = null;
6778        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6779            if (ps != null && ps.resourcePathString != null) {
6780                resourcePath = ps.resourcePathString;
6781                baseResourcePath = ps.resourcePathString;
6782            } else {
6783                // Should not happen at all. Just log an error.
6784                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6785            }
6786        } else {
6787            resourcePath = pkg.codePath;
6788            baseResourcePath = pkg.baseCodePath;
6789        }
6790
6791        // Set application objects path explicitly.
6792        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6793        pkg.setApplicationInfoCodePath(pkg.codePath);
6794        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6795        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6796        pkg.setApplicationInfoResourcePath(resourcePath);
6797        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6798        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6799
6800        // Note that we invoke the following method only if we are about to unpack an application
6801        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6802                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6803
6804        /*
6805         * If the system app should be overridden by a previously installed
6806         * data, hide the system app now and let the /data/app scan pick it up
6807         * again.
6808         */
6809        if (shouldHideSystemApp) {
6810            synchronized (mPackages) {
6811                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6812            }
6813        }
6814
6815        return scannedPkg;
6816    }
6817
6818    private static String fixProcessName(String defProcessName,
6819            String processName, int uid) {
6820        if (processName == null) {
6821            return defProcessName;
6822        }
6823        return processName;
6824    }
6825
6826    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6827            throws PackageManagerException {
6828        if (pkgSetting.signatures.mSignatures != null) {
6829            // Already existing package. Make sure signatures match
6830            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6831                    == PackageManager.SIGNATURE_MATCH;
6832            if (!match) {
6833                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6834                        == PackageManager.SIGNATURE_MATCH;
6835            }
6836            if (!match) {
6837                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6838                        == PackageManager.SIGNATURE_MATCH;
6839            }
6840            if (!match) {
6841                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6842                        + pkg.packageName + " signatures do not match the "
6843                        + "previously installed version; ignoring!");
6844            }
6845        }
6846
6847        // Check for shared user signatures
6848        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6849            // Already existing package. Make sure signatures match
6850            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6851                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6852            if (!match) {
6853                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6854                        == PackageManager.SIGNATURE_MATCH;
6855            }
6856            if (!match) {
6857                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6858                        == PackageManager.SIGNATURE_MATCH;
6859            }
6860            if (!match) {
6861                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6862                        "Package " + pkg.packageName
6863                        + " has no signatures that match those in shared user "
6864                        + pkgSetting.sharedUser.name + "; ignoring!");
6865            }
6866        }
6867    }
6868
6869    /**
6870     * Enforces that only the system UID or root's UID can call a method exposed
6871     * via Binder.
6872     *
6873     * @param message used as message if SecurityException is thrown
6874     * @throws SecurityException if the caller is not system or root
6875     */
6876    private static final void enforceSystemOrRoot(String message) {
6877        final int uid = Binder.getCallingUid();
6878        if (uid != Process.SYSTEM_UID && uid != 0) {
6879            throw new SecurityException(message);
6880        }
6881    }
6882
6883    @Override
6884    public void performFstrimIfNeeded() {
6885        enforceSystemOrRoot("Only the system can request fstrim");
6886
6887        // Before everything else, see whether we need to fstrim.
6888        try {
6889            IMountService ms = PackageHelper.getMountService();
6890            if (ms != null) {
6891                final boolean isUpgrade = isUpgrade();
6892                boolean doTrim = isUpgrade;
6893                if (doTrim) {
6894                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6895                } else {
6896                    final long interval = android.provider.Settings.Global.getLong(
6897                            mContext.getContentResolver(),
6898                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6899                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6900                    if (interval > 0) {
6901                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6902                        if (timeSinceLast > interval) {
6903                            doTrim = true;
6904                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6905                                    + "; running immediately");
6906                        }
6907                    }
6908                }
6909                if (doTrim) {
6910                    if (!isFirstBoot()) {
6911                        try {
6912                            ActivityManagerNative.getDefault().showBootMessage(
6913                                    mContext.getResources().getString(
6914                                            R.string.android_upgrading_fstrim), true);
6915                        } catch (RemoteException e) {
6916                        }
6917                    }
6918                    ms.runMaintenance();
6919                }
6920            } else {
6921                Slog.e(TAG, "Mount service unavailable!");
6922            }
6923        } catch (RemoteException e) {
6924            // Can't happen; MountService is local
6925        }
6926    }
6927
6928    @Override
6929    public void extractPackagesIfNeeded() {
6930        enforceSystemOrRoot("Only the system can request package extraction");
6931
6932        // We need to re-extract after an OTA.
6933        boolean causeUpgrade = isUpgrade();
6934
6935        // First boot or factory reset.
6936        // Note: we also handle devices that are upgrading to N right now as if it is their
6937        //       first boot, as they do not have profile data.
6938        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
6939
6940        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
6941        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
6942
6943        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
6944            return;
6945        }
6946
6947        List<PackageParser.Package> pkgs;
6948        synchronized (mPackages) {
6949            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6950        }
6951
6952        int curr = 0;
6953        int total = pkgs.size();
6954        for (PackageParser.Package pkg : pkgs) {
6955            curr++;
6956
6957            if (DEBUG_DEXOPT) {
6958                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6959            }
6960
6961            if (!isFirstBoot()) {
6962                try {
6963                    ActivityManagerNative.getDefault().showBootMessage(
6964                            mContext.getResources().getString(R.string.android_upgrading_apk,
6965                                    curr, total), true);
6966                } catch (RemoteException e) {
6967                }
6968            }
6969
6970            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6971                // If the cache was pruned, any compiled odex files will likely be out of date
6972                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
6973                // Instead, force the extraction in this case.
6974                performDexOpt(pkg.packageName,
6975                        null /* instructionSet */,
6976                        false /* checkProfiles */,
6977                        causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
6978                        false /* force */);
6979            }
6980        }
6981    }
6982
6983    @Override
6984    public void notifyPackageUse(String packageName) {
6985        synchronized (mPackages) {
6986            PackageParser.Package p = mPackages.get(packageName);
6987            if (p == null) {
6988                return;
6989            }
6990            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6991        }
6992    }
6993
6994    // TODO: this is not used nor needed. Delete it.
6995    @Override
6996    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6997        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
6998                getFullCompilerFilter(), false /* force */);
6999    }
7000
7001    @Override
7002    public boolean performDexOpt(String packageName, String instructionSet,
7003            boolean checkProfiles, int compileReason, boolean force) {
7004        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7005                getCompilerFilterForReason(compileReason), force);
7006    }
7007
7008    @Override
7009    public boolean performDexOptMode(String packageName, String instructionSet,
7010            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7011        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7012                targetCompilerFilter, force);
7013    }
7014
7015    private boolean performDexOptTraced(String packageName, String instructionSet,
7016                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7018        try {
7019            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7020                    targetCompilerFilter, force);
7021        } finally {
7022            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7023        }
7024    }
7025
7026    private boolean performDexOptInternal(String packageName, String instructionSet,
7027                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7028        PackageParser.Package p;
7029        final String targetInstructionSet;
7030        synchronized (mPackages) {
7031            p = mPackages.get(packageName);
7032            if (p == null) {
7033                return false;
7034            }
7035            mPackageUsage.write(false);
7036
7037            targetInstructionSet = instructionSet != null ? instructionSet :
7038                    getPrimaryInstructionSet(p.applicationInfo);
7039        }
7040        long callingId = Binder.clearCallingIdentity();
7041        try {
7042            synchronized (mInstallLock) {
7043                final String[] instructionSets = new String[] { targetInstructionSet };
7044                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7045                        checkProfiles, targetCompilerFilter, force);
7046                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7047            }
7048        } finally {
7049            Binder.restoreCallingIdentity(callingId);
7050        }
7051    }
7052
7053    public ArraySet<String> getOptimizablePackages() {
7054        ArraySet<String> pkgs = new ArraySet<String>();
7055        synchronized (mPackages) {
7056            for (PackageParser.Package p : mPackages.values()) {
7057                if (PackageDexOptimizer.canOptimizePackage(p)) {
7058                    pkgs.add(p.packageName);
7059                }
7060            }
7061        }
7062        return pkgs;
7063    }
7064
7065    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7066            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7067            boolean force) {
7068        // Select the dex optimizer based on the force parameter.
7069        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7070        //       allocate an object here.
7071        PackageDexOptimizer pdo = force
7072                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7073                : mPackageDexOptimizer;
7074
7075        // Optimize all dependencies first. Note: we ignore the return value and march on
7076        // on errors.
7077        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7078        if (!deps.isEmpty()) {
7079            for (PackageParser.Package depPackage : deps) {
7080                // TODO: Analyze and investigate if we (should) profile libraries.
7081                // Currently this will do a full compilation of the library by default.
7082                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7083                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7084            }
7085        }
7086
7087        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7088    }
7089
7090    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7091        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7092            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7093            Set<String> collectedNames = new HashSet<>();
7094            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7095
7096            retValue.remove(p);
7097
7098            return retValue;
7099        } else {
7100            return Collections.emptyList();
7101        }
7102    }
7103
7104    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7105            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7106        if (!collectedNames.contains(p.packageName)) {
7107            collectedNames.add(p.packageName);
7108            collected.add(p);
7109
7110            if (p.usesLibraries != null) {
7111                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7112            }
7113            if (p.usesOptionalLibraries != null) {
7114                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7115                        collectedNames);
7116            }
7117        }
7118    }
7119
7120    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7121            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7122        for (String libName : libs) {
7123            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7124            if (libPkg != null) {
7125                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7126            }
7127        }
7128    }
7129
7130    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7131        synchronized (mPackages) {
7132            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7133            if (lib != null && lib.apk != null) {
7134                return mPackages.get(lib.apk);
7135            }
7136        }
7137        return null;
7138    }
7139
7140    public void shutdown() {
7141        mPackageUsage.write(true);
7142    }
7143
7144    @Override
7145    public void forceDexOpt(String packageName) {
7146        enforceSystemOrRoot("forceDexOpt");
7147
7148        PackageParser.Package pkg;
7149        synchronized (mPackages) {
7150            pkg = mPackages.get(packageName);
7151            if (pkg == null) {
7152                throw new IllegalArgumentException("Unknown package: " + packageName);
7153            }
7154        }
7155
7156        synchronized (mInstallLock) {
7157            final String[] instructionSets = new String[] {
7158                    getPrimaryInstructionSet(pkg.applicationInfo) };
7159
7160            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7161
7162            // Whoever is calling forceDexOpt wants a fully compiled package.
7163            // Don't use profiles since that may cause compilation to be skipped.
7164            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7165                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7166                    true /* force */);
7167
7168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7169            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7170                throw new IllegalStateException("Failed to dexopt: " + res);
7171            }
7172        }
7173    }
7174
7175    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7176        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7177            Slog.w(TAG, "Unable to update from " + oldPkg.name
7178                    + " to " + newPkg.packageName
7179                    + ": old package not in system partition");
7180            return false;
7181        } else if (mPackages.get(oldPkg.name) != null) {
7182            Slog.w(TAG, "Unable to update from " + oldPkg.name
7183                    + " to " + newPkg.packageName
7184                    + ": old package still exists");
7185            return false;
7186        }
7187        return true;
7188    }
7189
7190    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7191        // TODO: triage flags as part of 26466827
7192        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7193
7194        boolean res = true;
7195        final int[] users = sUserManager.getUserIds();
7196        for (int user : users) {
7197            try {
7198                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7199            } catch (InstallerException e) {
7200                Slog.w(TAG, "Failed to delete data directory", e);
7201                res = false;
7202            }
7203        }
7204        return res;
7205    }
7206
7207    void removeCodePathLI(File codePath) {
7208        if (codePath.isDirectory()) {
7209            try {
7210                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7211            } catch (InstallerException e) {
7212                Slog.w(TAG, "Failed to remove code path", e);
7213            }
7214        } else {
7215            codePath.delete();
7216        }
7217    }
7218
7219    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7220        try {
7221            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7222        } catch (InstallerException e) {
7223            Slog.w(TAG, "Failed to destroy app data", e);
7224        }
7225    }
7226
7227    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7228            int appId, String seinfo) {
7229        try {
7230            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7231        } catch (InstallerException e) {
7232            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7233        }
7234    }
7235
7236    private void deleteProfilesLI(String packageName, boolean destroy) {
7237        final PackageParser.Package pkg;
7238        synchronized (mPackages) {
7239            pkg = mPackages.get(packageName);
7240        }
7241        if (pkg == null) {
7242            Slog.w(TAG, "Failed to delete profiles. No package: " + packageName);
7243            return;
7244        }
7245        deleteProfilesLI(pkg, destroy);
7246    }
7247
7248    private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
7249        try {
7250            if (destroy) {
7251                mInstaller.clearAppProfiles(pkg.packageName);
7252            } else {
7253                mInstaller.destroyAppProfiles(pkg.packageName);
7254            }
7255        } catch (InstallerException ex) {
7256            Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
7257        }
7258    }
7259
7260    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7261        final PackageParser.Package pkg;
7262        synchronized (mPackages) {
7263            pkg = mPackages.get(packageName);
7264        }
7265        if (pkg == null) {
7266            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7267            return;
7268        }
7269        deleteCodeCacheDirsLI(pkg);
7270    }
7271
7272    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7273        // TODO: triage flags as part of 26466827
7274        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7275
7276        int[] users = sUserManager.getUserIds();
7277        int res = 0;
7278        for (int user : users) {
7279            // Remove the parent code cache
7280            try {
7281                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7282                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7283            } catch (InstallerException e) {
7284                Slog.w(TAG, "Failed to delete code cache directory", e);
7285            }
7286            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7287            for (int i = 0; i < childCount; i++) {
7288                PackageParser.Package childPkg = pkg.childPackages.get(i);
7289                // Remove the child code cache
7290                try {
7291                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7292                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7293                } catch (InstallerException e) {
7294                    Slog.w(TAG, "Failed to delete code cache directory", e);
7295                }
7296            }
7297        }
7298    }
7299
7300    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7301            long lastUpdateTime) {
7302        // Set parent install/update time
7303        PackageSetting ps = (PackageSetting) pkg.mExtras;
7304        if (ps != null) {
7305            ps.firstInstallTime = firstInstallTime;
7306            ps.lastUpdateTime = lastUpdateTime;
7307        }
7308        // Set children install/update time
7309        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7310        for (int i = 0; i < childCount; i++) {
7311            PackageParser.Package childPkg = pkg.childPackages.get(i);
7312            ps = (PackageSetting) childPkg.mExtras;
7313            if (ps != null) {
7314                ps.firstInstallTime = firstInstallTime;
7315                ps.lastUpdateTime = lastUpdateTime;
7316            }
7317        }
7318    }
7319
7320    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7321            PackageParser.Package changingLib) {
7322        if (file.path != null) {
7323            usesLibraryFiles.add(file.path);
7324            return;
7325        }
7326        PackageParser.Package p = mPackages.get(file.apk);
7327        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7328            // If we are doing this while in the middle of updating a library apk,
7329            // then we need to make sure to use that new apk for determining the
7330            // dependencies here.  (We haven't yet finished committing the new apk
7331            // to the package manager state.)
7332            if (p == null || p.packageName.equals(changingLib.packageName)) {
7333                p = changingLib;
7334            }
7335        }
7336        if (p != null) {
7337            usesLibraryFiles.addAll(p.getAllCodePaths());
7338        }
7339    }
7340
7341    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7342            PackageParser.Package changingLib) throws PackageManagerException {
7343        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7344            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7345            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7346            for (int i=0; i<N; i++) {
7347                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7348                if (file == null) {
7349                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7350                            "Package " + pkg.packageName + " requires unavailable shared library "
7351                            + pkg.usesLibraries.get(i) + "; failing!");
7352                }
7353                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7354            }
7355            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7356            for (int i=0; i<N; i++) {
7357                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7358                if (file == null) {
7359                    Slog.w(TAG, "Package " + pkg.packageName
7360                            + " desires unavailable shared library "
7361                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7362                } else {
7363                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7364                }
7365            }
7366            N = usesLibraryFiles.size();
7367            if (N > 0) {
7368                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7369            } else {
7370                pkg.usesLibraryFiles = null;
7371            }
7372        }
7373    }
7374
7375    private static boolean hasString(List<String> list, List<String> which) {
7376        if (list == null) {
7377            return false;
7378        }
7379        for (int i=list.size()-1; i>=0; i--) {
7380            for (int j=which.size()-1; j>=0; j--) {
7381                if (which.get(j).equals(list.get(i))) {
7382                    return true;
7383                }
7384            }
7385        }
7386        return false;
7387    }
7388
7389    private void updateAllSharedLibrariesLPw() {
7390        for (PackageParser.Package pkg : mPackages.values()) {
7391            try {
7392                updateSharedLibrariesLPw(pkg, null);
7393            } catch (PackageManagerException e) {
7394                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7395            }
7396        }
7397    }
7398
7399    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7400            PackageParser.Package changingPkg) {
7401        ArrayList<PackageParser.Package> res = null;
7402        for (PackageParser.Package pkg : mPackages.values()) {
7403            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7404                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7405                if (res == null) {
7406                    res = new ArrayList<PackageParser.Package>();
7407                }
7408                res.add(pkg);
7409                try {
7410                    updateSharedLibrariesLPw(pkg, changingPkg);
7411                } catch (PackageManagerException e) {
7412                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7413                }
7414            }
7415        }
7416        return res;
7417    }
7418
7419    /**
7420     * Derive the value of the {@code cpuAbiOverride} based on the provided
7421     * value and an optional stored value from the package settings.
7422     */
7423    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7424        String cpuAbiOverride = null;
7425
7426        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7427            cpuAbiOverride = null;
7428        } else if (abiOverride != null) {
7429            cpuAbiOverride = abiOverride;
7430        } else if (settings != null) {
7431            cpuAbiOverride = settings.cpuAbiOverrideString;
7432        }
7433
7434        return cpuAbiOverride;
7435    }
7436
7437    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7438            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7439        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7440        // If the package has children and this is the first dive in the function
7441        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7442        // whether all packages (parent and children) would be successfully scanned
7443        // before the actual scan since scanning mutates internal state and we want
7444        // to atomically install the package and its children.
7445        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7446            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7447                scanFlags |= SCAN_CHECK_ONLY;
7448            }
7449        } else {
7450            scanFlags &= ~SCAN_CHECK_ONLY;
7451        }
7452
7453        final PackageParser.Package scannedPkg;
7454        try {
7455            // Scan the parent
7456            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7457            // Scan the children
7458            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7459            for (int i = 0; i < childCount; i++) {
7460                PackageParser.Package childPkg = pkg.childPackages.get(i);
7461                scanPackageLI(childPkg, parseFlags,
7462                        scanFlags, currentTime, user);
7463            }
7464        } finally {
7465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7466        }
7467
7468        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7469            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7470        }
7471
7472        return scannedPkg;
7473    }
7474
7475    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7476            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7477        boolean success = false;
7478        try {
7479            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7480                    currentTime, user);
7481            success = true;
7482            return res;
7483        } finally {
7484            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7485                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7486            }
7487        }
7488    }
7489
7490    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7491            int scanFlags, long currentTime, UserHandle user)
7492            throws PackageManagerException {
7493        final File scanFile = new File(pkg.codePath);
7494        if (pkg.applicationInfo.getCodePath() == null ||
7495                pkg.applicationInfo.getResourcePath() == null) {
7496            // Bail out. The resource and code paths haven't been set.
7497            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7498                    "Code and resource paths haven't been set correctly");
7499        }
7500
7501        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7502            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7503        } else {
7504            // Only allow system apps to be flagged as core apps.
7505            pkg.coreApp = false;
7506        }
7507
7508        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7509            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7510        }
7511
7512        if (mCustomResolverComponentName != null &&
7513                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7514            setUpCustomResolverActivity(pkg);
7515        }
7516
7517        if (pkg.packageName.equals("android")) {
7518            synchronized (mPackages) {
7519                if (mAndroidApplication != null) {
7520                    Slog.w(TAG, "*************************************************");
7521                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7522                    Slog.w(TAG, " file=" + scanFile);
7523                    Slog.w(TAG, "*************************************************");
7524                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7525                            "Core android package being redefined.  Skipping.");
7526                }
7527
7528                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7529                    // Set up information for our fall-back user intent resolution activity.
7530                    mPlatformPackage = pkg;
7531                    pkg.mVersionCode = mSdkVersion;
7532                    mAndroidApplication = pkg.applicationInfo;
7533
7534                    if (!mResolverReplaced) {
7535                        mResolveActivity.applicationInfo = mAndroidApplication;
7536                        mResolveActivity.name = ResolverActivity.class.getName();
7537                        mResolveActivity.packageName = mAndroidApplication.packageName;
7538                        mResolveActivity.processName = "system:ui";
7539                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7540                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7541                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7542                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7543                        mResolveActivity.exported = true;
7544                        mResolveActivity.enabled = true;
7545                        mResolveInfo.activityInfo = mResolveActivity;
7546                        mResolveInfo.priority = 0;
7547                        mResolveInfo.preferredOrder = 0;
7548                        mResolveInfo.match = 0;
7549                        mResolveComponentName = new ComponentName(
7550                                mAndroidApplication.packageName, mResolveActivity.name);
7551                    }
7552                }
7553            }
7554        }
7555
7556        if (DEBUG_PACKAGE_SCANNING) {
7557            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7558                Log.d(TAG, "Scanning package " + pkg.packageName);
7559        }
7560
7561        synchronized (mPackages) {
7562            if (mPackages.containsKey(pkg.packageName)
7563                    || mSharedLibraries.containsKey(pkg.packageName)) {
7564                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7565                        "Application package " + pkg.packageName
7566                                + " already installed.  Skipping duplicate.");
7567            }
7568
7569            // If we're only installing presumed-existing packages, require that the
7570            // scanned APK is both already known and at the path previously established
7571            // for it.  Previously unknown packages we pick up normally, but if we have an
7572            // a priori expectation about this package's install presence, enforce it.
7573            // With a singular exception for new system packages. When an OTA contains
7574            // a new system package, we allow the codepath to change from a system location
7575            // to the user-installed location. If we don't allow this change, any newer,
7576            // user-installed version of the application will be ignored.
7577            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7578                if (mExpectingBetter.containsKey(pkg.packageName)) {
7579                    logCriticalInfo(Log.WARN,
7580                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7581                } else {
7582                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7583                    if (known != null) {
7584                        if (DEBUG_PACKAGE_SCANNING) {
7585                            Log.d(TAG, "Examining " + pkg.codePath
7586                                    + " and requiring known paths " + known.codePathString
7587                                    + " & " + known.resourcePathString);
7588                        }
7589                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7590                                || !pkg.applicationInfo.getResourcePath().equals(
7591                                known.resourcePathString)) {
7592                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7593                                    "Application package " + pkg.packageName
7594                                            + " found at " + pkg.applicationInfo.getCodePath()
7595                                            + " but expected at " + known.codePathString
7596                                            + "; ignoring.");
7597                        }
7598                    }
7599                }
7600            }
7601        }
7602
7603        // Initialize package source and resource directories
7604        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7605        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7606
7607        SharedUserSetting suid = null;
7608        PackageSetting pkgSetting = null;
7609
7610        if (!isSystemApp(pkg)) {
7611            // Only system apps can use these features.
7612            pkg.mOriginalPackages = null;
7613            pkg.mRealPackage = null;
7614            pkg.mAdoptPermissions = null;
7615        }
7616
7617        // Getting the package setting may have a side-effect, so if we
7618        // are only checking if scan would succeed, stash a copy of the
7619        // old setting to restore at the end.
7620        PackageSetting nonMutatedPs = null;
7621
7622        // writer
7623        synchronized (mPackages) {
7624            if (pkg.mSharedUserId != null) {
7625                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7626                if (suid == null) {
7627                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7628                            "Creating application package " + pkg.packageName
7629                            + " for shared user failed");
7630                }
7631                if (DEBUG_PACKAGE_SCANNING) {
7632                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7633                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7634                                + "): packages=" + suid.packages);
7635                }
7636            }
7637
7638            // Check if we are renaming from an original package name.
7639            PackageSetting origPackage = null;
7640            String realName = null;
7641            if (pkg.mOriginalPackages != null) {
7642                // This package may need to be renamed to a previously
7643                // installed name.  Let's check on that...
7644                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7645                if (pkg.mOriginalPackages.contains(renamed)) {
7646                    // This package had originally been installed as the
7647                    // original name, and we have already taken care of
7648                    // transitioning to the new one.  Just update the new
7649                    // one to continue using the old name.
7650                    realName = pkg.mRealPackage;
7651                    if (!pkg.packageName.equals(renamed)) {
7652                        // Callers into this function may have already taken
7653                        // care of renaming the package; only do it here if
7654                        // it is not already done.
7655                        pkg.setPackageName(renamed);
7656                    }
7657
7658                } else {
7659                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7660                        if ((origPackage = mSettings.peekPackageLPr(
7661                                pkg.mOriginalPackages.get(i))) != null) {
7662                            // We do have the package already installed under its
7663                            // original name...  should we use it?
7664                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7665                                // New package is not compatible with original.
7666                                origPackage = null;
7667                                continue;
7668                            } else if (origPackage.sharedUser != null) {
7669                                // Make sure uid is compatible between packages.
7670                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7671                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7672                                            + " to " + pkg.packageName + ": old uid "
7673                                            + origPackage.sharedUser.name
7674                                            + " differs from " + pkg.mSharedUserId);
7675                                    origPackage = null;
7676                                    continue;
7677                                }
7678                            } else {
7679                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7680                                        + pkg.packageName + " to old name " + origPackage.name);
7681                            }
7682                            break;
7683                        }
7684                    }
7685                }
7686            }
7687
7688            if (mTransferedPackages.contains(pkg.packageName)) {
7689                Slog.w(TAG, "Package " + pkg.packageName
7690                        + " was transferred to another, but its .apk remains");
7691            }
7692
7693            // See comments in nonMutatedPs declaration
7694            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7695                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7696                if (foundPs != null) {
7697                    nonMutatedPs = new PackageSetting(foundPs);
7698                }
7699            }
7700
7701            // Just create the setting, don't add it yet. For already existing packages
7702            // the PkgSetting exists already and doesn't have to be created.
7703            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7704                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7705                    pkg.applicationInfo.primaryCpuAbi,
7706                    pkg.applicationInfo.secondaryCpuAbi,
7707                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7708                    user, false);
7709            if (pkgSetting == null) {
7710                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7711                        "Creating application package " + pkg.packageName + " failed");
7712            }
7713
7714            if (pkgSetting.origPackage != null) {
7715                // If we are first transitioning from an original package,
7716                // fix up the new package's name now.  We need to do this after
7717                // looking up the package under its new name, so getPackageLP
7718                // can take care of fiddling things correctly.
7719                pkg.setPackageName(origPackage.name);
7720
7721                // File a report about this.
7722                String msg = "New package " + pkgSetting.realName
7723                        + " renamed to replace old package " + pkgSetting.name;
7724                reportSettingsProblem(Log.WARN, msg);
7725
7726                // Make a note of it.
7727                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7728                    mTransferedPackages.add(origPackage.name);
7729                }
7730
7731                // No longer need to retain this.
7732                pkgSetting.origPackage = null;
7733            }
7734
7735            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7736                // Make a note of it.
7737                mTransferedPackages.add(pkg.packageName);
7738            }
7739
7740            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7741                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7742            }
7743
7744            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7745                // Check all shared libraries and map to their actual file path.
7746                // We only do this here for apps not on a system dir, because those
7747                // are the only ones that can fail an install due to this.  We
7748                // will take care of the system apps by updating all of their
7749                // library paths after the scan is done.
7750                updateSharedLibrariesLPw(pkg, null);
7751            }
7752
7753            if (mFoundPolicyFile) {
7754                SELinuxMMAC.assignSeinfoValue(pkg);
7755            }
7756
7757            pkg.applicationInfo.uid = pkgSetting.appId;
7758            pkg.mExtras = pkgSetting;
7759            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7760                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7761                    // We just determined the app is signed correctly, so bring
7762                    // over the latest parsed certs.
7763                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7764                } else {
7765                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7766                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7767                                "Package " + pkg.packageName + " upgrade keys do not match the "
7768                                + "previously installed version");
7769                    } else {
7770                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7771                        String msg = "System package " + pkg.packageName
7772                            + " signature changed; retaining data.";
7773                        reportSettingsProblem(Log.WARN, msg);
7774                    }
7775                }
7776            } else {
7777                try {
7778                    verifySignaturesLP(pkgSetting, pkg);
7779                    // We just determined the app is signed correctly, so bring
7780                    // over the latest parsed certs.
7781                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7782                } catch (PackageManagerException e) {
7783                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7784                        throw e;
7785                    }
7786                    // The signature has changed, but this package is in the system
7787                    // image...  let's recover!
7788                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7789                    // However...  if this package is part of a shared user, but it
7790                    // doesn't match the signature of the shared user, let's fail.
7791                    // What this means is that you can't change the signatures
7792                    // associated with an overall shared user, which doesn't seem all
7793                    // that unreasonable.
7794                    if (pkgSetting.sharedUser != null) {
7795                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7796                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7797                            throw new PackageManagerException(
7798                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7799                                            "Signature mismatch for shared user: "
7800                                            + pkgSetting.sharedUser);
7801                        }
7802                    }
7803                    // File a report about this.
7804                    String msg = "System package " + pkg.packageName
7805                        + " signature changed; retaining data.";
7806                    reportSettingsProblem(Log.WARN, msg);
7807                }
7808            }
7809            // Verify that this new package doesn't have any content providers
7810            // that conflict with existing packages.  Only do this if the
7811            // package isn't already installed, since we don't want to break
7812            // things that are installed.
7813            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7814                final int N = pkg.providers.size();
7815                int i;
7816                for (i=0; i<N; i++) {
7817                    PackageParser.Provider p = pkg.providers.get(i);
7818                    if (p.info.authority != null) {
7819                        String names[] = p.info.authority.split(";");
7820                        for (int j = 0; j < names.length; j++) {
7821                            if (mProvidersByAuthority.containsKey(names[j])) {
7822                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7823                                final String otherPackageName =
7824                                        ((other != null && other.getComponentName() != null) ?
7825                                                other.getComponentName().getPackageName() : "?");
7826                                throw new PackageManagerException(
7827                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7828                                                "Can't install because provider name " + names[j]
7829                                                + " (in package " + pkg.applicationInfo.packageName
7830                                                + ") is already used by " + otherPackageName);
7831                            }
7832                        }
7833                    }
7834                }
7835            }
7836
7837            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7838                // This package wants to adopt ownership of permissions from
7839                // another package.
7840                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7841                    final String origName = pkg.mAdoptPermissions.get(i);
7842                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7843                    if (orig != null) {
7844                        if (verifyPackageUpdateLPr(orig, pkg)) {
7845                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7846                                    + pkg.packageName);
7847                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7848                        }
7849                    }
7850                }
7851            }
7852        }
7853
7854        final String pkgName = pkg.packageName;
7855
7856        final long scanFileTime = scanFile.lastModified();
7857        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7858        pkg.applicationInfo.processName = fixProcessName(
7859                pkg.applicationInfo.packageName,
7860                pkg.applicationInfo.processName,
7861                pkg.applicationInfo.uid);
7862
7863        if (pkg != mPlatformPackage) {
7864            // Get all of our default paths setup
7865            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7866        }
7867
7868        final String path = scanFile.getPath();
7869        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7870
7871        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7872            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7873
7874            // Some system apps still use directory structure for native libraries
7875            // in which case we might end up not detecting abi solely based on apk
7876            // structure. Try to detect abi based on directory structure.
7877            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7878                    pkg.applicationInfo.primaryCpuAbi == null) {
7879                setBundledAppAbisAndRoots(pkg, pkgSetting);
7880                setNativeLibraryPaths(pkg);
7881            }
7882
7883        } else {
7884            if ((scanFlags & SCAN_MOVE) != 0) {
7885                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7886                // but we already have this packages package info in the PackageSetting. We just
7887                // use that and derive the native library path based on the new codepath.
7888                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7889                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7890            }
7891
7892            // Set native library paths again. For moves, the path will be updated based on the
7893            // ABIs we've determined above. For non-moves, the path will be updated based on the
7894            // ABIs we determined during compilation, but the path will depend on the final
7895            // package path (after the rename away from the stage path).
7896            setNativeLibraryPaths(pkg);
7897        }
7898
7899        // This is a special case for the "system" package, where the ABI is
7900        // dictated by the zygote configuration (and init.rc). We should keep track
7901        // of this ABI so that we can deal with "normal" applications that run under
7902        // the same UID correctly.
7903        if (mPlatformPackage == pkg) {
7904            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7905                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7906        }
7907
7908        // If there's a mismatch between the abi-override in the package setting
7909        // and the abiOverride specified for the install. Warn about this because we
7910        // would've already compiled the app without taking the package setting into
7911        // account.
7912        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7913            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7914                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7915                        " for package " + pkg.packageName);
7916            }
7917        }
7918
7919        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7920        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7921        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7922
7923        // Copy the derived override back to the parsed package, so that we can
7924        // update the package settings accordingly.
7925        pkg.cpuAbiOverride = cpuAbiOverride;
7926
7927        if (DEBUG_ABI_SELECTION) {
7928            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7929                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7930                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7931        }
7932
7933        // Push the derived path down into PackageSettings so we know what to
7934        // clean up at uninstall time.
7935        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7936
7937        if (DEBUG_ABI_SELECTION) {
7938            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7939                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7940                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7941        }
7942
7943        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7944            // We don't do this here during boot because we can do it all
7945            // at once after scanning all existing packages.
7946            //
7947            // We also do this *before* we perform dexopt on this package, so that
7948            // we can avoid redundant dexopts, and also to make sure we've got the
7949            // code and package path correct.
7950            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7951                    pkg, true /* boot complete */);
7952        }
7953
7954        if (mFactoryTest && pkg.requestedPermissions.contains(
7955                android.Manifest.permission.FACTORY_TEST)) {
7956            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7957        }
7958
7959        ArrayList<PackageParser.Package> clientLibPkgs = null;
7960
7961        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7962            if (nonMutatedPs != null) {
7963                synchronized (mPackages) {
7964                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7965                }
7966            }
7967            return pkg;
7968        }
7969
7970        // Only privileged apps and updated privileged apps can add child packages.
7971        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7972            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7973                throw new PackageManagerException("Only privileged apps and updated "
7974                        + "privileged apps can add child packages. Ignoring package "
7975                        + pkg.packageName);
7976            }
7977            final int childCount = pkg.childPackages.size();
7978            for (int i = 0; i < childCount; i++) {
7979                PackageParser.Package childPkg = pkg.childPackages.get(i);
7980                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7981                        childPkg.packageName)) {
7982                    throw new PackageManagerException("Cannot override a child package of "
7983                            + "another disabled system app. Ignoring package " + pkg.packageName);
7984                }
7985            }
7986        }
7987
7988        // writer
7989        synchronized (mPackages) {
7990            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7991                // Only system apps can add new shared libraries.
7992                if (pkg.libraryNames != null) {
7993                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7994                        String name = pkg.libraryNames.get(i);
7995                        boolean allowed = false;
7996                        if (pkg.isUpdatedSystemApp()) {
7997                            // New library entries can only be added through the
7998                            // system image.  This is important to get rid of a lot
7999                            // of nasty edge cases: for example if we allowed a non-
8000                            // system update of the app to add a library, then uninstalling
8001                            // the update would make the library go away, and assumptions
8002                            // we made such as through app install filtering would now
8003                            // have allowed apps on the device which aren't compatible
8004                            // with it.  Better to just have the restriction here, be
8005                            // conservative, and create many fewer cases that can negatively
8006                            // impact the user experience.
8007                            final PackageSetting sysPs = mSettings
8008                                    .getDisabledSystemPkgLPr(pkg.packageName);
8009                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8010                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8011                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8012                                        allowed = true;
8013                                        break;
8014                                    }
8015                                }
8016                            }
8017                        } else {
8018                            allowed = true;
8019                        }
8020                        if (allowed) {
8021                            if (!mSharedLibraries.containsKey(name)) {
8022                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8023                            } else if (!name.equals(pkg.packageName)) {
8024                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8025                                        + name + " already exists; skipping");
8026                            }
8027                        } else {
8028                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8029                                    + name + " that is not declared on system image; skipping");
8030                        }
8031                    }
8032                    if ((scanFlags & SCAN_BOOTING) == 0) {
8033                        // If we are not booting, we need to update any applications
8034                        // that are clients of our shared library.  If we are booting,
8035                        // this will all be done once the scan is complete.
8036                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8037                    }
8038                }
8039            }
8040        }
8041
8042        // Request the ActivityManager to kill the process(only for existing packages)
8043        // so that we do not end up in a confused state while the user is still using the older
8044        // version of the application while the new one gets installed.
8045        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
8046        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
8047        if (killApp) {
8048            if (isReplacing) {
8049                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
8050
8051                killApplication(pkg.applicationInfo.packageName,
8052                            pkg.applicationInfo.uid, "replace pkg");
8053
8054                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8055            }
8056        }
8057
8058        // Also need to kill any apps that are dependent on the library.
8059        if (clientLibPkgs != null) {
8060            for (int i=0; i<clientLibPkgs.size(); i++) {
8061                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8062                killApplication(clientPkg.applicationInfo.packageName,
8063                        clientPkg.applicationInfo.uid, "update lib");
8064            }
8065        }
8066
8067        // Make sure we're not adding any bogus keyset info
8068        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8069        ksms.assertScannedPackageValid(pkg);
8070
8071        // writer
8072        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8073
8074        boolean createIdmapFailed = false;
8075        synchronized (mPackages) {
8076            // We don't expect installation to fail beyond this point
8077
8078            // Add the new setting to mSettings
8079            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8080            // Add the new setting to mPackages
8081            mPackages.put(pkg.applicationInfo.packageName, pkg);
8082            // Make sure we don't accidentally delete its data.
8083            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8084            while (iter.hasNext()) {
8085                PackageCleanItem item = iter.next();
8086                if (pkgName.equals(item.packageName)) {
8087                    iter.remove();
8088                }
8089            }
8090
8091            // Take care of first install / last update times.
8092            if (currentTime != 0) {
8093                if (pkgSetting.firstInstallTime == 0) {
8094                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8095                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8096                    pkgSetting.lastUpdateTime = currentTime;
8097                }
8098            } else if (pkgSetting.firstInstallTime == 0) {
8099                // We need *something*.  Take time time stamp of the file.
8100                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8101            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8102                if (scanFileTime != pkgSetting.timeStamp) {
8103                    // A package on the system image has changed; consider this
8104                    // to be an update.
8105                    pkgSetting.lastUpdateTime = scanFileTime;
8106                }
8107            }
8108
8109            // Add the package's KeySets to the global KeySetManagerService
8110            ksms.addScannedPackageLPw(pkg);
8111
8112            int N = pkg.providers.size();
8113            StringBuilder r = null;
8114            int i;
8115            for (i=0; i<N; i++) {
8116                PackageParser.Provider p = pkg.providers.get(i);
8117                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8118                        p.info.processName, pkg.applicationInfo.uid);
8119                mProviders.addProvider(p);
8120                p.syncable = p.info.isSyncable;
8121                if (p.info.authority != null) {
8122                    String names[] = p.info.authority.split(";");
8123                    p.info.authority = null;
8124                    for (int j = 0; j < names.length; j++) {
8125                        if (j == 1 && p.syncable) {
8126                            // We only want the first authority for a provider to possibly be
8127                            // syncable, so if we already added this provider using a different
8128                            // authority clear the syncable flag. We copy the provider before
8129                            // changing it because the mProviders object contains a reference
8130                            // to a provider that we don't want to change.
8131                            // Only do this for the second authority since the resulting provider
8132                            // object can be the same for all future authorities for this provider.
8133                            p = new PackageParser.Provider(p);
8134                            p.syncable = false;
8135                        }
8136                        if (!mProvidersByAuthority.containsKey(names[j])) {
8137                            mProvidersByAuthority.put(names[j], p);
8138                            if (p.info.authority == null) {
8139                                p.info.authority = names[j];
8140                            } else {
8141                                p.info.authority = p.info.authority + ";" + names[j];
8142                            }
8143                            if (DEBUG_PACKAGE_SCANNING) {
8144                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8145                                    Log.d(TAG, "Registered content provider: " + names[j]
8146                                            + ", className = " + p.info.name + ", isSyncable = "
8147                                            + p.info.isSyncable);
8148                            }
8149                        } else {
8150                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8151                            Slog.w(TAG, "Skipping provider name " + names[j] +
8152                                    " (in package " + pkg.applicationInfo.packageName +
8153                                    "): name already used by "
8154                                    + ((other != null && other.getComponentName() != null)
8155                                            ? other.getComponentName().getPackageName() : "?"));
8156                        }
8157                    }
8158                }
8159                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8160                    if (r == null) {
8161                        r = new StringBuilder(256);
8162                    } else {
8163                        r.append(' ');
8164                    }
8165                    r.append(p.info.name);
8166                }
8167            }
8168            if (r != null) {
8169                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8170            }
8171
8172            N = pkg.services.size();
8173            r = null;
8174            for (i=0; i<N; i++) {
8175                PackageParser.Service s = pkg.services.get(i);
8176                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8177                        s.info.processName, pkg.applicationInfo.uid);
8178                mServices.addService(s);
8179                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8180                    if (r == null) {
8181                        r = new StringBuilder(256);
8182                    } else {
8183                        r.append(' ');
8184                    }
8185                    r.append(s.info.name);
8186                }
8187            }
8188            if (r != null) {
8189                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8190            }
8191
8192            N = pkg.receivers.size();
8193            r = null;
8194            for (i=0; i<N; i++) {
8195                PackageParser.Activity a = pkg.receivers.get(i);
8196                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8197                        a.info.processName, pkg.applicationInfo.uid);
8198                mReceivers.addActivity(a, "receiver");
8199                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8200                    if (r == null) {
8201                        r = new StringBuilder(256);
8202                    } else {
8203                        r.append(' ');
8204                    }
8205                    r.append(a.info.name);
8206                }
8207            }
8208            if (r != null) {
8209                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8210            }
8211
8212            N = pkg.activities.size();
8213            r = null;
8214            for (i=0; i<N; i++) {
8215                PackageParser.Activity a = pkg.activities.get(i);
8216                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8217                        a.info.processName, pkg.applicationInfo.uid);
8218                mActivities.addActivity(a, "activity");
8219                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8220                    if (r == null) {
8221                        r = new StringBuilder(256);
8222                    } else {
8223                        r.append(' ');
8224                    }
8225                    r.append(a.info.name);
8226                }
8227            }
8228            if (r != null) {
8229                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8230            }
8231
8232            N = pkg.permissionGroups.size();
8233            r = null;
8234            for (i=0; i<N; i++) {
8235                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8236                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8237                if (cur == null) {
8238                    mPermissionGroups.put(pg.info.name, pg);
8239                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8240                        if (r == null) {
8241                            r = new StringBuilder(256);
8242                        } else {
8243                            r.append(' ');
8244                        }
8245                        r.append(pg.info.name);
8246                    }
8247                } else {
8248                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8249                            + pg.info.packageName + " ignored: original from "
8250                            + cur.info.packageName);
8251                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8252                        if (r == null) {
8253                            r = new StringBuilder(256);
8254                        } else {
8255                            r.append(' ');
8256                        }
8257                        r.append("DUP:");
8258                        r.append(pg.info.name);
8259                    }
8260                }
8261            }
8262            if (r != null) {
8263                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8264            }
8265
8266            N = pkg.permissions.size();
8267            r = null;
8268            for (i=0; i<N; i++) {
8269                PackageParser.Permission p = pkg.permissions.get(i);
8270
8271                // Assume by default that we did not install this permission into the system.
8272                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8273
8274                // Now that permission groups have a special meaning, we ignore permission
8275                // groups for legacy apps to prevent unexpected behavior. In particular,
8276                // permissions for one app being granted to someone just becase they happen
8277                // to be in a group defined by another app (before this had no implications).
8278                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8279                    p.group = mPermissionGroups.get(p.info.group);
8280                    // Warn for a permission in an unknown group.
8281                    if (p.info.group != null && p.group == null) {
8282                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8283                                + p.info.packageName + " in an unknown group " + p.info.group);
8284                    }
8285                }
8286
8287                ArrayMap<String, BasePermission> permissionMap =
8288                        p.tree ? mSettings.mPermissionTrees
8289                                : mSettings.mPermissions;
8290                BasePermission bp = permissionMap.get(p.info.name);
8291
8292                // Allow system apps to redefine non-system permissions
8293                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8294                    final boolean currentOwnerIsSystem = (bp.perm != null
8295                            && isSystemApp(bp.perm.owner));
8296                    if (isSystemApp(p.owner)) {
8297                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8298                            // It's a built-in permission and no owner, take ownership now
8299                            bp.packageSetting = pkgSetting;
8300                            bp.perm = p;
8301                            bp.uid = pkg.applicationInfo.uid;
8302                            bp.sourcePackage = p.info.packageName;
8303                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8304                        } else if (!currentOwnerIsSystem) {
8305                            String msg = "New decl " + p.owner + " of permission  "
8306                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8307                            reportSettingsProblem(Log.WARN, msg);
8308                            bp = null;
8309                        }
8310                    }
8311                }
8312
8313                if (bp == null) {
8314                    bp = new BasePermission(p.info.name, p.info.packageName,
8315                            BasePermission.TYPE_NORMAL);
8316                    permissionMap.put(p.info.name, bp);
8317                }
8318
8319                if (bp.perm == null) {
8320                    if (bp.sourcePackage == null
8321                            || bp.sourcePackage.equals(p.info.packageName)) {
8322                        BasePermission tree = findPermissionTreeLP(p.info.name);
8323                        if (tree == null
8324                                || tree.sourcePackage.equals(p.info.packageName)) {
8325                            bp.packageSetting = pkgSetting;
8326                            bp.perm = p;
8327                            bp.uid = pkg.applicationInfo.uid;
8328                            bp.sourcePackage = p.info.packageName;
8329                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8330                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8331                                if (r == null) {
8332                                    r = new StringBuilder(256);
8333                                } else {
8334                                    r.append(' ');
8335                                }
8336                                r.append(p.info.name);
8337                            }
8338                        } else {
8339                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8340                                    + p.info.packageName + " ignored: base tree "
8341                                    + tree.name + " is from package "
8342                                    + tree.sourcePackage);
8343                        }
8344                    } else {
8345                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8346                                + p.info.packageName + " ignored: original from "
8347                                + bp.sourcePackage);
8348                    }
8349                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8350                    if (r == null) {
8351                        r = new StringBuilder(256);
8352                    } else {
8353                        r.append(' ');
8354                    }
8355                    r.append("DUP:");
8356                    r.append(p.info.name);
8357                }
8358                if (bp.perm == p) {
8359                    bp.protectionLevel = p.info.protectionLevel;
8360                }
8361            }
8362
8363            if (r != null) {
8364                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8365            }
8366
8367            N = pkg.instrumentation.size();
8368            r = null;
8369            for (i=0; i<N; i++) {
8370                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8371                a.info.packageName = pkg.applicationInfo.packageName;
8372                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8373                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8374                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8375                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8376                a.info.dataDir = pkg.applicationInfo.dataDir;
8377                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8378                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8379
8380                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8381                // need other information about the application, like the ABI and what not ?
8382                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8383                mInstrumentation.put(a.getComponentName(), a);
8384                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8385                    if (r == null) {
8386                        r = new StringBuilder(256);
8387                    } else {
8388                        r.append(' ');
8389                    }
8390                    r.append(a.info.name);
8391                }
8392            }
8393            if (r != null) {
8394                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8395            }
8396
8397            if (pkg.protectedBroadcasts != null) {
8398                N = pkg.protectedBroadcasts.size();
8399                for (i=0; i<N; i++) {
8400                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8401                }
8402            }
8403
8404            pkgSetting.setTimeStamp(scanFileTime);
8405
8406            // Create idmap files for pairs of (packages, overlay packages).
8407            // Note: "android", ie framework-res.apk, is handled by native layers.
8408            if (pkg.mOverlayTarget != null) {
8409                // This is an overlay package.
8410                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8411                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8412                        mOverlays.put(pkg.mOverlayTarget,
8413                                new ArrayMap<String, PackageParser.Package>());
8414                    }
8415                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8416                    map.put(pkg.packageName, pkg);
8417                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8418                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8419                        createIdmapFailed = true;
8420                    }
8421                }
8422            } else if (mOverlays.containsKey(pkg.packageName) &&
8423                    !pkg.packageName.equals("android")) {
8424                // This is a regular package, with one or more known overlay packages.
8425                createIdmapsForPackageLI(pkg);
8426            }
8427        }
8428
8429        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8430
8431        if (createIdmapFailed) {
8432            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8433                    "scanPackageLI failed to createIdmap");
8434        }
8435        return pkg;
8436    }
8437
8438    /**
8439     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8440     * is derived purely on the basis of the contents of {@code scanFile} and
8441     * {@code cpuAbiOverride}.
8442     *
8443     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8444     */
8445    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8446                                 String cpuAbiOverride, boolean extractLibs)
8447            throws PackageManagerException {
8448        // TODO: We can probably be smarter about this stuff. For installed apps,
8449        // we can calculate this information at install time once and for all. For
8450        // system apps, we can probably assume that this information doesn't change
8451        // after the first boot scan. As things stand, we do lots of unnecessary work.
8452
8453        // Give ourselves some initial paths; we'll come back for another
8454        // pass once we've determined ABI below.
8455        setNativeLibraryPaths(pkg);
8456
8457        // We would never need to extract libs for forward-locked and external packages,
8458        // since the container service will do it for us. We shouldn't attempt to
8459        // extract libs from system app when it was not updated.
8460        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8461                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8462            extractLibs = false;
8463        }
8464
8465        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8466        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8467
8468        NativeLibraryHelper.Handle handle = null;
8469        try {
8470            handle = NativeLibraryHelper.Handle.create(pkg);
8471            // TODO(multiArch): This can be null for apps that didn't go through the
8472            // usual installation process. We can calculate it again, like we
8473            // do during install time.
8474            //
8475            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8476            // unnecessary.
8477            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8478
8479            // Null out the abis so that they can be recalculated.
8480            pkg.applicationInfo.primaryCpuAbi = null;
8481            pkg.applicationInfo.secondaryCpuAbi = null;
8482            if (isMultiArch(pkg.applicationInfo)) {
8483                // Warn if we've set an abiOverride for multi-lib packages..
8484                // By definition, we need to copy both 32 and 64 bit libraries for
8485                // such packages.
8486                if (pkg.cpuAbiOverride != null
8487                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8488                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8489                }
8490
8491                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8492                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8493                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8494                    if (extractLibs) {
8495                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8496                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8497                                useIsaSpecificSubdirs);
8498                    } else {
8499                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8500                    }
8501                }
8502
8503                maybeThrowExceptionForMultiArchCopy(
8504                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8505
8506                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8507                    if (extractLibs) {
8508                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8509                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8510                                useIsaSpecificSubdirs);
8511                    } else {
8512                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8513                    }
8514                }
8515
8516                maybeThrowExceptionForMultiArchCopy(
8517                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8518
8519                if (abi64 >= 0) {
8520                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8521                }
8522
8523                if (abi32 >= 0) {
8524                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8525                    if (abi64 >= 0) {
8526                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8527                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8528                            pkg.applicationInfo.primaryCpuAbi = abi;
8529                        } else {
8530                            pkg.applicationInfo.secondaryCpuAbi = abi;
8531                        }
8532                    } else {
8533                        pkg.applicationInfo.primaryCpuAbi = abi;
8534                    }
8535                }
8536
8537            } else {
8538                String[] abiList = (cpuAbiOverride != null) ?
8539                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8540
8541                // Enable gross and lame hacks for apps that are built with old
8542                // SDK tools. We must scan their APKs for renderscript bitcode and
8543                // not launch them if it's present. Don't bother checking on devices
8544                // that don't have 64 bit support.
8545                boolean needsRenderScriptOverride = false;
8546                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8547                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8548                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8549                    needsRenderScriptOverride = true;
8550                }
8551
8552                final int copyRet;
8553                if (extractLibs) {
8554                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8555                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8556                } else {
8557                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8558                }
8559
8560                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8561                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8562                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8563                }
8564
8565                if (copyRet >= 0) {
8566                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8567                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8568                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8569                } else if (needsRenderScriptOverride) {
8570                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8571                }
8572            }
8573        } catch (IOException ioe) {
8574            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8575        } finally {
8576            IoUtils.closeQuietly(handle);
8577        }
8578
8579        // Now that we've calculated the ABIs and determined if it's an internal app,
8580        // we will go ahead and populate the nativeLibraryPath.
8581        setNativeLibraryPaths(pkg);
8582    }
8583
8584    /**
8585     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8586     * i.e, so that all packages can be run inside a single process if required.
8587     *
8588     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8589     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8590     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8591     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8592     * updating a package that belongs to a shared user.
8593     *
8594     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8595     * adds unnecessary complexity.
8596     */
8597    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8598            PackageParser.Package scannedPackage, boolean bootComplete) {
8599        String requiredInstructionSet = null;
8600        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8601            requiredInstructionSet = VMRuntime.getInstructionSet(
8602                     scannedPackage.applicationInfo.primaryCpuAbi);
8603        }
8604
8605        PackageSetting requirer = null;
8606        for (PackageSetting ps : packagesForUser) {
8607            // If packagesForUser contains scannedPackage, we skip it. This will happen
8608            // when scannedPackage is an update of an existing package. Without this check,
8609            // we will never be able to change the ABI of any package belonging to a shared
8610            // user, even if it's compatible with other packages.
8611            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8612                if (ps.primaryCpuAbiString == null) {
8613                    continue;
8614                }
8615
8616                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8617                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8618                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8619                    // this but there's not much we can do.
8620                    String errorMessage = "Instruction set mismatch, "
8621                            + ((requirer == null) ? "[caller]" : requirer)
8622                            + " requires " + requiredInstructionSet + " whereas " + ps
8623                            + " requires " + instructionSet;
8624                    Slog.w(TAG, errorMessage);
8625                }
8626
8627                if (requiredInstructionSet == null) {
8628                    requiredInstructionSet = instructionSet;
8629                    requirer = ps;
8630                }
8631            }
8632        }
8633
8634        if (requiredInstructionSet != null) {
8635            String adjustedAbi;
8636            if (requirer != null) {
8637                // requirer != null implies that either scannedPackage was null or that scannedPackage
8638                // did not require an ABI, in which case we have to adjust scannedPackage to match
8639                // the ABI of the set (which is the same as requirer's ABI)
8640                adjustedAbi = requirer.primaryCpuAbiString;
8641                if (scannedPackage != null) {
8642                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8643                }
8644            } else {
8645                // requirer == null implies that we're updating all ABIs in the set to
8646                // match scannedPackage.
8647                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8648            }
8649
8650            for (PackageSetting ps : packagesForUser) {
8651                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8652                    if (ps.primaryCpuAbiString != null) {
8653                        continue;
8654                    }
8655
8656                    ps.primaryCpuAbiString = adjustedAbi;
8657                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8658                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8659                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8660                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8661                                + " (requirer="
8662                                + (requirer == null ? "null" : requirer.pkg.packageName)
8663                                + ", scannedPackage="
8664                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8665                                + ")");
8666                        try {
8667                            mInstaller.rmdex(ps.codePathString,
8668                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8669                        } catch (InstallerException ignored) {
8670                        }
8671                    }
8672                }
8673            }
8674        }
8675    }
8676
8677    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8678        synchronized (mPackages) {
8679            mResolverReplaced = true;
8680            // Set up information for custom user intent resolution activity.
8681            mResolveActivity.applicationInfo = pkg.applicationInfo;
8682            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8683            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8684            mResolveActivity.processName = pkg.applicationInfo.packageName;
8685            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8686            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8687                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8688            mResolveActivity.theme = 0;
8689            mResolveActivity.exported = true;
8690            mResolveActivity.enabled = true;
8691            mResolveInfo.activityInfo = mResolveActivity;
8692            mResolveInfo.priority = 0;
8693            mResolveInfo.preferredOrder = 0;
8694            mResolveInfo.match = 0;
8695            mResolveComponentName = mCustomResolverComponentName;
8696            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8697                    mResolveComponentName);
8698        }
8699    }
8700
8701    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8702        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8703
8704        // Set up information for ephemeral installer activity
8705        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8706        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8707        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8708        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8709        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8710        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8711                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8712        mEphemeralInstallerActivity.theme = 0;
8713        mEphemeralInstallerActivity.exported = true;
8714        mEphemeralInstallerActivity.enabled = true;
8715        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8716        mEphemeralInstallerInfo.priority = 0;
8717        mEphemeralInstallerInfo.preferredOrder = 0;
8718        mEphemeralInstallerInfo.match = 0;
8719
8720        if (DEBUG_EPHEMERAL) {
8721            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8722        }
8723    }
8724
8725    private static String calculateBundledApkRoot(final String codePathString) {
8726        final File codePath = new File(codePathString);
8727        final File codeRoot;
8728        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8729            codeRoot = Environment.getRootDirectory();
8730        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8731            codeRoot = Environment.getOemDirectory();
8732        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8733            codeRoot = Environment.getVendorDirectory();
8734        } else {
8735            // Unrecognized code path; take its top real segment as the apk root:
8736            // e.g. /something/app/blah.apk => /something
8737            try {
8738                File f = codePath.getCanonicalFile();
8739                File parent = f.getParentFile();    // non-null because codePath is a file
8740                File tmp;
8741                while ((tmp = parent.getParentFile()) != null) {
8742                    f = parent;
8743                    parent = tmp;
8744                }
8745                codeRoot = f;
8746                Slog.w(TAG, "Unrecognized code path "
8747                        + codePath + " - using " + codeRoot);
8748            } catch (IOException e) {
8749                // Can't canonicalize the code path -- shenanigans?
8750                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8751                return Environment.getRootDirectory().getPath();
8752            }
8753        }
8754        return codeRoot.getPath();
8755    }
8756
8757    /**
8758     * Derive and set the location of native libraries for the given package,
8759     * which varies depending on where and how the package was installed.
8760     */
8761    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8762        final ApplicationInfo info = pkg.applicationInfo;
8763        final String codePath = pkg.codePath;
8764        final File codeFile = new File(codePath);
8765        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8766        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8767
8768        info.nativeLibraryRootDir = null;
8769        info.nativeLibraryRootRequiresIsa = false;
8770        info.nativeLibraryDir = null;
8771        info.secondaryNativeLibraryDir = null;
8772
8773        if (isApkFile(codeFile)) {
8774            // Monolithic install
8775            if (bundledApp) {
8776                // If "/system/lib64/apkname" exists, assume that is the per-package
8777                // native library directory to use; otherwise use "/system/lib/apkname".
8778                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8779                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8780                        getPrimaryInstructionSet(info));
8781
8782                // This is a bundled system app so choose the path based on the ABI.
8783                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8784                // is just the default path.
8785                final String apkName = deriveCodePathName(codePath);
8786                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8787                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8788                        apkName).getAbsolutePath();
8789
8790                if (info.secondaryCpuAbi != null) {
8791                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8792                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8793                            secondaryLibDir, apkName).getAbsolutePath();
8794                }
8795            } else if (asecApp) {
8796                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8797                        .getAbsolutePath();
8798            } else {
8799                final String apkName = deriveCodePathName(codePath);
8800                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8801                        .getAbsolutePath();
8802            }
8803
8804            info.nativeLibraryRootRequiresIsa = false;
8805            info.nativeLibraryDir = info.nativeLibraryRootDir;
8806        } else {
8807            // Cluster install
8808            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8809            info.nativeLibraryRootRequiresIsa = true;
8810
8811            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8812                    getPrimaryInstructionSet(info)).getAbsolutePath();
8813
8814            if (info.secondaryCpuAbi != null) {
8815                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8816                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8817            }
8818        }
8819    }
8820
8821    /**
8822     * Calculate the abis and roots for a bundled app. These can uniquely
8823     * be determined from the contents of the system partition, i.e whether
8824     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8825     * of this information, and instead assume that the system was built
8826     * sensibly.
8827     */
8828    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8829                                           PackageSetting pkgSetting) {
8830        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8831
8832        // If "/system/lib64/apkname" exists, assume that is the per-package
8833        // native library directory to use; otherwise use "/system/lib/apkname".
8834        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8835        setBundledAppAbi(pkg, apkRoot, apkName);
8836        // pkgSetting might be null during rescan following uninstall of updates
8837        // to a bundled app, so accommodate that possibility.  The settings in
8838        // that case will be established later from the parsed package.
8839        //
8840        // If the settings aren't null, sync them up with what we've just derived.
8841        // note that apkRoot isn't stored in the package settings.
8842        if (pkgSetting != null) {
8843            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8844            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8845        }
8846    }
8847
8848    /**
8849     * Deduces the ABI of a bundled app and sets the relevant fields on the
8850     * parsed pkg object.
8851     *
8852     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8853     *        under which system libraries are installed.
8854     * @param apkName the name of the installed package.
8855     */
8856    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8857        final File codeFile = new File(pkg.codePath);
8858
8859        final boolean has64BitLibs;
8860        final boolean has32BitLibs;
8861        if (isApkFile(codeFile)) {
8862            // Monolithic install
8863            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8864            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8865        } else {
8866            // Cluster install
8867            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8868            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8869                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8870                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8871                has64BitLibs = (new File(rootDir, isa)).exists();
8872            } else {
8873                has64BitLibs = false;
8874            }
8875            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8876                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8877                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8878                has32BitLibs = (new File(rootDir, isa)).exists();
8879            } else {
8880                has32BitLibs = false;
8881            }
8882        }
8883
8884        if (has64BitLibs && !has32BitLibs) {
8885            // The package has 64 bit libs, but not 32 bit libs. Its primary
8886            // ABI should be 64 bit. We can safely assume here that the bundled
8887            // native libraries correspond to the most preferred ABI in the list.
8888
8889            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8890            pkg.applicationInfo.secondaryCpuAbi = null;
8891        } else if (has32BitLibs && !has64BitLibs) {
8892            // The package has 32 bit libs but not 64 bit libs. Its primary
8893            // ABI should be 32 bit.
8894
8895            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8896            pkg.applicationInfo.secondaryCpuAbi = null;
8897        } else if (has32BitLibs && has64BitLibs) {
8898            // The application has both 64 and 32 bit bundled libraries. We check
8899            // here that the app declares multiArch support, and warn if it doesn't.
8900            //
8901            // We will be lenient here and record both ABIs. The primary will be the
8902            // ABI that's higher on the list, i.e, a device that's configured to prefer
8903            // 64 bit apps will see a 64 bit primary ABI,
8904
8905            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8906                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8907            }
8908
8909            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8910                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8911                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8912            } else {
8913                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8914                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8915            }
8916        } else {
8917            pkg.applicationInfo.primaryCpuAbi = null;
8918            pkg.applicationInfo.secondaryCpuAbi = null;
8919        }
8920    }
8921
8922    private void killPackage(PackageParser.Package pkg, String reason) {
8923        // Kill the parent package
8924        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8925        // Kill the child packages
8926        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8927        for (int i = 0; i < childCount; i++) {
8928            PackageParser.Package childPkg = pkg.childPackages.get(i);
8929            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8930        }
8931    }
8932
8933    private void killApplication(String pkgName, int appId, String reason) {
8934        // Request the ActivityManager to kill the process(only for existing packages)
8935        // so that we do not end up in a confused state while the user is still using the older
8936        // version of the application while the new one gets installed.
8937        IActivityManager am = ActivityManagerNative.getDefault();
8938        if (am != null) {
8939            try {
8940                am.killApplicationWithAppId(pkgName, appId, reason);
8941            } catch (RemoteException e) {
8942            }
8943        }
8944    }
8945
8946    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8947        // Remove the parent package setting
8948        PackageSetting ps = (PackageSetting) pkg.mExtras;
8949        if (ps != null) {
8950            removePackageLI(ps, chatty);
8951        }
8952        // Remove the child package setting
8953        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8954        for (int i = 0; i < childCount; i++) {
8955            PackageParser.Package childPkg = pkg.childPackages.get(i);
8956            ps = (PackageSetting) childPkg.mExtras;
8957            if (ps != null) {
8958                removePackageLI(ps, chatty);
8959            }
8960        }
8961    }
8962
8963    void removePackageLI(PackageSetting ps, boolean chatty) {
8964        if (DEBUG_INSTALL) {
8965            if (chatty)
8966                Log.d(TAG, "Removing package " + ps.name);
8967        }
8968
8969        // writer
8970        synchronized (mPackages) {
8971            mPackages.remove(ps.name);
8972            final PackageParser.Package pkg = ps.pkg;
8973            if (pkg != null) {
8974                cleanPackageDataStructuresLILPw(pkg, chatty);
8975            }
8976        }
8977    }
8978
8979    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8980        if (DEBUG_INSTALL) {
8981            if (chatty)
8982                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8983        }
8984
8985        // writer
8986        synchronized (mPackages) {
8987            // Remove the parent package
8988            mPackages.remove(pkg.applicationInfo.packageName);
8989            cleanPackageDataStructuresLILPw(pkg, chatty);
8990
8991            // Remove the child packages
8992            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8993            for (int i = 0; i < childCount; i++) {
8994                PackageParser.Package childPkg = pkg.childPackages.get(i);
8995                mPackages.remove(childPkg.applicationInfo.packageName);
8996                cleanPackageDataStructuresLILPw(childPkg, chatty);
8997            }
8998        }
8999    }
9000
9001    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9002        int N = pkg.providers.size();
9003        StringBuilder r = null;
9004        int i;
9005        for (i=0; i<N; i++) {
9006            PackageParser.Provider p = pkg.providers.get(i);
9007            mProviders.removeProvider(p);
9008            if (p.info.authority == null) {
9009
9010                /* There was another ContentProvider with this authority when
9011                 * this app was installed so this authority is null,
9012                 * Ignore it as we don't have to unregister the provider.
9013                 */
9014                continue;
9015            }
9016            String names[] = p.info.authority.split(";");
9017            for (int j = 0; j < names.length; j++) {
9018                if (mProvidersByAuthority.get(names[j]) == p) {
9019                    mProvidersByAuthority.remove(names[j]);
9020                    if (DEBUG_REMOVE) {
9021                        if (chatty)
9022                            Log.d(TAG, "Unregistered content provider: " + names[j]
9023                                    + ", className = " + p.info.name + ", isSyncable = "
9024                                    + p.info.isSyncable);
9025                    }
9026                }
9027            }
9028            if (DEBUG_REMOVE && chatty) {
9029                if (r == null) {
9030                    r = new StringBuilder(256);
9031                } else {
9032                    r.append(' ');
9033                }
9034                r.append(p.info.name);
9035            }
9036        }
9037        if (r != null) {
9038            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9039        }
9040
9041        N = pkg.services.size();
9042        r = null;
9043        for (i=0; i<N; i++) {
9044            PackageParser.Service s = pkg.services.get(i);
9045            mServices.removeService(s);
9046            if (chatty) {
9047                if (r == null) {
9048                    r = new StringBuilder(256);
9049                } else {
9050                    r.append(' ');
9051                }
9052                r.append(s.info.name);
9053            }
9054        }
9055        if (r != null) {
9056            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9057        }
9058
9059        N = pkg.receivers.size();
9060        r = null;
9061        for (i=0; i<N; i++) {
9062            PackageParser.Activity a = pkg.receivers.get(i);
9063            mReceivers.removeActivity(a, "receiver");
9064            if (DEBUG_REMOVE && chatty) {
9065                if (r == null) {
9066                    r = new StringBuilder(256);
9067                } else {
9068                    r.append(' ');
9069                }
9070                r.append(a.info.name);
9071            }
9072        }
9073        if (r != null) {
9074            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9075        }
9076
9077        N = pkg.activities.size();
9078        r = null;
9079        for (i=0; i<N; i++) {
9080            PackageParser.Activity a = pkg.activities.get(i);
9081            mActivities.removeActivity(a, "activity");
9082            if (DEBUG_REMOVE && chatty) {
9083                if (r == null) {
9084                    r = new StringBuilder(256);
9085                } else {
9086                    r.append(' ');
9087                }
9088                r.append(a.info.name);
9089            }
9090        }
9091        if (r != null) {
9092            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9093        }
9094
9095        N = pkg.permissions.size();
9096        r = null;
9097        for (i=0; i<N; i++) {
9098            PackageParser.Permission p = pkg.permissions.get(i);
9099            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9100            if (bp == null) {
9101                bp = mSettings.mPermissionTrees.get(p.info.name);
9102            }
9103            if (bp != null && bp.perm == p) {
9104                bp.perm = null;
9105                if (DEBUG_REMOVE && chatty) {
9106                    if (r == null) {
9107                        r = new StringBuilder(256);
9108                    } else {
9109                        r.append(' ');
9110                    }
9111                    r.append(p.info.name);
9112                }
9113            }
9114            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9115                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9116                if (appOpPkgs != null) {
9117                    appOpPkgs.remove(pkg.packageName);
9118                }
9119            }
9120        }
9121        if (r != null) {
9122            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9123        }
9124
9125        N = pkg.requestedPermissions.size();
9126        r = null;
9127        for (i=0; i<N; i++) {
9128            String perm = pkg.requestedPermissions.get(i);
9129            BasePermission bp = mSettings.mPermissions.get(perm);
9130            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9131                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9132                if (appOpPkgs != null) {
9133                    appOpPkgs.remove(pkg.packageName);
9134                    if (appOpPkgs.isEmpty()) {
9135                        mAppOpPermissionPackages.remove(perm);
9136                    }
9137                }
9138            }
9139        }
9140        if (r != null) {
9141            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9142        }
9143
9144        N = pkg.instrumentation.size();
9145        r = null;
9146        for (i=0; i<N; i++) {
9147            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9148            mInstrumentation.remove(a.getComponentName());
9149            if (DEBUG_REMOVE && chatty) {
9150                if (r == null) {
9151                    r = new StringBuilder(256);
9152                } else {
9153                    r.append(' ');
9154                }
9155                r.append(a.info.name);
9156            }
9157        }
9158        if (r != null) {
9159            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9160        }
9161
9162        r = null;
9163        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9164            // Only system apps can hold shared libraries.
9165            if (pkg.libraryNames != null) {
9166                for (i=0; i<pkg.libraryNames.size(); i++) {
9167                    String name = pkg.libraryNames.get(i);
9168                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9169                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9170                        mSharedLibraries.remove(name);
9171                        if (DEBUG_REMOVE && chatty) {
9172                            if (r == null) {
9173                                r = new StringBuilder(256);
9174                            } else {
9175                                r.append(' ');
9176                            }
9177                            r.append(name);
9178                        }
9179                    }
9180                }
9181            }
9182        }
9183        if (r != null) {
9184            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9185        }
9186    }
9187
9188    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9189        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9190            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9191                return true;
9192            }
9193        }
9194        return false;
9195    }
9196
9197    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9198    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9199    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9200
9201    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9202        // Update the parent permissions
9203        updatePermissionsLPw(pkg.packageName, pkg, flags);
9204        // Update the child permissions
9205        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9206        for (int i = 0; i < childCount; i++) {
9207            PackageParser.Package childPkg = pkg.childPackages.get(i);
9208            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9209        }
9210    }
9211
9212    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9213            int flags) {
9214        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9215        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9216    }
9217
9218    private void updatePermissionsLPw(String changingPkg,
9219            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9220        // Make sure there are no dangling permission trees.
9221        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9222        while (it.hasNext()) {
9223            final BasePermission bp = it.next();
9224            if (bp.packageSetting == null) {
9225                // We may not yet have parsed the package, so just see if
9226                // we still know about its settings.
9227                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9228            }
9229            if (bp.packageSetting == null) {
9230                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9231                        + " from package " + bp.sourcePackage);
9232                it.remove();
9233            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9234                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9235                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9236                            + " from package " + bp.sourcePackage);
9237                    flags |= UPDATE_PERMISSIONS_ALL;
9238                    it.remove();
9239                }
9240            }
9241        }
9242
9243        // Make sure all dynamic permissions have been assigned to a package,
9244        // and make sure there are no dangling permissions.
9245        it = mSettings.mPermissions.values().iterator();
9246        while (it.hasNext()) {
9247            final BasePermission bp = it.next();
9248            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9249                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9250                        + bp.name + " pkg=" + bp.sourcePackage
9251                        + " info=" + bp.pendingInfo);
9252                if (bp.packageSetting == null && bp.pendingInfo != null) {
9253                    final BasePermission tree = findPermissionTreeLP(bp.name);
9254                    if (tree != null && tree.perm != null) {
9255                        bp.packageSetting = tree.packageSetting;
9256                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9257                                new PermissionInfo(bp.pendingInfo));
9258                        bp.perm.info.packageName = tree.perm.info.packageName;
9259                        bp.perm.info.name = bp.name;
9260                        bp.uid = tree.uid;
9261                    }
9262                }
9263            }
9264            if (bp.packageSetting == null) {
9265                // We may not yet have parsed the package, so just see if
9266                // we still know about its settings.
9267                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9268            }
9269            if (bp.packageSetting == null) {
9270                Slog.w(TAG, "Removing dangling permission: " + bp.name
9271                        + " from package " + bp.sourcePackage);
9272                it.remove();
9273            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9274                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9275                    Slog.i(TAG, "Removing old permission: " + bp.name
9276                            + " from package " + bp.sourcePackage);
9277                    flags |= UPDATE_PERMISSIONS_ALL;
9278                    it.remove();
9279                }
9280            }
9281        }
9282
9283        // Now update the permissions for all packages, in particular
9284        // replace the granted permissions of the system packages.
9285        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9286            for (PackageParser.Package pkg : mPackages.values()) {
9287                if (pkg != pkgInfo) {
9288                    // Only replace for packages on requested volume
9289                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9290                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9291                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9292                    grantPermissionsLPw(pkg, replace, changingPkg);
9293                }
9294            }
9295        }
9296
9297        if (pkgInfo != null) {
9298            // Only replace for packages on requested volume
9299            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9300            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9301                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9302            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9303        }
9304    }
9305
9306    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9307            String packageOfInterest) {
9308        // IMPORTANT: There are two types of permissions: install and runtime.
9309        // Install time permissions are granted when the app is installed to
9310        // all device users and users added in the future. Runtime permissions
9311        // are granted at runtime explicitly to specific users. Normal and signature
9312        // protected permissions are install time permissions. Dangerous permissions
9313        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9314        // otherwise they are runtime permissions. This function does not manage
9315        // runtime permissions except for the case an app targeting Lollipop MR1
9316        // being upgraded to target a newer SDK, in which case dangerous permissions
9317        // are transformed from install time to runtime ones.
9318
9319        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9320        if (ps == null) {
9321            return;
9322        }
9323
9324        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9325
9326        PermissionsState permissionsState = ps.getPermissionsState();
9327        PermissionsState origPermissions = permissionsState;
9328
9329        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9330
9331        boolean runtimePermissionsRevoked = false;
9332        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9333
9334        boolean changedInstallPermission = false;
9335
9336        if (replace) {
9337            ps.installPermissionsFixed = false;
9338            if (!ps.isSharedUser()) {
9339                origPermissions = new PermissionsState(permissionsState);
9340                permissionsState.reset();
9341            } else {
9342                // We need to know only about runtime permission changes since the
9343                // calling code always writes the install permissions state but
9344                // the runtime ones are written only if changed. The only cases of
9345                // changed runtime permissions here are promotion of an install to
9346                // runtime and revocation of a runtime from a shared user.
9347                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9348                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9349                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9350                    runtimePermissionsRevoked = true;
9351                }
9352            }
9353        }
9354
9355        permissionsState.setGlobalGids(mGlobalGids);
9356
9357        final int N = pkg.requestedPermissions.size();
9358        for (int i=0; i<N; i++) {
9359            final String name = pkg.requestedPermissions.get(i);
9360            final BasePermission bp = mSettings.mPermissions.get(name);
9361
9362            if (DEBUG_INSTALL) {
9363                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9364            }
9365
9366            if (bp == null || bp.packageSetting == null) {
9367                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9368                    Slog.w(TAG, "Unknown permission " + name
9369                            + " in package " + pkg.packageName);
9370                }
9371                continue;
9372            }
9373
9374            final String perm = bp.name;
9375            boolean allowedSig = false;
9376            int grant = GRANT_DENIED;
9377
9378            // Keep track of app op permissions.
9379            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9380                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9381                if (pkgs == null) {
9382                    pkgs = new ArraySet<>();
9383                    mAppOpPermissionPackages.put(bp.name, pkgs);
9384                }
9385                pkgs.add(pkg.packageName);
9386            }
9387
9388            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9389            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9390                    >= Build.VERSION_CODES.M;
9391            switch (level) {
9392                case PermissionInfo.PROTECTION_NORMAL: {
9393                    // For all apps normal permissions are install time ones.
9394                    grant = GRANT_INSTALL;
9395                } break;
9396
9397                case PermissionInfo.PROTECTION_DANGEROUS: {
9398                    // If a permission review is required for legacy apps we represent
9399                    // their permissions as always granted runtime ones since we need
9400                    // to keep the review required permission flag per user while an
9401                    // install permission's state is shared across all users.
9402                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9403                        // For legacy apps dangerous permissions are install time ones.
9404                        grant = GRANT_INSTALL;
9405                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9406                        // For legacy apps that became modern, install becomes runtime.
9407                        grant = GRANT_UPGRADE;
9408                    } else if (mPromoteSystemApps
9409                            && isSystemApp(ps)
9410                            && mExistingSystemPackages.contains(ps.name)) {
9411                        // For legacy system apps, install becomes runtime.
9412                        // We cannot check hasInstallPermission() for system apps since those
9413                        // permissions were granted implicitly and not persisted pre-M.
9414                        grant = GRANT_UPGRADE;
9415                    } else {
9416                        // For modern apps keep runtime permissions unchanged.
9417                        grant = GRANT_RUNTIME;
9418                    }
9419                } break;
9420
9421                case PermissionInfo.PROTECTION_SIGNATURE: {
9422                    // For all apps signature permissions are install time ones.
9423                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9424                    if (allowedSig) {
9425                        grant = GRANT_INSTALL;
9426                    }
9427                } break;
9428            }
9429
9430            if (DEBUG_INSTALL) {
9431                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9432            }
9433
9434            if (grant != GRANT_DENIED) {
9435                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9436                    // If this is an existing, non-system package, then
9437                    // we can't add any new permissions to it.
9438                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9439                        // Except...  if this is a permission that was added
9440                        // to the platform (note: need to only do this when
9441                        // updating the platform).
9442                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9443                            grant = GRANT_DENIED;
9444                        }
9445                    }
9446                }
9447
9448                switch (grant) {
9449                    case GRANT_INSTALL: {
9450                        // Revoke this as runtime permission to handle the case of
9451                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9452                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9453                            if (origPermissions.getRuntimePermissionState(
9454                                    bp.name, userId) != null) {
9455                                // Revoke the runtime permission and clear the flags.
9456                                origPermissions.revokeRuntimePermission(bp, userId);
9457                                origPermissions.updatePermissionFlags(bp, userId,
9458                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9459                                // If we revoked a permission permission, we have to write.
9460                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9461                                        changedRuntimePermissionUserIds, userId);
9462                            }
9463                        }
9464                        // Grant an install permission.
9465                        if (permissionsState.grantInstallPermission(bp) !=
9466                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9467                            changedInstallPermission = true;
9468                        }
9469                    } break;
9470
9471                    case GRANT_RUNTIME: {
9472                        // Grant previously granted runtime permissions.
9473                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9474                            PermissionState permissionState = origPermissions
9475                                    .getRuntimePermissionState(bp.name, userId);
9476                            int flags = permissionState != null
9477                                    ? permissionState.getFlags() : 0;
9478                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9479                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9480                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9481                                    // If we cannot put the permission as it was, we have to write.
9482                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9483                                            changedRuntimePermissionUserIds, userId);
9484                                }
9485                                // If the app supports runtime permissions no need for a review.
9486                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9487                                        && appSupportsRuntimePermissions
9488                                        && (flags & PackageManager
9489                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9490                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9491                                    // Since we changed the flags, we have to write.
9492                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9493                                            changedRuntimePermissionUserIds, userId);
9494                                }
9495                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9496                                    && !appSupportsRuntimePermissions) {
9497                                // For legacy apps that need a permission review, every new
9498                                // runtime permission is granted but it is pending a review.
9499                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9500                                    permissionsState.grantRuntimePermission(bp, userId);
9501                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9502                                    // We changed the permission and flags, hence have to write.
9503                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9504                                            changedRuntimePermissionUserIds, userId);
9505                                }
9506                            }
9507                            // Propagate the permission flags.
9508                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9509                        }
9510                    } break;
9511
9512                    case GRANT_UPGRADE: {
9513                        // Grant runtime permissions for a previously held install permission.
9514                        PermissionState permissionState = origPermissions
9515                                .getInstallPermissionState(bp.name);
9516                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9517
9518                        if (origPermissions.revokeInstallPermission(bp)
9519                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9520                            // We will be transferring the permission flags, so clear them.
9521                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9522                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9523                            changedInstallPermission = true;
9524                        }
9525
9526                        // If the permission is not to be promoted to runtime we ignore it and
9527                        // also its other flags as they are not applicable to install permissions.
9528                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9529                            for (int userId : currentUserIds) {
9530                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9531                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9532                                    // Transfer the permission flags.
9533                                    permissionsState.updatePermissionFlags(bp, userId,
9534                                            flags, flags);
9535                                    // If we granted the permission, we have to write.
9536                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9537                                            changedRuntimePermissionUserIds, userId);
9538                                }
9539                            }
9540                        }
9541                    } break;
9542
9543                    default: {
9544                        if (packageOfInterest == null
9545                                || packageOfInterest.equals(pkg.packageName)) {
9546                            Slog.w(TAG, "Not granting permission " + perm
9547                                    + " to package " + pkg.packageName
9548                                    + " because it was previously installed without");
9549                        }
9550                    } break;
9551                }
9552            } else {
9553                if (permissionsState.revokeInstallPermission(bp) !=
9554                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9555                    // Also drop the permission flags.
9556                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9557                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9558                    changedInstallPermission = true;
9559                    Slog.i(TAG, "Un-granting permission " + perm
9560                            + " from package " + pkg.packageName
9561                            + " (protectionLevel=" + bp.protectionLevel
9562                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9563                            + ")");
9564                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9565                    // Don't print warning for app op permissions, since it is fine for them
9566                    // not to be granted, there is a UI for the user to decide.
9567                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9568                        Slog.w(TAG, "Not granting permission " + perm
9569                                + " to package " + pkg.packageName
9570                                + " (protectionLevel=" + bp.protectionLevel
9571                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9572                                + ")");
9573                    }
9574                }
9575            }
9576        }
9577
9578        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9579                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9580            // This is the first that we have heard about this package, so the
9581            // permissions we have now selected are fixed until explicitly
9582            // changed.
9583            ps.installPermissionsFixed = true;
9584        }
9585
9586        // Persist the runtime permissions state for users with changes. If permissions
9587        // were revoked because no app in the shared user declares them we have to
9588        // write synchronously to avoid losing runtime permissions state.
9589        for (int userId : changedRuntimePermissionUserIds) {
9590            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9591        }
9592
9593        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9594    }
9595
9596    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9597        boolean allowed = false;
9598        final int NP = PackageParser.NEW_PERMISSIONS.length;
9599        for (int ip=0; ip<NP; ip++) {
9600            final PackageParser.NewPermissionInfo npi
9601                    = PackageParser.NEW_PERMISSIONS[ip];
9602            if (npi.name.equals(perm)
9603                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9604                allowed = true;
9605                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9606                        + pkg.packageName);
9607                break;
9608            }
9609        }
9610        return allowed;
9611    }
9612
9613    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9614            BasePermission bp, PermissionsState origPermissions) {
9615        boolean allowed;
9616        allowed = (compareSignatures(
9617                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9618                        == PackageManager.SIGNATURE_MATCH)
9619                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9620                        == PackageManager.SIGNATURE_MATCH);
9621        if (!allowed && (bp.protectionLevel
9622                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9623            if (isSystemApp(pkg)) {
9624                // For updated system applications, a system permission
9625                // is granted only if it had been defined by the original application.
9626                if (pkg.isUpdatedSystemApp()) {
9627                    final PackageSetting sysPs = mSettings
9628                            .getDisabledSystemPkgLPr(pkg.packageName);
9629                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9630                        // If the original was granted this permission, we take
9631                        // that grant decision as read and propagate it to the
9632                        // update.
9633                        if (sysPs.isPrivileged()) {
9634                            allowed = true;
9635                        }
9636                    } else {
9637                        // The system apk may have been updated with an older
9638                        // version of the one on the data partition, but which
9639                        // granted a new system permission that it didn't have
9640                        // before.  In this case we do want to allow the app to
9641                        // now get the new permission if the ancestral apk is
9642                        // privileged to get it.
9643                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9644                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9645                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9646                                    allowed = true;
9647                                    break;
9648                                }
9649                            }
9650                        }
9651                        // Also if a privileged parent package on the system image or any of
9652                        // its children requested a privileged permission, the updated child
9653                        // packages can also get the permission.
9654                        if (pkg.parentPackage != null) {
9655                            final PackageSetting disabledSysParentPs = mSettings
9656                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9657                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9658                                    && disabledSysParentPs.isPrivileged()) {
9659                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9660                                    allowed = true;
9661                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9662                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9663                                    for (int i = 0; i < count; i++) {
9664                                        PackageParser.Package disabledSysChildPkg =
9665                                                disabledSysParentPs.pkg.childPackages.get(i);
9666                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9667                                                perm)) {
9668                                            allowed = true;
9669                                            break;
9670                                        }
9671                                    }
9672                                }
9673                            }
9674                        }
9675                    }
9676                } else {
9677                    allowed = isPrivilegedApp(pkg);
9678                }
9679            }
9680        }
9681        if (!allowed) {
9682            if (!allowed && (bp.protectionLevel
9683                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9684                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9685                // If this was a previously normal/dangerous permission that got moved
9686                // to a system permission as part of the runtime permission redesign, then
9687                // we still want to blindly grant it to old apps.
9688                allowed = true;
9689            }
9690            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9691                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9692                // If this permission is to be granted to the system installer and
9693                // this app is an installer, then it gets the permission.
9694                allowed = true;
9695            }
9696            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9697                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9698                // If this permission is to be granted to the system verifier and
9699                // this app is a verifier, then it gets the permission.
9700                allowed = true;
9701            }
9702            if (!allowed && (bp.protectionLevel
9703                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9704                    && isSystemApp(pkg)) {
9705                // Any pre-installed system app is allowed to get this permission.
9706                allowed = true;
9707            }
9708            if (!allowed && (bp.protectionLevel
9709                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9710                // For development permissions, a development permission
9711                // is granted only if it was already granted.
9712                allowed = origPermissions.hasInstallPermission(perm);
9713            }
9714        }
9715        return allowed;
9716    }
9717
9718    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9719        final int permCount = pkg.requestedPermissions.size();
9720        for (int j = 0; j < permCount; j++) {
9721            String requestedPermission = pkg.requestedPermissions.get(j);
9722            if (permission.equals(requestedPermission)) {
9723                return true;
9724            }
9725        }
9726        return false;
9727    }
9728
9729    final class ActivityIntentResolver
9730            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9732                boolean defaultOnly, int userId) {
9733            if (!sUserManager.exists(userId)) return null;
9734            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9735            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9736        }
9737
9738        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9739                int userId) {
9740            if (!sUserManager.exists(userId)) return null;
9741            mFlags = flags;
9742            return super.queryIntent(intent, resolvedType,
9743                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9744        }
9745
9746        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9747                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9748            if (!sUserManager.exists(userId)) return null;
9749            if (packageActivities == null) {
9750                return null;
9751            }
9752            mFlags = flags;
9753            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9754            final int N = packageActivities.size();
9755            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9756                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9757
9758            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9759            for (int i = 0; i < N; ++i) {
9760                intentFilters = packageActivities.get(i).intents;
9761                if (intentFilters != null && intentFilters.size() > 0) {
9762                    PackageParser.ActivityIntentInfo[] array =
9763                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9764                    intentFilters.toArray(array);
9765                    listCut.add(array);
9766                }
9767            }
9768            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9769        }
9770
9771        public final void addActivity(PackageParser.Activity a, String type) {
9772            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9773            mActivities.put(a.getComponentName(), a);
9774            if (DEBUG_SHOW_INFO)
9775                Log.v(
9776                TAG, "  " + type + " " +
9777                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9778            if (DEBUG_SHOW_INFO)
9779                Log.v(TAG, "    Class=" + a.info.name);
9780            final int NI = a.intents.size();
9781            for (int j=0; j<NI; j++) {
9782                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9783                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9784                    intent.setPriority(0);
9785                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9786                            + a.className + " with priority > 0, forcing to 0");
9787                }
9788                if (DEBUG_SHOW_INFO) {
9789                    Log.v(TAG, "    IntentFilter:");
9790                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9791                }
9792                if (!intent.debugCheck()) {
9793                    Log.w(TAG, "==> For Activity " + a.info.name);
9794                }
9795                addFilter(intent);
9796            }
9797        }
9798
9799        public final void removeActivity(PackageParser.Activity a, String type) {
9800            mActivities.remove(a.getComponentName());
9801            if (DEBUG_SHOW_INFO) {
9802                Log.v(TAG, "  " + type + " "
9803                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9804                                : a.info.name) + ":");
9805                Log.v(TAG, "    Class=" + a.info.name);
9806            }
9807            final int NI = a.intents.size();
9808            for (int j=0; j<NI; j++) {
9809                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9810                if (DEBUG_SHOW_INFO) {
9811                    Log.v(TAG, "    IntentFilter:");
9812                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9813                }
9814                removeFilter(intent);
9815            }
9816        }
9817
9818        @Override
9819        protected boolean allowFilterResult(
9820                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9821            ActivityInfo filterAi = filter.activity.info;
9822            for (int i=dest.size()-1; i>=0; i--) {
9823                ActivityInfo destAi = dest.get(i).activityInfo;
9824                if (destAi.name == filterAi.name
9825                        && destAi.packageName == filterAi.packageName) {
9826                    return false;
9827                }
9828            }
9829            return true;
9830        }
9831
9832        @Override
9833        protected ActivityIntentInfo[] newArray(int size) {
9834            return new ActivityIntentInfo[size];
9835        }
9836
9837        @Override
9838        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9839            if (!sUserManager.exists(userId)) return true;
9840            PackageParser.Package p = filter.activity.owner;
9841            if (p != null) {
9842                PackageSetting ps = (PackageSetting)p.mExtras;
9843                if (ps != null) {
9844                    // System apps are never considered stopped for purposes of
9845                    // filtering, because there may be no way for the user to
9846                    // actually re-launch them.
9847                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9848                            && ps.getStopped(userId);
9849                }
9850            }
9851            return false;
9852        }
9853
9854        @Override
9855        protected boolean isPackageForFilter(String packageName,
9856                PackageParser.ActivityIntentInfo info) {
9857            return packageName.equals(info.activity.owner.packageName);
9858        }
9859
9860        @Override
9861        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9862                int match, int userId) {
9863            if (!sUserManager.exists(userId)) return null;
9864            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9865                return null;
9866            }
9867            final PackageParser.Activity activity = info.activity;
9868            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9869            if (ps == null) {
9870                return null;
9871            }
9872            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9873                    ps.readUserState(userId), userId);
9874            if (ai == null) {
9875                return null;
9876            }
9877            final ResolveInfo res = new ResolveInfo();
9878            res.activityInfo = ai;
9879            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9880                res.filter = info;
9881            }
9882            if (info != null) {
9883                res.handleAllWebDataURI = info.handleAllWebDataURI();
9884            }
9885            res.priority = info.getPriority();
9886            res.preferredOrder = activity.owner.mPreferredOrder;
9887            //System.out.println("Result: " + res.activityInfo.className +
9888            //                   " = " + res.priority);
9889            res.match = match;
9890            res.isDefault = info.hasDefault;
9891            res.labelRes = info.labelRes;
9892            res.nonLocalizedLabel = info.nonLocalizedLabel;
9893            if (userNeedsBadging(userId)) {
9894                res.noResourceId = true;
9895            } else {
9896                res.icon = info.icon;
9897            }
9898            res.iconResourceId = info.icon;
9899            res.system = res.activityInfo.applicationInfo.isSystemApp();
9900            return res;
9901        }
9902
9903        @Override
9904        protected void sortResults(List<ResolveInfo> results) {
9905            Collections.sort(results, mResolvePrioritySorter);
9906        }
9907
9908        @Override
9909        protected void dumpFilter(PrintWriter out, String prefix,
9910                PackageParser.ActivityIntentInfo filter) {
9911            out.print(prefix); out.print(
9912                    Integer.toHexString(System.identityHashCode(filter.activity)));
9913                    out.print(' ');
9914                    filter.activity.printComponentShortName(out);
9915                    out.print(" filter ");
9916                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9917        }
9918
9919        @Override
9920        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9921            return filter.activity;
9922        }
9923
9924        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9925            PackageParser.Activity activity = (PackageParser.Activity)label;
9926            out.print(prefix); out.print(
9927                    Integer.toHexString(System.identityHashCode(activity)));
9928                    out.print(' ');
9929                    activity.printComponentShortName(out);
9930            if (count > 1) {
9931                out.print(" ("); out.print(count); out.print(" filters)");
9932            }
9933            out.println();
9934        }
9935
9936//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9937//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9938//            final List<ResolveInfo> retList = Lists.newArrayList();
9939//            while (i.hasNext()) {
9940//                final ResolveInfo resolveInfo = i.next();
9941//                if (isEnabledLP(resolveInfo.activityInfo)) {
9942//                    retList.add(resolveInfo);
9943//                }
9944//            }
9945//            return retList;
9946//        }
9947
9948        // Keys are String (activity class name), values are Activity.
9949        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9950                = new ArrayMap<ComponentName, PackageParser.Activity>();
9951        private int mFlags;
9952    }
9953
9954    private final class ServiceIntentResolver
9955            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9956        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9957                boolean defaultOnly, int userId) {
9958            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9959            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9960        }
9961
9962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9963                int userId) {
9964            if (!sUserManager.exists(userId)) return null;
9965            mFlags = flags;
9966            return super.queryIntent(intent, resolvedType,
9967                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9968        }
9969
9970        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9971                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9972            if (!sUserManager.exists(userId)) return null;
9973            if (packageServices == null) {
9974                return null;
9975            }
9976            mFlags = flags;
9977            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9978            final int N = packageServices.size();
9979            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9980                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9981
9982            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9983            for (int i = 0; i < N; ++i) {
9984                intentFilters = packageServices.get(i).intents;
9985                if (intentFilters != null && intentFilters.size() > 0) {
9986                    PackageParser.ServiceIntentInfo[] array =
9987                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9988                    intentFilters.toArray(array);
9989                    listCut.add(array);
9990                }
9991            }
9992            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9993        }
9994
9995        public final void addService(PackageParser.Service s) {
9996            mServices.put(s.getComponentName(), s);
9997            if (DEBUG_SHOW_INFO) {
9998                Log.v(TAG, "  "
9999                        + (s.info.nonLocalizedLabel != null
10000                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10001                Log.v(TAG, "    Class=" + s.info.name);
10002            }
10003            final int NI = s.intents.size();
10004            int j;
10005            for (j=0; j<NI; j++) {
10006                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10007                if (DEBUG_SHOW_INFO) {
10008                    Log.v(TAG, "    IntentFilter:");
10009                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10010                }
10011                if (!intent.debugCheck()) {
10012                    Log.w(TAG, "==> For Service " + s.info.name);
10013                }
10014                addFilter(intent);
10015            }
10016        }
10017
10018        public final void removeService(PackageParser.Service s) {
10019            mServices.remove(s.getComponentName());
10020            if (DEBUG_SHOW_INFO) {
10021                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10022                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10023                Log.v(TAG, "    Class=" + s.info.name);
10024            }
10025            final int NI = s.intents.size();
10026            int j;
10027            for (j=0; j<NI; j++) {
10028                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10029                if (DEBUG_SHOW_INFO) {
10030                    Log.v(TAG, "    IntentFilter:");
10031                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10032                }
10033                removeFilter(intent);
10034            }
10035        }
10036
10037        @Override
10038        protected boolean allowFilterResult(
10039                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10040            ServiceInfo filterSi = filter.service.info;
10041            for (int i=dest.size()-1; i>=0; i--) {
10042                ServiceInfo destAi = dest.get(i).serviceInfo;
10043                if (destAi.name == filterSi.name
10044                        && destAi.packageName == filterSi.packageName) {
10045                    return false;
10046                }
10047            }
10048            return true;
10049        }
10050
10051        @Override
10052        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10053            return new PackageParser.ServiceIntentInfo[size];
10054        }
10055
10056        @Override
10057        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10058            if (!sUserManager.exists(userId)) return true;
10059            PackageParser.Package p = filter.service.owner;
10060            if (p != null) {
10061                PackageSetting ps = (PackageSetting)p.mExtras;
10062                if (ps != null) {
10063                    // System apps are never considered stopped for purposes of
10064                    // filtering, because there may be no way for the user to
10065                    // actually re-launch them.
10066                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10067                            && ps.getStopped(userId);
10068                }
10069            }
10070            return false;
10071        }
10072
10073        @Override
10074        protected boolean isPackageForFilter(String packageName,
10075                PackageParser.ServiceIntentInfo info) {
10076            return packageName.equals(info.service.owner.packageName);
10077        }
10078
10079        @Override
10080        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10081                int match, int userId) {
10082            if (!sUserManager.exists(userId)) return null;
10083            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10084            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10085                return null;
10086            }
10087            final PackageParser.Service service = info.service;
10088            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10089            if (ps == null) {
10090                return null;
10091            }
10092            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10093                    ps.readUserState(userId), userId);
10094            if (si == null) {
10095                return null;
10096            }
10097            final ResolveInfo res = new ResolveInfo();
10098            res.serviceInfo = si;
10099            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10100                res.filter = filter;
10101            }
10102            res.priority = info.getPriority();
10103            res.preferredOrder = service.owner.mPreferredOrder;
10104            res.match = match;
10105            res.isDefault = info.hasDefault;
10106            res.labelRes = info.labelRes;
10107            res.nonLocalizedLabel = info.nonLocalizedLabel;
10108            res.icon = info.icon;
10109            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10110            return res;
10111        }
10112
10113        @Override
10114        protected void sortResults(List<ResolveInfo> results) {
10115            Collections.sort(results, mResolvePrioritySorter);
10116        }
10117
10118        @Override
10119        protected void dumpFilter(PrintWriter out, String prefix,
10120                PackageParser.ServiceIntentInfo filter) {
10121            out.print(prefix); out.print(
10122                    Integer.toHexString(System.identityHashCode(filter.service)));
10123                    out.print(' ');
10124                    filter.service.printComponentShortName(out);
10125                    out.print(" filter ");
10126                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10127        }
10128
10129        @Override
10130        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10131            return filter.service;
10132        }
10133
10134        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10135            PackageParser.Service service = (PackageParser.Service)label;
10136            out.print(prefix); out.print(
10137                    Integer.toHexString(System.identityHashCode(service)));
10138                    out.print(' ');
10139                    service.printComponentShortName(out);
10140            if (count > 1) {
10141                out.print(" ("); out.print(count); out.print(" filters)");
10142            }
10143            out.println();
10144        }
10145
10146//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10147//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10148//            final List<ResolveInfo> retList = Lists.newArrayList();
10149//            while (i.hasNext()) {
10150//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10151//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10152//                    retList.add(resolveInfo);
10153//                }
10154//            }
10155//            return retList;
10156//        }
10157
10158        // Keys are String (activity class name), values are Activity.
10159        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10160                = new ArrayMap<ComponentName, PackageParser.Service>();
10161        private int mFlags;
10162    };
10163
10164    private final class ProviderIntentResolver
10165            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10166        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10167                boolean defaultOnly, int userId) {
10168            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10169            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10170        }
10171
10172        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10173                int userId) {
10174            if (!sUserManager.exists(userId))
10175                return null;
10176            mFlags = flags;
10177            return super.queryIntent(intent, resolvedType,
10178                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10179        }
10180
10181        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10182                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10183            if (!sUserManager.exists(userId))
10184                return null;
10185            if (packageProviders == null) {
10186                return null;
10187            }
10188            mFlags = flags;
10189            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10190            final int N = packageProviders.size();
10191            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10192                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10193
10194            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10195            for (int i = 0; i < N; ++i) {
10196                intentFilters = packageProviders.get(i).intents;
10197                if (intentFilters != null && intentFilters.size() > 0) {
10198                    PackageParser.ProviderIntentInfo[] array =
10199                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10200                    intentFilters.toArray(array);
10201                    listCut.add(array);
10202                }
10203            }
10204            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10205        }
10206
10207        public final void addProvider(PackageParser.Provider p) {
10208            if (mProviders.containsKey(p.getComponentName())) {
10209                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10210                return;
10211            }
10212
10213            mProviders.put(p.getComponentName(), p);
10214            if (DEBUG_SHOW_INFO) {
10215                Log.v(TAG, "  "
10216                        + (p.info.nonLocalizedLabel != null
10217                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10218                Log.v(TAG, "    Class=" + p.info.name);
10219            }
10220            final int NI = p.intents.size();
10221            int j;
10222            for (j = 0; j < NI; j++) {
10223                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10224                if (DEBUG_SHOW_INFO) {
10225                    Log.v(TAG, "    IntentFilter:");
10226                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10227                }
10228                if (!intent.debugCheck()) {
10229                    Log.w(TAG, "==> For Provider " + p.info.name);
10230                }
10231                addFilter(intent);
10232            }
10233        }
10234
10235        public final void removeProvider(PackageParser.Provider p) {
10236            mProviders.remove(p.getComponentName());
10237            if (DEBUG_SHOW_INFO) {
10238                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10239                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10240                Log.v(TAG, "    Class=" + p.info.name);
10241            }
10242            final int NI = p.intents.size();
10243            int j;
10244            for (j = 0; j < NI; j++) {
10245                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10246                if (DEBUG_SHOW_INFO) {
10247                    Log.v(TAG, "    IntentFilter:");
10248                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10249                }
10250                removeFilter(intent);
10251            }
10252        }
10253
10254        @Override
10255        protected boolean allowFilterResult(
10256                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10257            ProviderInfo filterPi = filter.provider.info;
10258            for (int i = dest.size() - 1; i >= 0; i--) {
10259                ProviderInfo destPi = dest.get(i).providerInfo;
10260                if (destPi.name == filterPi.name
10261                        && destPi.packageName == filterPi.packageName) {
10262                    return false;
10263                }
10264            }
10265            return true;
10266        }
10267
10268        @Override
10269        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10270            return new PackageParser.ProviderIntentInfo[size];
10271        }
10272
10273        @Override
10274        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10275            if (!sUserManager.exists(userId))
10276                return true;
10277            PackageParser.Package p = filter.provider.owner;
10278            if (p != null) {
10279                PackageSetting ps = (PackageSetting) p.mExtras;
10280                if (ps != null) {
10281                    // System apps are never considered stopped for purposes of
10282                    // filtering, because there may be no way for the user to
10283                    // actually re-launch them.
10284                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10285                            && ps.getStopped(userId);
10286                }
10287            }
10288            return false;
10289        }
10290
10291        @Override
10292        protected boolean isPackageForFilter(String packageName,
10293                PackageParser.ProviderIntentInfo info) {
10294            return packageName.equals(info.provider.owner.packageName);
10295        }
10296
10297        @Override
10298        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10299                int match, int userId) {
10300            if (!sUserManager.exists(userId))
10301                return null;
10302            final PackageParser.ProviderIntentInfo info = filter;
10303            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10304                return null;
10305            }
10306            final PackageParser.Provider provider = info.provider;
10307            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10308            if (ps == null) {
10309                return null;
10310            }
10311            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10312                    ps.readUserState(userId), userId);
10313            if (pi == null) {
10314                return null;
10315            }
10316            final ResolveInfo res = new ResolveInfo();
10317            res.providerInfo = pi;
10318            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10319                res.filter = filter;
10320            }
10321            res.priority = info.getPriority();
10322            res.preferredOrder = provider.owner.mPreferredOrder;
10323            res.match = match;
10324            res.isDefault = info.hasDefault;
10325            res.labelRes = info.labelRes;
10326            res.nonLocalizedLabel = info.nonLocalizedLabel;
10327            res.icon = info.icon;
10328            res.system = res.providerInfo.applicationInfo.isSystemApp();
10329            return res;
10330        }
10331
10332        @Override
10333        protected void sortResults(List<ResolveInfo> results) {
10334            Collections.sort(results, mResolvePrioritySorter);
10335        }
10336
10337        @Override
10338        protected void dumpFilter(PrintWriter out, String prefix,
10339                PackageParser.ProviderIntentInfo filter) {
10340            out.print(prefix);
10341            out.print(
10342                    Integer.toHexString(System.identityHashCode(filter.provider)));
10343            out.print(' ');
10344            filter.provider.printComponentShortName(out);
10345            out.print(" filter ");
10346            out.println(Integer.toHexString(System.identityHashCode(filter)));
10347        }
10348
10349        @Override
10350        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10351            return filter.provider;
10352        }
10353
10354        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10355            PackageParser.Provider provider = (PackageParser.Provider)label;
10356            out.print(prefix); out.print(
10357                    Integer.toHexString(System.identityHashCode(provider)));
10358                    out.print(' ');
10359                    provider.printComponentShortName(out);
10360            if (count > 1) {
10361                out.print(" ("); out.print(count); out.print(" filters)");
10362            }
10363            out.println();
10364        }
10365
10366        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10367                = new ArrayMap<ComponentName, PackageParser.Provider>();
10368        private int mFlags;
10369    }
10370
10371    private static final class EphemeralIntentResolver
10372            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10373        @Override
10374        protected EphemeralResolveIntentInfo[] newArray(int size) {
10375            return new EphemeralResolveIntentInfo[size];
10376        }
10377
10378        @Override
10379        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10380            return true;
10381        }
10382
10383        @Override
10384        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10385                int userId) {
10386            if (!sUserManager.exists(userId)) {
10387                return null;
10388            }
10389            return info.getEphemeralResolveInfo();
10390        }
10391    }
10392
10393    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10394            new Comparator<ResolveInfo>() {
10395        public int compare(ResolveInfo r1, ResolveInfo r2) {
10396            int v1 = r1.priority;
10397            int v2 = r2.priority;
10398            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10399            if (v1 != v2) {
10400                return (v1 > v2) ? -1 : 1;
10401            }
10402            v1 = r1.preferredOrder;
10403            v2 = r2.preferredOrder;
10404            if (v1 != v2) {
10405                return (v1 > v2) ? -1 : 1;
10406            }
10407            if (r1.isDefault != r2.isDefault) {
10408                return r1.isDefault ? -1 : 1;
10409            }
10410            v1 = r1.match;
10411            v2 = r2.match;
10412            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10413            if (v1 != v2) {
10414                return (v1 > v2) ? -1 : 1;
10415            }
10416            if (r1.system != r2.system) {
10417                return r1.system ? -1 : 1;
10418            }
10419            if (r1.activityInfo != null) {
10420                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10421            }
10422            if (r1.serviceInfo != null) {
10423                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10424            }
10425            if (r1.providerInfo != null) {
10426                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10427            }
10428            return 0;
10429        }
10430    };
10431
10432    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10433            new Comparator<ProviderInfo>() {
10434        public int compare(ProviderInfo p1, ProviderInfo p2) {
10435            final int v1 = p1.initOrder;
10436            final int v2 = p2.initOrder;
10437            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10438        }
10439    };
10440
10441    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10442            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10443            final int[] userIds) {
10444        mHandler.post(new Runnable() {
10445            @Override
10446            public void run() {
10447                try {
10448                    final IActivityManager am = ActivityManagerNative.getDefault();
10449                    if (am == null) return;
10450                    final int[] resolvedUserIds;
10451                    if (userIds == null) {
10452                        resolvedUserIds = am.getRunningUserIds();
10453                    } else {
10454                        resolvedUserIds = userIds;
10455                    }
10456                    for (int id : resolvedUserIds) {
10457                        final Intent intent = new Intent(action,
10458                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10459                        if (extras != null) {
10460                            intent.putExtras(extras);
10461                        }
10462                        if (targetPkg != null) {
10463                            intent.setPackage(targetPkg);
10464                        }
10465                        // Modify the UID when posting to other users
10466                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10467                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10468                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10469                            intent.putExtra(Intent.EXTRA_UID, uid);
10470                        }
10471                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10472                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10473                        if (DEBUG_BROADCASTS) {
10474                            RuntimeException here = new RuntimeException("here");
10475                            here.fillInStackTrace();
10476                            Slog.d(TAG, "Sending to user " + id + ": "
10477                                    + intent.toShortString(false, true, false, false)
10478                                    + " " + intent.getExtras(), here);
10479                        }
10480                        am.broadcastIntent(null, intent, null, finishedReceiver,
10481                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10482                                null, finishedReceiver != null, false, id);
10483                    }
10484                } catch (RemoteException ex) {
10485                }
10486            }
10487        });
10488    }
10489
10490    /**
10491     * Check if the external storage media is available. This is true if there
10492     * is a mounted external storage medium or if the external storage is
10493     * emulated.
10494     */
10495    private boolean isExternalMediaAvailable() {
10496        return mMediaMounted || Environment.isExternalStorageEmulated();
10497    }
10498
10499    @Override
10500    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10501        // writer
10502        synchronized (mPackages) {
10503            if (!isExternalMediaAvailable()) {
10504                // If the external storage is no longer mounted at this point,
10505                // the caller may not have been able to delete all of this
10506                // packages files and can not delete any more.  Bail.
10507                return null;
10508            }
10509            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10510            if (lastPackage != null) {
10511                pkgs.remove(lastPackage);
10512            }
10513            if (pkgs.size() > 0) {
10514                return pkgs.get(0);
10515            }
10516        }
10517        return null;
10518    }
10519
10520    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10521        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10522                userId, andCode ? 1 : 0, packageName);
10523        if (mSystemReady) {
10524            msg.sendToTarget();
10525        } else {
10526            if (mPostSystemReadyMessages == null) {
10527                mPostSystemReadyMessages = new ArrayList<>();
10528            }
10529            mPostSystemReadyMessages.add(msg);
10530        }
10531    }
10532
10533    void startCleaningPackages() {
10534        // reader
10535        if (!isExternalMediaAvailable()) {
10536            return;
10537        }
10538        synchronized (mPackages) {
10539            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10540                return;
10541            }
10542        }
10543        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10544        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10545        IActivityManager am = ActivityManagerNative.getDefault();
10546        if (am != null) {
10547            try {
10548                am.startService(null, intent, null, mContext.getOpPackageName(),
10549                        UserHandle.USER_SYSTEM);
10550            } catch (RemoteException e) {
10551            }
10552        }
10553    }
10554
10555    @Override
10556    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10557            int installFlags, String installerPackageName, int userId) {
10558        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10559
10560        final int callingUid = Binder.getCallingUid();
10561        enforceCrossUserPermission(callingUid, userId,
10562                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10563
10564        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10565            try {
10566                if (observer != null) {
10567                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10568                }
10569            } catch (RemoteException re) {
10570            }
10571            return;
10572        }
10573
10574        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10575            installFlags |= PackageManager.INSTALL_FROM_ADB;
10576
10577        } else {
10578            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10579            // about installerPackageName.
10580
10581            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10582            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10583        }
10584
10585        UserHandle user;
10586        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10587            user = UserHandle.ALL;
10588        } else {
10589            user = new UserHandle(userId);
10590        }
10591
10592        // Only system components can circumvent runtime permissions when installing.
10593        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10594                && mContext.checkCallingOrSelfPermission(Manifest.permission
10595                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10596            throw new SecurityException("You need the "
10597                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10598                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10599        }
10600
10601        final File originFile = new File(originPath);
10602        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10603
10604        final Message msg = mHandler.obtainMessage(INIT_COPY);
10605        final VerificationInfo verificationInfo = new VerificationInfo(
10606                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10607        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10608                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10609                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10610        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10611        msg.obj = params;
10612
10613        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10614                System.identityHashCode(msg.obj));
10615        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10616                System.identityHashCode(msg.obj));
10617
10618        mHandler.sendMessage(msg);
10619    }
10620
10621    void installStage(String packageName, File stagedDir, String stagedCid,
10622            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10623            String installerPackageName, int installerUid, UserHandle user) {
10624        if (DEBUG_EPHEMERAL) {
10625            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10626                Slog.d(TAG, "Ephemeral install of " + packageName);
10627            }
10628        }
10629        final VerificationInfo verificationInfo = new VerificationInfo(
10630                sessionParams.originatingUri, sessionParams.referrerUri,
10631                sessionParams.originatingUid, installerUid);
10632
10633        final OriginInfo origin;
10634        if (stagedDir != null) {
10635            origin = OriginInfo.fromStagedFile(stagedDir);
10636        } else {
10637            origin = OriginInfo.fromStagedContainer(stagedCid);
10638        }
10639
10640        final Message msg = mHandler.obtainMessage(INIT_COPY);
10641        final InstallParams params = new InstallParams(origin, null, observer,
10642                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10643                verificationInfo, user, sessionParams.abiOverride,
10644                sessionParams.grantedRuntimePermissions);
10645        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10646        msg.obj = params;
10647
10648        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10649                System.identityHashCode(msg.obj));
10650        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10651                System.identityHashCode(msg.obj));
10652
10653        mHandler.sendMessage(msg);
10654    }
10655
10656    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10657            int userId) {
10658        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10659        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10660    }
10661
10662    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10663            int appId, int userId) {
10664        Bundle extras = new Bundle(1);
10665        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10666
10667        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10668                packageName, extras, 0, null, null, new int[] {userId});
10669        try {
10670            IActivityManager am = ActivityManagerNative.getDefault();
10671            if (isSystem && am.isUserRunning(userId, 0)) {
10672                // The just-installed/enabled app is bundled on the system, so presumed
10673                // to be able to run automatically without needing an explicit launch.
10674                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10675                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10676                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10677                        .setPackage(packageName);
10678                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10679                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10680            }
10681        } catch (RemoteException e) {
10682            // shouldn't happen
10683            Slog.w(TAG, "Unable to bootstrap installed package", e);
10684        }
10685    }
10686
10687    @Override
10688    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10689            int userId) {
10690        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10691        PackageSetting pkgSetting;
10692        final int uid = Binder.getCallingUid();
10693        enforceCrossUserPermission(uid, userId,
10694                true /* requireFullPermission */, true /* checkShell */,
10695                "setApplicationHiddenSetting for user " + userId);
10696
10697        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10698            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10699            return false;
10700        }
10701
10702        long callingId = Binder.clearCallingIdentity();
10703        try {
10704            boolean sendAdded = false;
10705            boolean sendRemoved = false;
10706            // writer
10707            synchronized (mPackages) {
10708                pkgSetting = mSettings.mPackages.get(packageName);
10709                if (pkgSetting == null) {
10710                    return false;
10711                }
10712                if (pkgSetting.getHidden(userId) != hidden) {
10713                    pkgSetting.setHidden(hidden, userId);
10714                    mSettings.writePackageRestrictionsLPr(userId);
10715                    if (hidden) {
10716                        sendRemoved = true;
10717                    } else {
10718                        sendAdded = true;
10719                    }
10720                }
10721            }
10722            if (sendAdded) {
10723                sendPackageAddedForUser(packageName, pkgSetting, userId);
10724                return true;
10725            }
10726            if (sendRemoved) {
10727                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10728                        "hiding pkg");
10729                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10730                return true;
10731            }
10732        } finally {
10733            Binder.restoreCallingIdentity(callingId);
10734        }
10735        return false;
10736    }
10737
10738    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10739            int userId) {
10740        final PackageRemovedInfo info = new PackageRemovedInfo();
10741        info.removedPackage = packageName;
10742        info.removedUsers = new int[] {userId};
10743        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10744        info.sendPackageRemovedBroadcasts(true /*killApp*/);
10745    }
10746
10747    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10748        if (pkgList.length > 0) {
10749            Bundle extras = new Bundle(1);
10750            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10751
10752            sendPackageBroadcast(
10753                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10754                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10755                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10756                    new int[] {userId});
10757        }
10758    }
10759
10760    /**
10761     * Returns true if application is not found or there was an error. Otherwise it returns
10762     * the hidden state of the package for the given user.
10763     */
10764    @Override
10765    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10766        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10767        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10768                true /* requireFullPermission */, false /* checkShell */,
10769                "getApplicationHidden for user " + userId);
10770        PackageSetting pkgSetting;
10771        long callingId = Binder.clearCallingIdentity();
10772        try {
10773            // writer
10774            synchronized (mPackages) {
10775                pkgSetting = mSettings.mPackages.get(packageName);
10776                if (pkgSetting == null) {
10777                    return true;
10778                }
10779                return pkgSetting.getHidden(userId);
10780            }
10781        } finally {
10782            Binder.restoreCallingIdentity(callingId);
10783        }
10784    }
10785
10786    /**
10787     * @hide
10788     */
10789    @Override
10790    public int installExistingPackageAsUser(String packageName, int userId) {
10791        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10792                null);
10793        PackageSetting pkgSetting;
10794        final int uid = Binder.getCallingUid();
10795        enforceCrossUserPermission(uid, userId,
10796                true /* requireFullPermission */, true /* checkShell */,
10797                "installExistingPackage for user " + userId);
10798        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10799            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10800        }
10801
10802        long callingId = Binder.clearCallingIdentity();
10803        try {
10804            boolean installed = false;
10805
10806            // writer
10807            synchronized (mPackages) {
10808                pkgSetting = mSettings.mPackages.get(packageName);
10809                if (pkgSetting == null) {
10810                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10811                }
10812                if (!pkgSetting.getInstalled(userId)) {
10813                    pkgSetting.setInstalled(true, userId);
10814                    pkgSetting.setHidden(false, userId);
10815                    mSettings.writePackageRestrictionsLPr(userId);
10816                    installed = true;
10817                }
10818            }
10819
10820            if (installed) {
10821                if (pkgSetting.pkg != null) {
10822                    prepareAppDataAfterInstall(pkgSetting.pkg);
10823                }
10824                sendPackageAddedForUser(packageName, pkgSetting, userId);
10825            }
10826        } finally {
10827            Binder.restoreCallingIdentity(callingId);
10828        }
10829
10830        return PackageManager.INSTALL_SUCCEEDED;
10831    }
10832
10833    boolean isUserRestricted(int userId, String restrictionKey) {
10834        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10835        if (restrictions.getBoolean(restrictionKey, false)) {
10836            Log.w(TAG, "User is restricted: " + restrictionKey);
10837            return true;
10838        }
10839        return false;
10840    }
10841
10842    @Override
10843    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10844            int userId) {
10845        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10846        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10847                true /* requireFullPermission */, true /* checkShell */,
10848                "setPackagesSuspended for user " + userId);
10849
10850        if (ArrayUtils.isEmpty(packageNames)) {
10851            return packageNames;
10852        }
10853
10854        // List of package names for whom the suspended state has changed.
10855        List<String> changedPackages = new ArrayList<>(packageNames.length);
10856        // List of package names for whom the suspended state is not set as requested in this
10857        // method.
10858        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10859        for (int i = 0; i < packageNames.length; i++) {
10860            String packageName = packageNames[i];
10861            long callingId = Binder.clearCallingIdentity();
10862            try {
10863                boolean changed = false;
10864                final int appId;
10865                synchronized (mPackages) {
10866                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10867                    if (pkgSetting == null) {
10868                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10869                                + "\". Skipping suspending/un-suspending.");
10870                        unactionedPackages.add(packageName);
10871                        continue;
10872                    }
10873                    appId = pkgSetting.appId;
10874                    if (pkgSetting.getSuspended(userId) != suspended) {
10875                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10876                            unactionedPackages.add(packageName);
10877                            continue;
10878                        }
10879                        pkgSetting.setSuspended(suspended, userId);
10880                        mSettings.writePackageRestrictionsLPr(userId);
10881                        changed = true;
10882                        changedPackages.add(packageName);
10883                    }
10884                }
10885
10886                if (changed && suspended) {
10887                    killApplication(packageName, UserHandle.getUid(userId, appId),
10888                            "suspending package");
10889                }
10890            } finally {
10891                Binder.restoreCallingIdentity(callingId);
10892            }
10893        }
10894
10895        if (!changedPackages.isEmpty()) {
10896            sendPackagesSuspendedForUser(changedPackages.toArray(
10897                    new String[changedPackages.size()]), userId, suspended);
10898        }
10899
10900        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10901    }
10902
10903    @Override
10904    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10905        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10906                true /* requireFullPermission */, false /* checkShell */,
10907                "isPackageSuspendedForUser for user " + userId);
10908        synchronized (mPackages) {
10909            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10910            return pkgSetting != null && pkgSetting.getSuspended(userId);
10911        }
10912    }
10913
10914    /**
10915     * TODO: cache and disallow blocking the active dialer.
10916     *
10917     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
10918     */
10919    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10920        if (isPackageDeviceAdmin(packageName, userId)) {
10921            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10922                    + "\": has an active device admin");
10923            return false;
10924        }
10925
10926        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10927        if (packageName.equals(activeLauncherPackageName)) {
10928            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10929                    + "\": contains the active launcher");
10930            return false;
10931        }
10932
10933        if (packageName.equals(mRequiredInstallerPackage)) {
10934            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10935                    + "\": required for package installation");
10936            return false;
10937        }
10938
10939        if (packageName.equals(mRequiredVerifierPackage)) {
10940            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10941                    + "\": required for package verification");
10942            return false;
10943        }
10944
10945        final PackageParser.Package pkg = mPackages.get(packageName);
10946        if (pkg != null && isPrivilegedApp(pkg)) {
10947            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10948                    + "\": is a privileged app");
10949            return false;
10950        }
10951
10952        return true;
10953    }
10954
10955    private String getActiveLauncherPackageName(int userId) {
10956        Intent intent = new Intent(Intent.ACTION_MAIN);
10957        intent.addCategory(Intent.CATEGORY_HOME);
10958        ResolveInfo resolveInfo = resolveIntent(
10959                intent,
10960                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10961                PackageManager.MATCH_DEFAULT_ONLY,
10962                userId);
10963
10964        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10965    }
10966
10967    @Override
10968    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10969        mContext.enforceCallingOrSelfPermission(
10970                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10971                "Only package verification agents can verify applications");
10972
10973        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10974        final PackageVerificationResponse response = new PackageVerificationResponse(
10975                verificationCode, Binder.getCallingUid());
10976        msg.arg1 = id;
10977        msg.obj = response;
10978        mHandler.sendMessage(msg);
10979    }
10980
10981    @Override
10982    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10983            long millisecondsToDelay) {
10984        mContext.enforceCallingOrSelfPermission(
10985                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10986                "Only package verification agents can extend verification timeouts");
10987
10988        final PackageVerificationState state = mPendingVerification.get(id);
10989        final PackageVerificationResponse response = new PackageVerificationResponse(
10990                verificationCodeAtTimeout, Binder.getCallingUid());
10991
10992        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10993            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10994        }
10995        if (millisecondsToDelay < 0) {
10996            millisecondsToDelay = 0;
10997        }
10998        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10999                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11000            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11001        }
11002
11003        if ((state != null) && !state.timeoutExtended()) {
11004            state.extendTimeout();
11005
11006            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11007            msg.arg1 = id;
11008            msg.obj = response;
11009            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11010        }
11011    }
11012
11013    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11014            int verificationCode, UserHandle user) {
11015        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11016        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11017        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11018        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11019        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11020
11021        mContext.sendBroadcastAsUser(intent, user,
11022                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11023    }
11024
11025    private ComponentName matchComponentForVerifier(String packageName,
11026            List<ResolveInfo> receivers) {
11027        ActivityInfo targetReceiver = null;
11028
11029        final int NR = receivers.size();
11030        for (int i = 0; i < NR; i++) {
11031            final ResolveInfo info = receivers.get(i);
11032            if (info.activityInfo == null) {
11033                continue;
11034            }
11035
11036            if (packageName.equals(info.activityInfo.packageName)) {
11037                targetReceiver = info.activityInfo;
11038                break;
11039            }
11040        }
11041
11042        if (targetReceiver == null) {
11043            return null;
11044        }
11045
11046        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11047    }
11048
11049    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11050            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11051        if (pkgInfo.verifiers.length == 0) {
11052            return null;
11053        }
11054
11055        final int N = pkgInfo.verifiers.length;
11056        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11057        for (int i = 0; i < N; i++) {
11058            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11059
11060            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11061                    receivers);
11062            if (comp == null) {
11063                continue;
11064            }
11065
11066            final int verifierUid = getUidForVerifier(verifierInfo);
11067            if (verifierUid == -1) {
11068                continue;
11069            }
11070
11071            if (DEBUG_VERIFY) {
11072                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11073                        + " with the correct signature");
11074            }
11075            sufficientVerifiers.add(comp);
11076            verificationState.addSufficientVerifier(verifierUid);
11077        }
11078
11079        return sufficientVerifiers;
11080    }
11081
11082    private int getUidForVerifier(VerifierInfo verifierInfo) {
11083        synchronized (mPackages) {
11084            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11085            if (pkg == null) {
11086                return -1;
11087            } else if (pkg.mSignatures.length != 1) {
11088                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11089                        + " has more than one signature; ignoring");
11090                return -1;
11091            }
11092
11093            /*
11094             * If the public key of the package's signature does not match
11095             * our expected public key, then this is a different package and
11096             * we should skip.
11097             */
11098
11099            final byte[] expectedPublicKey;
11100            try {
11101                final Signature verifierSig = pkg.mSignatures[0];
11102                final PublicKey publicKey = verifierSig.getPublicKey();
11103                expectedPublicKey = publicKey.getEncoded();
11104            } catch (CertificateException e) {
11105                return -1;
11106            }
11107
11108            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11109
11110            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11111                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11112                        + " does not have the expected public key; ignoring");
11113                return -1;
11114            }
11115
11116            return pkg.applicationInfo.uid;
11117        }
11118    }
11119
11120    @Override
11121    public void finishPackageInstall(int token) {
11122        enforceSystemOrRoot("Only the system is allowed to finish installs");
11123
11124        if (DEBUG_INSTALL) {
11125            Slog.v(TAG, "BM finishing package install for " + token);
11126        }
11127        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11128
11129        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11130        mHandler.sendMessage(msg);
11131    }
11132
11133    /**
11134     * Get the verification agent timeout.
11135     *
11136     * @return verification timeout in milliseconds
11137     */
11138    private long getVerificationTimeout() {
11139        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11140                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11141                DEFAULT_VERIFICATION_TIMEOUT);
11142    }
11143
11144    /**
11145     * Get the default verification agent response code.
11146     *
11147     * @return default verification response code
11148     */
11149    private int getDefaultVerificationResponse() {
11150        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11151                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11152                DEFAULT_VERIFICATION_RESPONSE);
11153    }
11154
11155    /**
11156     * Check whether or not package verification has been enabled.
11157     *
11158     * @return true if verification should be performed
11159     */
11160    private boolean isVerificationEnabled(int userId, int installFlags) {
11161        if (!DEFAULT_VERIFY_ENABLE) {
11162            return false;
11163        }
11164        // Ephemeral apps don't get the full verification treatment
11165        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11166            if (DEBUG_EPHEMERAL) {
11167                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11168            }
11169            return false;
11170        }
11171
11172        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11173
11174        // Check if installing from ADB
11175        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11176            // Do not run verification in a test harness environment
11177            if (ActivityManager.isRunningInTestHarness()) {
11178                return false;
11179            }
11180            if (ensureVerifyAppsEnabled) {
11181                return true;
11182            }
11183            // Check if the developer does not want package verification for ADB installs
11184            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11185                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11186                return false;
11187            }
11188        }
11189
11190        if (ensureVerifyAppsEnabled) {
11191            return true;
11192        }
11193
11194        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11195                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11196    }
11197
11198    @Override
11199    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11200            throws RemoteException {
11201        mContext.enforceCallingOrSelfPermission(
11202                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11203                "Only intentfilter verification agents can verify applications");
11204
11205        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11206        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11207                Binder.getCallingUid(), verificationCode, failedDomains);
11208        msg.arg1 = id;
11209        msg.obj = response;
11210        mHandler.sendMessage(msg);
11211    }
11212
11213    @Override
11214    public int getIntentVerificationStatus(String packageName, int userId) {
11215        synchronized (mPackages) {
11216            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11217        }
11218    }
11219
11220    @Override
11221    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11222        mContext.enforceCallingOrSelfPermission(
11223                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11224
11225        boolean result = false;
11226        synchronized (mPackages) {
11227            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11228        }
11229        if (result) {
11230            scheduleWritePackageRestrictionsLocked(userId);
11231        }
11232        return result;
11233    }
11234
11235    @Override
11236    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11237            String packageName) {
11238        synchronized (mPackages) {
11239            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11240        }
11241    }
11242
11243    @Override
11244    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11245        if (TextUtils.isEmpty(packageName)) {
11246            return ParceledListSlice.emptyList();
11247        }
11248        synchronized (mPackages) {
11249            PackageParser.Package pkg = mPackages.get(packageName);
11250            if (pkg == null || pkg.activities == null) {
11251                return ParceledListSlice.emptyList();
11252            }
11253            final int count = pkg.activities.size();
11254            ArrayList<IntentFilter> result = new ArrayList<>();
11255            for (int n=0; n<count; n++) {
11256                PackageParser.Activity activity = pkg.activities.get(n);
11257                if (activity.intents != null && activity.intents.size() > 0) {
11258                    result.addAll(activity.intents);
11259                }
11260            }
11261            return new ParceledListSlice<>(result);
11262        }
11263    }
11264
11265    @Override
11266    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11267        mContext.enforceCallingOrSelfPermission(
11268                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11269
11270        synchronized (mPackages) {
11271            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11272            if (packageName != null) {
11273                result |= updateIntentVerificationStatus(packageName,
11274                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11275                        userId);
11276                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11277                        packageName, userId);
11278            }
11279            return result;
11280        }
11281    }
11282
11283    @Override
11284    public String getDefaultBrowserPackageName(int userId) {
11285        synchronized (mPackages) {
11286            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11287        }
11288    }
11289
11290    /**
11291     * Get the "allow unknown sources" setting.
11292     *
11293     * @return the current "allow unknown sources" setting
11294     */
11295    private int getUnknownSourcesSettings() {
11296        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11297                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11298                -1);
11299    }
11300
11301    @Override
11302    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11303        final int uid = Binder.getCallingUid();
11304        // writer
11305        synchronized (mPackages) {
11306            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11307            if (targetPackageSetting == null) {
11308                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11309            }
11310
11311            PackageSetting installerPackageSetting;
11312            if (installerPackageName != null) {
11313                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11314                if (installerPackageSetting == null) {
11315                    throw new IllegalArgumentException("Unknown installer package: "
11316                            + installerPackageName);
11317                }
11318            } else {
11319                installerPackageSetting = null;
11320            }
11321
11322            Signature[] callerSignature;
11323            Object obj = mSettings.getUserIdLPr(uid);
11324            if (obj != null) {
11325                if (obj instanceof SharedUserSetting) {
11326                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11327                } else if (obj instanceof PackageSetting) {
11328                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11329                } else {
11330                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11331                }
11332            } else {
11333                throw new SecurityException("Unknown calling UID: " + uid);
11334            }
11335
11336            // Verify: can't set installerPackageName to a package that is
11337            // not signed with the same cert as the caller.
11338            if (installerPackageSetting != null) {
11339                if (compareSignatures(callerSignature,
11340                        installerPackageSetting.signatures.mSignatures)
11341                        != PackageManager.SIGNATURE_MATCH) {
11342                    throw new SecurityException(
11343                            "Caller does not have same cert as new installer package "
11344                            + installerPackageName);
11345                }
11346            }
11347
11348            // Verify: if target already has an installer package, it must
11349            // be signed with the same cert as the caller.
11350            if (targetPackageSetting.installerPackageName != null) {
11351                PackageSetting setting = mSettings.mPackages.get(
11352                        targetPackageSetting.installerPackageName);
11353                // If the currently set package isn't valid, then it's always
11354                // okay to change it.
11355                if (setting != null) {
11356                    if (compareSignatures(callerSignature,
11357                            setting.signatures.mSignatures)
11358                            != PackageManager.SIGNATURE_MATCH) {
11359                        throw new SecurityException(
11360                                "Caller does not have same cert as old installer package "
11361                                + targetPackageSetting.installerPackageName);
11362                    }
11363                }
11364            }
11365
11366            // Okay!
11367            targetPackageSetting.installerPackageName = installerPackageName;
11368            scheduleWriteSettingsLocked();
11369        }
11370    }
11371
11372    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11373        // Queue up an async operation since the package installation may take a little while.
11374        mHandler.post(new Runnable() {
11375            public void run() {
11376                mHandler.removeCallbacks(this);
11377                 // Result object to be returned
11378                PackageInstalledInfo res = new PackageInstalledInfo();
11379                res.setReturnCode(currentStatus);
11380                res.uid = -1;
11381                res.pkg = null;
11382                res.removedInfo = null;
11383                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11384                    args.doPreInstall(res.returnCode);
11385                    synchronized (mInstallLock) {
11386                        installPackageTracedLI(args, res);
11387                    }
11388                    args.doPostInstall(res.returnCode, res.uid);
11389                }
11390
11391                // A restore should be performed at this point if (a) the install
11392                // succeeded, (b) the operation is not an update, and (c) the new
11393                // package has not opted out of backup participation.
11394                final boolean update = res.removedInfo != null
11395                        && res.removedInfo.removedPackage != null;
11396                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11397                boolean doRestore = !update
11398                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11399
11400                // Set up the post-install work request bookkeeping.  This will be used
11401                // and cleaned up by the post-install event handling regardless of whether
11402                // there's a restore pass performed.  Token values are >= 1.
11403                int token;
11404                if (mNextInstallToken < 0) mNextInstallToken = 1;
11405                token = mNextInstallToken++;
11406
11407                PostInstallData data = new PostInstallData(args, res);
11408                mRunningInstalls.put(token, data);
11409                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11410
11411                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11412                    // Pass responsibility to the Backup Manager.  It will perform a
11413                    // restore if appropriate, then pass responsibility back to the
11414                    // Package Manager to run the post-install observer callbacks
11415                    // and broadcasts.
11416                    IBackupManager bm = IBackupManager.Stub.asInterface(
11417                            ServiceManager.getService(Context.BACKUP_SERVICE));
11418                    if (bm != null) {
11419                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11420                                + " to BM for possible restore");
11421                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11422                        try {
11423                            // TODO: http://b/22388012
11424                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11425                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11426                            } else {
11427                                doRestore = false;
11428                            }
11429                        } catch (RemoteException e) {
11430                            // can't happen; the backup manager is local
11431                        } catch (Exception e) {
11432                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11433                            doRestore = false;
11434                        }
11435                    } else {
11436                        Slog.e(TAG, "Backup Manager not found!");
11437                        doRestore = false;
11438                    }
11439                }
11440
11441                if (!doRestore) {
11442                    // No restore possible, or the Backup Manager was mysteriously not
11443                    // available -- just fire the post-install work request directly.
11444                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11445
11446                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11447
11448                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11449                    mHandler.sendMessage(msg);
11450                }
11451            }
11452        });
11453    }
11454
11455    private abstract class HandlerParams {
11456        private static final int MAX_RETRIES = 4;
11457
11458        /**
11459         * Number of times startCopy() has been attempted and had a non-fatal
11460         * error.
11461         */
11462        private int mRetries = 0;
11463
11464        /** User handle for the user requesting the information or installation. */
11465        private final UserHandle mUser;
11466        String traceMethod;
11467        int traceCookie;
11468
11469        HandlerParams(UserHandle user) {
11470            mUser = user;
11471        }
11472
11473        UserHandle getUser() {
11474            return mUser;
11475        }
11476
11477        HandlerParams setTraceMethod(String traceMethod) {
11478            this.traceMethod = traceMethod;
11479            return this;
11480        }
11481
11482        HandlerParams setTraceCookie(int traceCookie) {
11483            this.traceCookie = traceCookie;
11484            return this;
11485        }
11486
11487        final boolean startCopy() {
11488            boolean res;
11489            try {
11490                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11491
11492                if (++mRetries > MAX_RETRIES) {
11493                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11494                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11495                    handleServiceError();
11496                    return false;
11497                } else {
11498                    handleStartCopy();
11499                    res = true;
11500                }
11501            } catch (RemoteException e) {
11502                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11503                mHandler.sendEmptyMessage(MCS_RECONNECT);
11504                res = false;
11505            }
11506            handleReturnCode();
11507            return res;
11508        }
11509
11510        final void serviceError() {
11511            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11512            handleServiceError();
11513            handleReturnCode();
11514        }
11515
11516        abstract void handleStartCopy() throws RemoteException;
11517        abstract void handleServiceError();
11518        abstract void handleReturnCode();
11519    }
11520
11521    class MeasureParams extends HandlerParams {
11522        private final PackageStats mStats;
11523        private boolean mSuccess;
11524
11525        private final IPackageStatsObserver mObserver;
11526
11527        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11528            super(new UserHandle(stats.userHandle));
11529            mObserver = observer;
11530            mStats = stats;
11531        }
11532
11533        @Override
11534        public String toString() {
11535            return "MeasureParams{"
11536                + Integer.toHexString(System.identityHashCode(this))
11537                + " " + mStats.packageName + "}";
11538        }
11539
11540        @Override
11541        void handleStartCopy() throws RemoteException {
11542            synchronized (mInstallLock) {
11543                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11544            }
11545
11546            if (mSuccess) {
11547                final boolean mounted;
11548                if (Environment.isExternalStorageEmulated()) {
11549                    mounted = true;
11550                } else {
11551                    final String status = Environment.getExternalStorageState();
11552                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11553                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11554                }
11555
11556                if (mounted) {
11557                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11558
11559                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11560                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11561
11562                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11563                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11564
11565                    // Always subtract cache size, since it's a subdirectory
11566                    mStats.externalDataSize -= mStats.externalCacheSize;
11567
11568                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11569                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11570
11571                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11572                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11573                }
11574            }
11575        }
11576
11577        @Override
11578        void handleReturnCode() {
11579            if (mObserver != null) {
11580                try {
11581                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11582                } catch (RemoteException e) {
11583                    Slog.i(TAG, "Observer no longer exists.");
11584                }
11585            }
11586        }
11587
11588        @Override
11589        void handleServiceError() {
11590            Slog.e(TAG, "Could not measure application " + mStats.packageName
11591                            + " external storage");
11592        }
11593    }
11594
11595    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11596            throws RemoteException {
11597        long result = 0;
11598        for (File path : paths) {
11599            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11600        }
11601        return result;
11602    }
11603
11604    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11605        for (File path : paths) {
11606            try {
11607                mcs.clearDirectory(path.getAbsolutePath());
11608            } catch (RemoteException e) {
11609            }
11610        }
11611    }
11612
11613    static class OriginInfo {
11614        /**
11615         * Location where install is coming from, before it has been
11616         * copied/renamed into place. This could be a single monolithic APK
11617         * file, or a cluster directory. This location may be untrusted.
11618         */
11619        final File file;
11620        final String cid;
11621
11622        /**
11623         * Flag indicating that {@link #file} or {@link #cid} has already been
11624         * staged, meaning downstream users don't need to defensively copy the
11625         * contents.
11626         */
11627        final boolean staged;
11628
11629        /**
11630         * Flag indicating that {@link #file} or {@link #cid} is an already
11631         * installed app that is being moved.
11632         */
11633        final boolean existing;
11634
11635        final String resolvedPath;
11636        final File resolvedFile;
11637
11638        static OriginInfo fromNothing() {
11639            return new OriginInfo(null, null, false, false);
11640        }
11641
11642        static OriginInfo fromUntrustedFile(File file) {
11643            return new OriginInfo(file, null, false, false);
11644        }
11645
11646        static OriginInfo fromExistingFile(File file) {
11647            return new OriginInfo(file, null, false, true);
11648        }
11649
11650        static OriginInfo fromStagedFile(File file) {
11651            return new OriginInfo(file, null, true, false);
11652        }
11653
11654        static OriginInfo fromStagedContainer(String cid) {
11655            return new OriginInfo(null, cid, true, false);
11656        }
11657
11658        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11659            this.file = file;
11660            this.cid = cid;
11661            this.staged = staged;
11662            this.existing = existing;
11663
11664            if (cid != null) {
11665                resolvedPath = PackageHelper.getSdDir(cid);
11666                resolvedFile = new File(resolvedPath);
11667            } else if (file != null) {
11668                resolvedPath = file.getAbsolutePath();
11669                resolvedFile = file;
11670            } else {
11671                resolvedPath = null;
11672                resolvedFile = null;
11673            }
11674        }
11675    }
11676
11677    static class MoveInfo {
11678        final int moveId;
11679        final String fromUuid;
11680        final String toUuid;
11681        final String packageName;
11682        final String dataAppName;
11683        final int appId;
11684        final String seinfo;
11685        final int targetSdkVersion;
11686
11687        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11688                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11689            this.moveId = moveId;
11690            this.fromUuid = fromUuid;
11691            this.toUuid = toUuid;
11692            this.packageName = packageName;
11693            this.dataAppName = dataAppName;
11694            this.appId = appId;
11695            this.seinfo = seinfo;
11696            this.targetSdkVersion = targetSdkVersion;
11697        }
11698    }
11699
11700    static class VerificationInfo {
11701        /** A constant used to indicate that a uid value is not present. */
11702        public static final int NO_UID = -1;
11703
11704        /** URI referencing where the package was downloaded from. */
11705        final Uri originatingUri;
11706
11707        /** HTTP referrer URI associated with the originatingURI. */
11708        final Uri referrer;
11709
11710        /** UID of the application that the install request originated from. */
11711        final int originatingUid;
11712
11713        /** UID of application requesting the install */
11714        final int installerUid;
11715
11716        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11717            this.originatingUri = originatingUri;
11718            this.referrer = referrer;
11719            this.originatingUid = originatingUid;
11720            this.installerUid = installerUid;
11721        }
11722    }
11723
11724    class InstallParams extends HandlerParams {
11725        final OriginInfo origin;
11726        final MoveInfo move;
11727        final IPackageInstallObserver2 observer;
11728        int installFlags;
11729        final String installerPackageName;
11730        final String volumeUuid;
11731        private InstallArgs mArgs;
11732        private int mRet;
11733        final String packageAbiOverride;
11734        final String[] grantedRuntimePermissions;
11735        final VerificationInfo verificationInfo;
11736
11737        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11738                int installFlags, String installerPackageName, String volumeUuid,
11739                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11740                String[] grantedPermissions) {
11741            super(user);
11742            this.origin = origin;
11743            this.move = move;
11744            this.observer = observer;
11745            this.installFlags = installFlags;
11746            this.installerPackageName = installerPackageName;
11747            this.volumeUuid = volumeUuid;
11748            this.verificationInfo = verificationInfo;
11749            this.packageAbiOverride = packageAbiOverride;
11750            this.grantedRuntimePermissions = grantedPermissions;
11751        }
11752
11753        @Override
11754        public String toString() {
11755            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11756                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11757        }
11758
11759        private int installLocationPolicy(PackageInfoLite pkgLite) {
11760            String packageName = pkgLite.packageName;
11761            int installLocation = pkgLite.installLocation;
11762            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11763            // reader
11764            synchronized (mPackages) {
11765                // Currently installed package which the new package is attempting to replace or
11766                // null if no such package is installed.
11767                PackageParser.Package installedPkg = mPackages.get(packageName);
11768                // Package which currently owns the data which the new package will own if installed.
11769                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11770                // will be null whereas dataOwnerPkg will contain information about the package
11771                // which was uninstalled while keeping its data.
11772                PackageParser.Package dataOwnerPkg = installedPkg;
11773                if (dataOwnerPkg  == null) {
11774                    PackageSetting ps = mSettings.mPackages.get(packageName);
11775                    if (ps != null) {
11776                        dataOwnerPkg = ps.pkg;
11777                    }
11778                }
11779
11780                if (dataOwnerPkg != null) {
11781                    // If installed, the package will get access to data left on the device by its
11782                    // predecessor. As a security measure, this is permited only if this is not a
11783                    // version downgrade or if the predecessor package is marked as debuggable and
11784                    // a downgrade is explicitly requested.
11785                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11786                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11787                        try {
11788                            checkDowngrade(dataOwnerPkg, pkgLite);
11789                        } catch (PackageManagerException e) {
11790                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11791                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11792                        }
11793                    }
11794                }
11795
11796                if (installedPkg != null) {
11797                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11798                        // Check for updated system application.
11799                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11800                            if (onSd) {
11801                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11802                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11803                            }
11804                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11805                        } else {
11806                            if (onSd) {
11807                                // Install flag overrides everything.
11808                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11809                            }
11810                            // If current upgrade specifies particular preference
11811                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11812                                // Application explicitly specified internal.
11813                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11814                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11815                                // App explictly prefers external. Let policy decide
11816                            } else {
11817                                // Prefer previous location
11818                                if (isExternal(installedPkg)) {
11819                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11820                                }
11821                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11822                            }
11823                        }
11824                    } else {
11825                        // Invalid install. Return error code
11826                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11827                    }
11828                }
11829            }
11830            // All the special cases have been taken care of.
11831            // Return result based on recommended install location.
11832            if (onSd) {
11833                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11834            }
11835            return pkgLite.recommendedInstallLocation;
11836        }
11837
11838        /*
11839         * Invoke remote method to get package information and install
11840         * location values. Override install location based on default
11841         * policy if needed and then create install arguments based
11842         * on the install location.
11843         */
11844        public void handleStartCopy() throws RemoteException {
11845            int ret = PackageManager.INSTALL_SUCCEEDED;
11846
11847            // If we're already staged, we've firmly committed to an install location
11848            if (origin.staged) {
11849                if (origin.file != null) {
11850                    installFlags |= PackageManager.INSTALL_INTERNAL;
11851                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11852                } else if (origin.cid != null) {
11853                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11854                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11855                } else {
11856                    throw new IllegalStateException("Invalid stage location");
11857                }
11858            }
11859
11860            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11861            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11862            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11863            PackageInfoLite pkgLite = null;
11864
11865            if (onInt && onSd) {
11866                // Check if both bits are set.
11867                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11868                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11869            } else if (onSd && ephemeral) {
11870                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11871                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11872            } else {
11873                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11874                        packageAbiOverride);
11875
11876                if (DEBUG_EPHEMERAL && ephemeral) {
11877                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11878                }
11879
11880                /*
11881                 * If we have too little free space, try to free cache
11882                 * before giving up.
11883                 */
11884                if (!origin.staged && pkgLite.recommendedInstallLocation
11885                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11886                    // TODO: focus freeing disk space on the target device
11887                    final StorageManager storage = StorageManager.from(mContext);
11888                    final long lowThreshold = storage.getStorageLowBytes(
11889                            Environment.getDataDirectory());
11890
11891                    final long sizeBytes = mContainerService.calculateInstalledSize(
11892                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11893
11894                    try {
11895                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11896                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11897                                installFlags, packageAbiOverride);
11898                    } catch (InstallerException e) {
11899                        Slog.w(TAG, "Failed to free cache", e);
11900                    }
11901
11902                    /*
11903                     * The cache free must have deleted the file we
11904                     * downloaded to install.
11905                     *
11906                     * TODO: fix the "freeCache" call to not delete
11907                     *       the file we care about.
11908                     */
11909                    if (pkgLite.recommendedInstallLocation
11910                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11911                        pkgLite.recommendedInstallLocation
11912                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11913                    }
11914                }
11915            }
11916
11917            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11918                int loc = pkgLite.recommendedInstallLocation;
11919                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11920                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11921                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11922                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11923                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11924                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11925                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11926                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11927                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11928                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11929                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11930                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11931                } else {
11932                    // Override with defaults if needed.
11933                    loc = installLocationPolicy(pkgLite);
11934                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11935                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11936                    } else if (!onSd && !onInt) {
11937                        // Override install location with flags
11938                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11939                            // Set the flag to install on external media.
11940                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11941                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11942                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11943                            if (DEBUG_EPHEMERAL) {
11944                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11945                            }
11946                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11947                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11948                                    |PackageManager.INSTALL_INTERNAL);
11949                        } else {
11950                            // Make sure the flag for installing on external
11951                            // media is unset
11952                            installFlags |= PackageManager.INSTALL_INTERNAL;
11953                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11954                        }
11955                    }
11956                }
11957            }
11958
11959            final InstallArgs args = createInstallArgs(this);
11960            mArgs = args;
11961
11962            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11963                // TODO: http://b/22976637
11964                // Apps installed for "all" users use the device owner to verify the app
11965                UserHandle verifierUser = getUser();
11966                if (verifierUser == UserHandle.ALL) {
11967                    verifierUser = UserHandle.SYSTEM;
11968                }
11969
11970                /*
11971                 * Determine if we have any installed package verifiers. If we
11972                 * do, then we'll defer to them to verify the packages.
11973                 */
11974                final int requiredUid = mRequiredVerifierPackage == null ? -1
11975                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11976                                verifierUser.getIdentifier());
11977                if (!origin.existing && requiredUid != -1
11978                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11979                    final Intent verification = new Intent(
11980                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11981                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11982                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11983                            PACKAGE_MIME_TYPE);
11984                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11985
11986                    // Query all live verifiers based on current user state
11987                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
11988                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11989
11990                    if (DEBUG_VERIFY) {
11991                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11992                                + verification.toString() + " with " + pkgLite.verifiers.length
11993                                + " optional verifiers");
11994                    }
11995
11996                    final int verificationId = mPendingVerificationToken++;
11997
11998                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11999
12000                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12001                            installerPackageName);
12002
12003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12004                            installFlags);
12005
12006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12007                            pkgLite.packageName);
12008
12009                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12010                            pkgLite.versionCode);
12011
12012                    if (verificationInfo != null) {
12013                        if (verificationInfo.originatingUri != null) {
12014                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12015                                    verificationInfo.originatingUri);
12016                        }
12017                        if (verificationInfo.referrer != null) {
12018                            verification.putExtra(Intent.EXTRA_REFERRER,
12019                                    verificationInfo.referrer);
12020                        }
12021                        if (verificationInfo.originatingUid >= 0) {
12022                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12023                                    verificationInfo.originatingUid);
12024                        }
12025                        if (verificationInfo.installerUid >= 0) {
12026                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12027                                    verificationInfo.installerUid);
12028                        }
12029                    }
12030
12031                    final PackageVerificationState verificationState = new PackageVerificationState(
12032                            requiredUid, args);
12033
12034                    mPendingVerification.append(verificationId, verificationState);
12035
12036                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12037                            receivers, verificationState);
12038
12039                    /*
12040                     * If any sufficient verifiers were listed in the package
12041                     * manifest, attempt to ask them.
12042                     */
12043                    if (sufficientVerifiers != null) {
12044                        final int N = sufficientVerifiers.size();
12045                        if (N == 0) {
12046                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12047                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12048                        } else {
12049                            for (int i = 0; i < N; i++) {
12050                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12051
12052                                final Intent sufficientIntent = new Intent(verification);
12053                                sufficientIntent.setComponent(verifierComponent);
12054                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12055                            }
12056                        }
12057                    }
12058
12059                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12060                            mRequiredVerifierPackage, receivers);
12061                    if (ret == PackageManager.INSTALL_SUCCEEDED
12062                            && mRequiredVerifierPackage != null) {
12063                        Trace.asyncTraceBegin(
12064                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12065                        /*
12066                         * Send the intent to the required verification agent,
12067                         * but only start the verification timeout after the
12068                         * target BroadcastReceivers have run.
12069                         */
12070                        verification.setComponent(requiredVerifierComponent);
12071                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12072                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12073                                new BroadcastReceiver() {
12074                                    @Override
12075                                    public void onReceive(Context context, Intent intent) {
12076                                        final Message msg = mHandler
12077                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12078                                        msg.arg1 = verificationId;
12079                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12080                                    }
12081                                }, null, 0, null, null);
12082
12083                        /*
12084                         * We don't want the copy to proceed until verification
12085                         * succeeds, so null out this field.
12086                         */
12087                        mArgs = null;
12088                    }
12089                } else {
12090                    /*
12091                     * No package verification is enabled, so immediately start
12092                     * the remote call to initiate copy using temporary file.
12093                     */
12094                    ret = args.copyApk(mContainerService, true);
12095                }
12096            }
12097
12098            mRet = ret;
12099        }
12100
12101        @Override
12102        void handleReturnCode() {
12103            // If mArgs is null, then MCS couldn't be reached. When it
12104            // reconnects, it will try again to install. At that point, this
12105            // will succeed.
12106            if (mArgs != null) {
12107                processPendingInstall(mArgs, mRet);
12108            }
12109        }
12110
12111        @Override
12112        void handleServiceError() {
12113            mArgs = createInstallArgs(this);
12114            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12115        }
12116
12117        public boolean isForwardLocked() {
12118            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12119        }
12120    }
12121
12122    /**
12123     * Used during creation of InstallArgs
12124     *
12125     * @param installFlags package installation flags
12126     * @return true if should be installed on external storage
12127     */
12128    private static boolean installOnExternalAsec(int installFlags) {
12129        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12130            return false;
12131        }
12132        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12133            return true;
12134        }
12135        return false;
12136    }
12137
12138    /**
12139     * Used during creation of InstallArgs
12140     *
12141     * @param installFlags package installation flags
12142     * @return true if should be installed as forward locked
12143     */
12144    private static boolean installForwardLocked(int installFlags) {
12145        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12146    }
12147
12148    private InstallArgs createInstallArgs(InstallParams params) {
12149        if (params.move != null) {
12150            return new MoveInstallArgs(params);
12151        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12152            return new AsecInstallArgs(params);
12153        } else {
12154            return new FileInstallArgs(params);
12155        }
12156    }
12157
12158    /**
12159     * Create args that describe an existing installed package. Typically used
12160     * when cleaning up old installs, or used as a move source.
12161     */
12162    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12163            String resourcePath, String[] instructionSets) {
12164        final boolean isInAsec;
12165        if (installOnExternalAsec(installFlags)) {
12166            /* Apps on SD card are always in ASEC containers. */
12167            isInAsec = true;
12168        } else if (installForwardLocked(installFlags)
12169                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12170            /*
12171             * Forward-locked apps are only in ASEC containers if they're the
12172             * new style
12173             */
12174            isInAsec = true;
12175        } else {
12176            isInAsec = false;
12177        }
12178
12179        if (isInAsec) {
12180            return new AsecInstallArgs(codePath, instructionSets,
12181                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12182        } else {
12183            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12184        }
12185    }
12186
12187    static abstract class InstallArgs {
12188        /** @see InstallParams#origin */
12189        final OriginInfo origin;
12190        /** @see InstallParams#move */
12191        final MoveInfo move;
12192
12193        final IPackageInstallObserver2 observer;
12194        // Always refers to PackageManager flags only
12195        final int installFlags;
12196        final String installerPackageName;
12197        final String volumeUuid;
12198        final UserHandle user;
12199        final String abiOverride;
12200        final String[] installGrantPermissions;
12201        /** If non-null, drop an async trace when the install completes */
12202        final String traceMethod;
12203        final int traceCookie;
12204
12205        // The list of instruction sets supported by this app. This is currently
12206        // only used during the rmdex() phase to clean up resources. We can get rid of this
12207        // if we move dex files under the common app path.
12208        /* nullable */ String[] instructionSets;
12209
12210        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12211                int installFlags, String installerPackageName, String volumeUuid,
12212                UserHandle user, String[] instructionSets,
12213                String abiOverride, String[] installGrantPermissions,
12214                String traceMethod, int traceCookie) {
12215            this.origin = origin;
12216            this.move = move;
12217            this.installFlags = installFlags;
12218            this.observer = observer;
12219            this.installerPackageName = installerPackageName;
12220            this.volumeUuid = volumeUuid;
12221            this.user = user;
12222            this.instructionSets = instructionSets;
12223            this.abiOverride = abiOverride;
12224            this.installGrantPermissions = installGrantPermissions;
12225            this.traceMethod = traceMethod;
12226            this.traceCookie = traceCookie;
12227        }
12228
12229        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12230        abstract int doPreInstall(int status);
12231
12232        /**
12233         * Rename package into final resting place. All paths on the given
12234         * scanned package should be updated to reflect the rename.
12235         */
12236        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12237        abstract int doPostInstall(int status, int uid);
12238
12239        /** @see PackageSettingBase#codePathString */
12240        abstract String getCodePath();
12241        /** @see PackageSettingBase#resourcePathString */
12242        abstract String getResourcePath();
12243
12244        // Need installer lock especially for dex file removal.
12245        abstract void cleanUpResourcesLI();
12246        abstract boolean doPostDeleteLI(boolean delete);
12247
12248        /**
12249         * Called before the source arguments are copied. This is used mostly
12250         * for MoveParams when it needs to read the source file to put it in the
12251         * destination.
12252         */
12253        int doPreCopy() {
12254            return PackageManager.INSTALL_SUCCEEDED;
12255        }
12256
12257        /**
12258         * Called after the source arguments are copied. This is used mostly for
12259         * MoveParams when it needs to read the source file to put it in the
12260         * destination.
12261         *
12262         * @return
12263         */
12264        int doPostCopy(int uid) {
12265            return PackageManager.INSTALL_SUCCEEDED;
12266        }
12267
12268        protected boolean isFwdLocked() {
12269            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12270        }
12271
12272        protected boolean isExternalAsec() {
12273            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12274        }
12275
12276        protected boolean isEphemeral() {
12277            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12278        }
12279
12280        UserHandle getUser() {
12281            return user;
12282        }
12283    }
12284
12285    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12286        if (!allCodePaths.isEmpty()) {
12287            if (instructionSets == null) {
12288                throw new IllegalStateException("instructionSet == null");
12289            }
12290            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12291            for (String codePath : allCodePaths) {
12292                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12293                    try {
12294                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12295                    } catch (InstallerException ignored) {
12296                    }
12297                }
12298            }
12299        }
12300    }
12301
12302    /**
12303     * Logic to handle installation of non-ASEC applications, including copying
12304     * and renaming logic.
12305     */
12306    class FileInstallArgs extends InstallArgs {
12307        private File codeFile;
12308        private File resourceFile;
12309
12310        // Example topology:
12311        // /data/app/com.example/base.apk
12312        // /data/app/com.example/split_foo.apk
12313        // /data/app/com.example/lib/arm/libfoo.so
12314        // /data/app/com.example/lib/arm64/libfoo.so
12315        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12316
12317        /** New install */
12318        FileInstallArgs(InstallParams params) {
12319            super(params.origin, params.move, params.observer, params.installFlags,
12320                    params.installerPackageName, params.volumeUuid,
12321                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12322                    params.grantedRuntimePermissions,
12323                    params.traceMethod, params.traceCookie);
12324            if (isFwdLocked()) {
12325                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12326            }
12327        }
12328
12329        /** Existing install */
12330        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12331            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12332                    null, null, null, 0);
12333            this.codeFile = (codePath != null) ? new File(codePath) : null;
12334            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12335        }
12336
12337        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12338            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12339            try {
12340                return doCopyApk(imcs, temp);
12341            } finally {
12342                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12343            }
12344        }
12345
12346        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12347            if (origin.staged) {
12348                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12349                codeFile = origin.file;
12350                resourceFile = origin.file;
12351                return PackageManager.INSTALL_SUCCEEDED;
12352            }
12353
12354            try {
12355                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12356                final File tempDir =
12357                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12358                codeFile = tempDir;
12359                resourceFile = tempDir;
12360            } catch (IOException e) {
12361                Slog.w(TAG, "Failed to create copy file: " + e);
12362                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12363            }
12364
12365            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12366                @Override
12367                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12368                    if (!FileUtils.isValidExtFilename(name)) {
12369                        throw new IllegalArgumentException("Invalid filename: " + name);
12370                    }
12371                    try {
12372                        final File file = new File(codeFile, name);
12373                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12374                                O_RDWR | O_CREAT, 0644);
12375                        Os.chmod(file.getAbsolutePath(), 0644);
12376                        return new ParcelFileDescriptor(fd);
12377                    } catch (ErrnoException e) {
12378                        throw new RemoteException("Failed to open: " + e.getMessage());
12379                    }
12380                }
12381            };
12382
12383            int ret = PackageManager.INSTALL_SUCCEEDED;
12384            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12385            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12386                Slog.e(TAG, "Failed to copy package");
12387                return ret;
12388            }
12389
12390            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12391            NativeLibraryHelper.Handle handle = null;
12392            try {
12393                handle = NativeLibraryHelper.Handle.create(codeFile);
12394                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12395                        abiOverride);
12396            } catch (IOException e) {
12397                Slog.e(TAG, "Copying native libraries failed", e);
12398                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12399            } finally {
12400                IoUtils.closeQuietly(handle);
12401            }
12402
12403            return ret;
12404        }
12405
12406        int doPreInstall(int status) {
12407            if (status != PackageManager.INSTALL_SUCCEEDED) {
12408                cleanUp();
12409            }
12410            return status;
12411        }
12412
12413        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12414            if (status != PackageManager.INSTALL_SUCCEEDED) {
12415                cleanUp();
12416                return false;
12417            }
12418
12419            final File targetDir = codeFile.getParentFile();
12420            final File beforeCodeFile = codeFile;
12421            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12422
12423            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12424            try {
12425                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12426            } catch (ErrnoException e) {
12427                Slog.w(TAG, "Failed to rename", e);
12428                return false;
12429            }
12430
12431            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12432                Slog.w(TAG, "Failed to restorecon");
12433                return false;
12434            }
12435
12436            // Reflect the rename internally
12437            codeFile = afterCodeFile;
12438            resourceFile = afterCodeFile;
12439
12440            // Reflect the rename in scanned details
12441            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12442            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12443                    afterCodeFile, pkg.baseCodePath));
12444            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12445                    afterCodeFile, pkg.splitCodePaths));
12446
12447            // Reflect the rename in app info
12448            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12449            pkg.setApplicationInfoCodePath(pkg.codePath);
12450            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12451            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12452            pkg.setApplicationInfoResourcePath(pkg.codePath);
12453            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12454            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12455
12456            return true;
12457        }
12458
12459        int doPostInstall(int status, int uid) {
12460            if (status != PackageManager.INSTALL_SUCCEEDED) {
12461                cleanUp();
12462            }
12463            return status;
12464        }
12465
12466        @Override
12467        String getCodePath() {
12468            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12469        }
12470
12471        @Override
12472        String getResourcePath() {
12473            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12474        }
12475
12476        private boolean cleanUp() {
12477            if (codeFile == null || !codeFile.exists()) {
12478                return false;
12479            }
12480
12481            removeCodePathLI(codeFile);
12482
12483            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12484                resourceFile.delete();
12485            }
12486
12487            return true;
12488        }
12489
12490        void cleanUpResourcesLI() {
12491            // Try enumerating all code paths before deleting
12492            List<String> allCodePaths = Collections.EMPTY_LIST;
12493            if (codeFile != null && codeFile.exists()) {
12494                try {
12495                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12496                    allCodePaths = pkg.getAllCodePaths();
12497                } catch (PackageParserException e) {
12498                    // Ignored; we tried our best
12499                }
12500            }
12501
12502            cleanUp();
12503            removeDexFiles(allCodePaths, instructionSets);
12504        }
12505
12506        boolean doPostDeleteLI(boolean delete) {
12507            // XXX err, shouldn't we respect the delete flag?
12508            cleanUpResourcesLI();
12509            return true;
12510        }
12511    }
12512
12513    private boolean isAsecExternal(String cid) {
12514        final String asecPath = PackageHelper.getSdFilesystem(cid);
12515        return !asecPath.startsWith(mAsecInternalPath);
12516    }
12517
12518    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12519            PackageManagerException {
12520        if (copyRet < 0) {
12521            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12522                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12523                throw new PackageManagerException(copyRet, message);
12524            }
12525        }
12526    }
12527
12528    /**
12529     * Extract the MountService "container ID" from the full code path of an
12530     * .apk.
12531     */
12532    static String cidFromCodePath(String fullCodePath) {
12533        int eidx = fullCodePath.lastIndexOf("/");
12534        String subStr1 = fullCodePath.substring(0, eidx);
12535        int sidx = subStr1.lastIndexOf("/");
12536        return subStr1.substring(sidx+1, eidx);
12537    }
12538
12539    /**
12540     * Logic to handle installation of ASEC applications, including copying and
12541     * renaming logic.
12542     */
12543    class AsecInstallArgs extends InstallArgs {
12544        static final String RES_FILE_NAME = "pkg.apk";
12545        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12546
12547        String cid;
12548        String packagePath;
12549        String resourcePath;
12550
12551        /** New install */
12552        AsecInstallArgs(InstallParams params) {
12553            super(params.origin, params.move, params.observer, params.installFlags,
12554                    params.installerPackageName, params.volumeUuid,
12555                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12556                    params.grantedRuntimePermissions,
12557                    params.traceMethod, params.traceCookie);
12558        }
12559
12560        /** Existing install */
12561        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12562                        boolean isExternal, boolean isForwardLocked) {
12563            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12564                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12565                    instructionSets, null, null, null, 0);
12566            // Hackily pretend we're still looking at a full code path
12567            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12568                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12569            }
12570
12571            // Extract cid from fullCodePath
12572            int eidx = fullCodePath.lastIndexOf("/");
12573            String subStr1 = fullCodePath.substring(0, eidx);
12574            int sidx = subStr1.lastIndexOf("/");
12575            cid = subStr1.substring(sidx+1, eidx);
12576            setMountPath(subStr1);
12577        }
12578
12579        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12580            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12581                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12582                    instructionSets, null, null, null, 0);
12583            this.cid = cid;
12584            setMountPath(PackageHelper.getSdDir(cid));
12585        }
12586
12587        void createCopyFile() {
12588            cid = mInstallerService.allocateExternalStageCidLegacy();
12589        }
12590
12591        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12592            if (origin.staged && origin.cid != null) {
12593                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12594                cid = origin.cid;
12595                setMountPath(PackageHelper.getSdDir(cid));
12596                return PackageManager.INSTALL_SUCCEEDED;
12597            }
12598
12599            if (temp) {
12600                createCopyFile();
12601            } else {
12602                /*
12603                 * Pre-emptively destroy the container since it's destroyed if
12604                 * copying fails due to it existing anyway.
12605                 */
12606                PackageHelper.destroySdDir(cid);
12607            }
12608
12609            final String newMountPath = imcs.copyPackageToContainer(
12610                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12611                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12612
12613            if (newMountPath != null) {
12614                setMountPath(newMountPath);
12615                return PackageManager.INSTALL_SUCCEEDED;
12616            } else {
12617                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12618            }
12619        }
12620
12621        @Override
12622        String getCodePath() {
12623            return packagePath;
12624        }
12625
12626        @Override
12627        String getResourcePath() {
12628            return resourcePath;
12629        }
12630
12631        int doPreInstall(int status) {
12632            if (status != PackageManager.INSTALL_SUCCEEDED) {
12633                // Destroy container
12634                PackageHelper.destroySdDir(cid);
12635            } else {
12636                boolean mounted = PackageHelper.isContainerMounted(cid);
12637                if (!mounted) {
12638                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12639                            Process.SYSTEM_UID);
12640                    if (newMountPath != null) {
12641                        setMountPath(newMountPath);
12642                    } else {
12643                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12644                    }
12645                }
12646            }
12647            return status;
12648        }
12649
12650        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12651            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12652            String newMountPath = null;
12653            if (PackageHelper.isContainerMounted(cid)) {
12654                // Unmount the container
12655                if (!PackageHelper.unMountSdDir(cid)) {
12656                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12657                    return false;
12658                }
12659            }
12660            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12661                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12662                        " which might be stale. Will try to clean up.");
12663                // Clean up the stale container and proceed to recreate.
12664                if (!PackageHelper.destroySdDir(newCacheId)) {
12665                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12666                    return false;
12667                }
12668                // Successfully cleaned up stale container. Try to rename again.
12669                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12670                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12671                            + " inspite of cleaning it up.");
12672                    return false;
12673                }
12674            }
12675            if (!PackageHelper.isContainerMounted(newCacheId)) {
12676                Slog.w(TAG, "Mounting container " + newCacheId);
12677                newMountPath = PackageHelper.mountSdDir(newCacheId,
12678                        getEncryptKey(), Process.SYSTEM_UID);
12679            } else {
12680                newMountPath = PackageHelper.getSdDir(newCacheId);
12681            }
12682            if (newMountPath == null) {
12683                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12684                return false;
12685            }
12686            Log.i(TAG, "Succesfully renamed " + cid +
12687                    " to " + newCacheId +
12688                    " at new path: " + newMountPath);
12689            cid = newCacheId;
12690
12691            final File beforeCodeFile = new File(packagePath);
12692            setMountPath(newMountPath);
12693            final File afterCodeFile = new File(packagePath);
12694
12695            // Reflect the rename in scanned details
12696            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12697            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12698                    afterCodeFile, pkg.baseCodePath));
12699            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12700                    afterCodeFile, pkg.splitCodePaths));
12701
12702            // Reflect the rename in app info
12703            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12704            pkg.setApplicationInfoCodePath(pkg.codePath);
12705            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12706            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12707            pkg.setApplicationInfoResourcePath(pkg.codePath);
12708            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12709            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12710
12711            return true;
12712        }
12713
12714        private void setMountPath(String mountPath) {
12715            final File mountFile = new File(mountPath);
12716
12717            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12718            if (monolithicFile.exists()) {
12719                packagePath = monolithicFile.getAbsolutePath();
12720                if (isFwdLocked()) {
12721                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12722                } else {
12723                    resourcePath = packagePath;
12724                }
12725            } else {
12726                packagePath = mountFile.getAbsolutePath();
12727                resourcePath = packagePath;
12728            }
12729        }
12730
12731        int doPostInstall(int status, int uid) {
12732            if (status != PackageManager.INSTALL_SUCCEEDED) {
12733                cleanUp();
12734            } else {
12735                final int groupOwner;
12736                final String protectedFile;
12737                if (isFwdLocked()) {
12738                    groupOwner = UserHandle.getSharedAppGid(uid);
12739                    protectedFile = RES_FILE_NAME;
12740                } else {
12741                    groupOwner = -1;
12742                    protectedFile = null;
12743                }
12744
12745                if (uid < Process.FIRST_APPLICATION_UID
12746                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12747                    Slog.e(TAG, "Failed to finalize " + cid);
12748                    PackageHelper.destroySdDir(cid);
12749                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12750                }
12751
12752                boolean mounted = PackageHelper.isContainerMounted(cid);
12753                if (!mounted) {
12754                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12755                }
12756            }
12757            return status;
12758        }
12759
12760        private void cleanUp() {
12761            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12762
12763            // Destroy secure container
12764            PackageHelper.destroySdDir(cid);
12765        }
12766
12767        private List<String> getAllCodePaths() {
12768            final File codeFile = new File(getCodePath());
12769            if (codeFile != null && codeFile.exists()) {
12770                try {
12771                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12772                    return pkg.getAllCodePaths();
12773                } catch (PackageParserException e) {
12774                    // Ignored; we tried our best
12775                }
12776            }
12777            return Collections.EMPTY_LIST;
12778        }
12779
12780        void cleanUpResourcesLI() {
12781            // Enumerate all code paths before deleting
12782            cleanUpResourcesLI(getAllCodePaths());
12783        }
12784
12785        private void cleanUpResourcesLI(List<String> allCodePaths) {
12786            cleanUp();
12787            removeDexFiles(allCodePaths, instructionSets);
12788        }
12789
12790        String getPackageName() {
12791            return getAsecPackageName(cid);
12792        }
12793
12794        boolean doPostDeleteLI(boolean delete) {
12795            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12796            final List<String> allCodePaths = getAllCodePaths();
12797            boolean mounted = PackageHelper.isContainerMounted(cid);
12798            if (mounted) {
12799                // Unmount first
12800                if (PackageHelper.unMountSdDir(cid)) {
12801                    mounted = false;
12802                }
12803            }
12804            if (!mounted && delete) {
12805                cleanUpResourcesLI(allCodePaths);
12806            }
12807            return !mounted;
12808        }
12809
12810        @Override
12811        int doPreCopy() {
12812            if (isFwdLocked()) {
12813                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12814                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12815                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12816                }
12817            }
12818
12819            return PackageManager.INSTALL_SUCCEEDED;
12820        }
12821
12822        @Override
12823        int doPostCopy(int uid) {
12824            if (isFwdLocked()) {
12825                if (uid < Process.FIRST_APPLICATION_UID
12826                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12827                                RES_FILE_NAME)) {
12828                    Slog.e(TAG, "Failed to finalize " + cid);
12829                    PackageHelper.destroySdDir(cid);
12830                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12831                }
12832            }
12833
12834            return PackageManager.INSTALL_SUCCEEDED;
12835        }
12836    }
12837
12838    /**
12839     * Logic to handle movement of existing installed applications.
12840     */
12841    class MoveInstallArgs extends InstallArgs {
12842        private File codeFile;
12843        private File resourceFile;
12844
12845        /** New install */
12846        MoveInstallArgs(InstallParams params) {
12847            super(params.origin, params.move, params.observer, params.installFlags,
12848                    params.installerPackageName, params.volumeUuid,
12849                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12850                    params.grantedRuntimePermissions,
12851                    params.traceMethod, params.traceCookie);
12852        }
12853
12854        int copyApk(IMediaContainerService imcs, boolean temp) {
12855            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12856                    + move.fromUuid + " to " + move.toUuid);
12857            synchronized (mInstaller) {
12858                try {
12859                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12860                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12861                } catch (InstallerException e) {
12862                    Slog.w(TAG, "Failed to move app", e);
12863                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12864                }
12865            }
12866
12867            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12868            resourceFile = codeFile;
12869            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12870
12871            return PackageManager.INSTALL_SUCCEEDED;
12872        }
12873
12874        int doPreInstall(int status) {
12875            if (status != PackageManager.INSTALL_SUCCEEDED) {
12876                cleanUp(move.toUuid);
12877            }
12878            return status;
12879        }
12880
12881        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12882            if (status != PackageManager.INSTALL_SUCCEEDED) {
12883                cleanUp(move.toUuid);
12884                return false;
12885            }
12886
12887            // Reflect the move in app info
12888            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12889            pkg.setApplicationInfoCodePath(pkg.codePath);
12890            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12891            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12892            pkg.setApplicationInfoResourcePath(pkg.codePath);
12893            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12894            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12895
12896            return true;
12897        }
12898
12899        int doPostInstall(int status, int uid) {
12900            if (status == PackageManager.INSTALL_SUCCEEDED) {
12901                cleanUp(move.fromUuid);
12902            } else {
12903                cleanUp(move.toUuid);
12904            }
12905            return status;
12906        }
12907
12908        @Override
12909        String getCodePath() {
12910            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12911        }
12912
12913        @Override
12914        String getResourcePath() {
12915            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12916        }
12917
12918        private boolean cleanUp(String volumeUuid) {
12919            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12920                    move.dataAppName);
12921            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12922            synchronized (mInstallLock) {
12923                // Clean up both app data and code
12924                removeDataDirsLI(volumeUuid, move.packageName);
12925                removeCodePathLI(codeFile);
12926            }
12927            return true;
12928        }
12929
12930        void cleanUpResourcesLI() {
12931            throw new UnsupportedOperationException();
12932        }
12933
12934        boolean doPostDeleteLI(boolean delete) {
12935            throw new UnsupportedOperationException();
12936        }
12937    }
12938
12939    static String getAsecPackageName(String packageCid) {
12940        int idx = packageCid.lastIndexOf("-");
12941        if (idx == -1) {
12942            return packageCid;
12943        }
12944        return packageCid.substring(0, idx);
12945    }
12946
12947    // Utility method used to create code paths based on package name and available index.
12948    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12949        String idxStr = "";
12950        int idx = 1;
12951        // Fall back to default value of idx=1 if prefix is not
12952        // part of oldCodePath
12953        if (oldCodePath != null) {
12954            String subStr = oldCodePath;
12955            // Drop the suffix right away
12956            if (suffix != null && subStr.endsWith(suffix)) {
12957                subStr = subStr.substring(0, subStr.length() - suffix.length());
12958            }
12959            // If oldCodePath already contains prefix find out the
12960            // ending index to either increment or decrement.
12961            int sidx = subStr.lastIndexOf(prefix);
12962            if (sidx != -1) {
12963                subStr = subStr.substring(sidx + prefix.length());
12964                if (subStr != null) {
12965                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12966                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12967                    }
12968                    try {
12969                        idx = Integer.parseInt(subStr);
12970                        if (idx <= 1) {
12971                            idx++;
12972                        } else {
12973                            idx--;
12974                        }
12975                    } catch(NumberFormatException e) {
12976                    }
12977                }
12978            }
12979        }
12980        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12981        return prefix + idxStr;
12982    }
12983
12984    private File getNextCodePath(File targetDir, String packageName) {
12985        int suffix = 1;
12986        File result;
12987        do {
12988            result = new File(targetDir, packageName + "-" + suffix);
12989            suffix++;
12990        } while (result.exists());
12991        return result;
12992    }
12993
12994    // Utility method that returns the relative package path with respect
12995    // to the installation directory. Like say for /data/data/com.test-1.apk
12996    // string com.test-1 is returned.
12997    static String deriveCodePathName(String codePath) {
12998        if (codePath == null) {
12999            return null;
13000        }
13001        final File codeFile = new File(codePath);
13002        final String name = codeFile.getName();
13003        if (codeFile.isDirectory()) {
13004            return name;
13005        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13006            final int lastDot = name.lastIndexOf('.');
13007            return name.substring(0, lastDot);
13008        } else {
13009            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13010            return null;
13011        }
13012    }
13013
13014    static class PackageInstalledInfo {
13015        String name;
13016        int uid;
13017        // The set of users that originally had this package installed.
13018        int[] origUsers;
13019        // The set of users that now have this package installed.
13020        int[] newUsers;
13021        PackageParser.Package pkg;
13022        int returnCode;
13023        String returnMsg;
13024        PackageRemovedInfo removedInfo;
13025        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13026
13027        public void setError(int code, String msg) {
13028            setReturnCode(code);
13029            setReturnMessage(msg);
13030            Slog.w(TAG, msg);
13031        }
13032
13033        public void setError(String msg, PackageParserException e) {
13034            setReturnCode(e.error);
13035            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13036            Slog.w(TAG, msg, e);
13037        }
13038
13039        public void setError(String msg, PackageManagerException e) {
13040            returnCode = e.error;
13041            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13042            Slog.w(TAG, msg, e);
13043        }
13044
13045        public void setReturnCode(int returnCode) {
13046            this.returnCode = returnCode;
13047            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13048            for (int i = 0; i < childCount; i++) {
13049                addedChildPackages.valueAt(i).returnCode = returnCode;
13050            }
13051        }
13052
13053        private void setReturnMessage(String returnMsg) {
13054            this.returnMsg = returnMsg;
13055            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13056            for (int i = 0; i < childCount; i++) {
13057                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13058            }
13059        }
13060
13061        // In some error cases we want to convey more info back to the observer
13062        String origPackage;
13063        String origPermission;
13064    }
13065
13066    /*
13067     * Install a non-existing package.
13068     */
13069    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13070            UserHandle user, String installerPackageName, String volumeUuid,
13071            PackageInstalledInfo res) {
13072        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13073
13074        // Remember this for later, in case we need to rollback this install
13075        String pkgName = pkg.packageName;
13076
13077        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13078
13079        synchronized(mPackages) {
13080            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13081                // A package with the same name is already installed, though
13082                // it has been renamed to an older name.  The package we
13083                // are trying to install should be installed as an update to
13084                // the existing one, but that has not been requested, so bail.
13085                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13086                        + " without first uninstalling package running as "
13087                        + mSettings.mRenamedPackages.get(pkgName));
13088                return;
13089            }
13090            if (mPackages.containsKey(pkgName)) {
13091                // Don't allow installation over an existing package with the same name.
13092                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13093                        + " without first uninstalling.");
13094                return;
13095            }
13096        }
13097
13098        try {
13099            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13100                    System.currentTimeMillis(), user);
13101
13102            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13103
13104            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13105                prepareAppDataAfterInstall(newPackage);
13106
13107            } else {
13108                // Remove package from internal structures, but keep around any
13109                // data that might have already existed
13110                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13111                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13112            }
13113        } catch (PackageManagerException e) {
13114            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13115        }
13116
13117        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13118    }
13119
13120    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13121        // Can't rotate keys during boot or if sharedUser.
13122        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13123                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13124            return false;
13125        }
13126        // app is using upgradeKeySets; make sure all are valid
13127        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13128        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13129        for (int i = 0; i < upgradeKeySets.length; i++) {
13130            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13131                Slog.wtf(TAG, "Package "
13132                         + (oldPs.name != null ? oldPs.name : "<null>")
13133                         + " contains upgrade-key-set reference to unknown key-set: "
13134                         + upgradeKeySets[i]
13135                         + " reverting to signatures check.");
13136                return false;
13137            }
13138        }
13139        return true;
13140    }
13141
13142    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13143        // Upgrade keysets are being used.  Determine if new package has a superset of the
13144        // required keys.
13145        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13146        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13147        for (int i = 0; i < upgradeKeySets.length; i++) {
13148            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13149            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13150                return true;
13151            }
13152        }
13153        return false;
13154    }
13155
13156    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13157            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13158        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13159
13160        final PackageParser.Package oldPackage;
13161        final String pkgName = pkg.packageName;
13162        final int[] allUsers;
13163        final boolean weFroze;
13164
13165        // First find the old package info and check signatures
13166        synchronized(mPackages) {
13167            oldPackage = mPackages.get(pkgName);
13168            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13169            if (isEphemeral && !oldIsEphemeral) {
13170                // can't downgrade from full to ephemeral
13171                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13172                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13173                return;
13174            }
13175            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13176            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13177            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13178                if (!checkUpgradeKeySetLP(ps, pkg)) {
13179                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13180                            "New package not signed by keys specified by upgrade-keysets: "
13181                                    + pkgName);
13182                    return;
13183                }
13184            } else {
13185                // default to original signature matching
13186                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13187                        != PackageManager.SIGNATURE_MATCH) {
13188                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13189                            "New package has a different signature: " + pkgName);
13190                    return;
13191                }
13192            }
13193
13194            // In case of rollback, remember per-user/profile install state
13195            allUsers = sUserManager.getUserIds();
13196
13197            // Mark the app as frozen to prevent launching during the upgrade
13198            // process, and then kill all running instances
13199            if (!ps.frozen) {
13200                ps.frozen = true;
13201                weFroze = true;
13202            } else {
13203                weFroze = false;
13204            }
13205        }
13206
13207        try {
13208            replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers,
13209                    installerPackageName, res);
13210        } finally {
13211            // Regardless of success or failure of upgrade steps above, always
13212            // unfreeze the package if we froze it
13213            if (weFroze) {
13214                unfreezePackage(pkgName);
13215            }
13216        }
13217    }
13218
13219    private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage,
13220            int parseFlags, int scanFlags, UserHandle user, int[] allUsers,
13221            String installerPackageName, PackageInstalledInfo res) {
13222        // Update what is removed
13223        res.removedInfo = new PackageRemovedInfo();
13224        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13225        res.removedInfo.removedPackage = oldPackage.packageName;
13226        res.removedInfo.isUpdate = true;
13227        final int childCount = (oldPackage.childPackages != null)
13228                ? oldPackage.childPackages.size() : 0;
13229        for (int i = 0; i < childCount; i++) {
13230            boolean childPackageUpdated = false;
13231            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13232            if (res.addedChildPackages != null) {
13233                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13234                if (childRes != null) {
13235                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13236                    childRes.removedInfo.removedPackage = childPkg.packageName;
13237                    childRes.removedInfo.isUpdate = true;
13238                    childPackageUpdated = true;
13239                }
13240            }
13241            if (!childPackageUpdated) {
13242                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13243                childRemovedRes.removedPackage = childPkg.packageName;
13244                childRemovedRes.isUpdate = false;
13245                childRemovedRes.dataRemoved = true;
13246                synchronized (mPackages) {
13247                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13248                    if (childPs != null) {
13249                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13250                    }
13251                }
13252                if (res.removedInfo.removedChildPackages == null) {
13253                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13254                }
13255                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13256            }
13257        }
13258
13259        boolean sysPkg = (isSystemApp(oldPackage));
13260        if (sysPkg) {
13261            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13262                    user, allUsers, installerPackageName, res);
13263        } else {
13264            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13265                    user, allUsers, installerPackageName, res);
13266        }
13267    }
13268
13269    public List<String> getPreviousCodePaths(String packageName) {
13270        final PackageSetting ps = mSettings.mPackages.get(packageName);
13271        final List<String> result = new ArrayList<String>();
13272        if (ps != null && ps.oldCodePaths != null) {
13273            result.addAll(ps.oldCodePaths);
13274        }
13275        return result;
13276    }
13277
13278    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13279            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13280            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13281        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13282                + deletedPackage);
13283
13284        String pkgName = deletedPackage.packageName;
13285        boolean deletedPkg = true;
13286        boolean addedPkg = false;
13287        boolean updatedSettings = false;
13288        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13289        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13290                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13291
13292        final long origUpdateTime = (pkg.mExtras != null)
13293                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13294
13295        // First delete the existing package while retaining the data directory
13296        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13297                res.removedInfo, true, pkg)) {
13298            // If the existing package wasn't successfully deleted
13299            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13300            deletedPkg = false;
13301        } else {
13302            // Successfully deleted the old package; proceed with replace.
13303
13304            // If deleted package lived in a container, give users a chance to
13305            // relinquish resources before killing.
13306            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13307                if (DEBUG_INSTALL) {
13308                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13309                }
13310                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13311                final ArrayList<String> pkgList = new ArrayList<String>(1);
13312                pkgList.add(deletedPackage.applicationInfo.packageName);
13313                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13314            }
13315
13316            deleteCodeCacheDirsLI(pkg);
13317            deleteProfilesLI(pkg, /*destroy*/ false);
13318
13319            try {
13320                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13321                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13322                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13323
13324                // Update the in-memory copy of the previous code paths.
13325                PackageSetting ps = mSettings.mPackages.get(pkgName);
13326                if (!killApp) {
13327                    if (ps.oldCodePaths == null) {
13328                        ps.oldCodePaths = new ArraySet<>();
13329                    }
13330                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13331                    if (deletedPackage.splitCodePaths != null) {
13332                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13333                    }
13334                } else {
13335                    ps.oldCodePaths = null;
13336                }
13337                if (ps.childPackageNames != null) {
13338                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13339                        final String childPkgName = ps.childPackageNames.get(i);
13340                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13341                        childPs.oldCodePaths = ps.oldCodePaths;
13342                    }
13343                }
13344                prepareAppDataAfterInstall(newPackage);
13345                addedPkg = true;
13346            } catch (PackageManagerException e) {
13347                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13348            }
13349        }
13350
13351        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13352            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13353
13354            // Revert all internal state mutations and added folders for the failed install
13355            if (addedPkg) {
13356                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13357                        res.removedInfo, true, null);
13358            }
13359
13360            // Restore the old package
13361            if (deletedPkg) {
13362                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13363                File restoreFile = new File(deletedPackage.codePath);
13364                // Parse old package
13365                boolean oldExternal = isExternal(deletedPackage);
13366                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13367                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13368                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13369                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13370                try {
13371                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13372                            null);
13373                } catch (PackageManagerException e) {
13374                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13375                            + e.getMessage());
13376                    return;
13377                }
13378
13379                synchronized (mPackages) {
13380                    // Ensure the installer package name up to date
13381                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13382
13383                    // Update permissions for restored package
13384                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13385
13386                    mSettings.writeLPr();
13387                }
13388
13389                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13390            }
13391        } else {
13392            synchronized (mPackages) {
13393                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13394                if (ps != null) {
13395                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13396                    if (res.removedInfo.removedChildPackages != null) {
13397                        final int childCount = res.removedInfo.removedChildPackages.size();
13398                        // Iterate in reverse as we may modify the collection
13399                        for (int i = childCount - 1; i >= 0; i--) {
13400                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13401                            if (res.addedChildPackages.containsKey(childPackageName)) {
13402                                res.removedInfo.removedChildPackages.removeAt(i);
13403                            } else {
13404                                PackageRemovedInfo childInfo = res.removedInfo
13405                                        .removedChildPackages.valueAt(i);
13406                                childInfo.removedForAllUsers = mPackages.get(
13407                                        childInfo.removedPackage) == null;
13408                            }
13409                        }
13410                    }
13411                }
13412            }
13413        }
13414    }
13415
13416    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13417            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13418            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13419        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13420                + ", old=" + deletedPackage);
13421
13422        final boolean disabledSystem;
13423
13424        // Set the system/privileged flags as needed
13425        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13426        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13427                != 0) {
13428            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13429        }
13430
13431        // Kill package processes including services, providers, etc.
13432        killPackage(deletedPackage, "replace sys pkg");
13433
13434        // Remove existing system package
13435        removePackageLI(deletedPackage, true);
13436
13437        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13438        if (!disabledSystem) {
13439            // We didn't need to disable the .apk as a current system package,
13440            // which means we are replacing another update that is already
13441            // installed.  We need to make sure to delete the older one's .apk.
13442            res.removedInfo.args = createInstallArgsForExisting(0,
13443                    deletedPackage.applicationInfo.getCodePath(),
13444                    deletedPackage.applicationInfo.getResourcePath(),
13445                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13446        } else {
13447            res.removedInfo.args = null;
13448        }
13449
13450        // Successfully disabled the old package. Now proceed with re-installation
13451        deleteCodeCacheDirsLI(pkg);
13452        deleteProfilesLI(pkg, /*destroy*/ false);
13453
13454        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13455        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13456                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13457
13458        PackageParser.Package newPackage = null;
13459        try {
13460            // Add the package to the internal data structures
13461            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13462
13463            // Set the update and install times
13464            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13465            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13466                    System.currentTimeMillis());
13467
13468            // Check for shared user id changes
13469            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13470                    deletedPackage, newPackage);
13471            if (invalidPackageName != null) {
13472                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13473                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13474                                + " to " + invalidPackageName);
13475            }
13476
13477            // Update the package dynamic state if succeeded
13478            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13479                // Now that the install succeeded make sure we remove data
13480                // directories for any child package the update removed.
13481                final int deletedChildCount = (deletedPackage.childPackages != null)
13482                        ? deletedPackage.childPackages.size() : 0;
13483                final int newChildCount = (newPackage.childPackages != null)
13484                        ? newPackage.childPackages.size() : 0;
13485                for (int i = 0; i < deletedChildCount; i++) {
13486                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13487                    boolean childPackageDeleted = true;
13488                    for (int j = 0; j < newChildCount; j++) {
13489                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13490                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13491                            childPackageDeleted = false;
13492                            break;
13493                        }
13494                    }
13495                    if (childPackageDeleted) {
13496                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13497                                deletedChildPkg.packageName);
13498                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13499                            PackageRemovedInfo removedChildRes = res.removedInfo
13500                                    .removedChildPackages.get(deletedChildPkg.packageName);
13501                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13502                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13503                        }
13504                    }
13505                }
13506
13507                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13508                prepareAppDataAfterInstall(newPackage);
13509            }
13510        } catch (PackageManagerException e) {
13511            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13512            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13513        }
13514
13515        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13516            // Re installation failed. Restore old information
13517            // Remove new pkg information
13518            if (newPackage != null) {
13519                removeInstalledPackageLI(newPackage, true);
13520            }
13521            // Add back the old system package
13522            try {
13523                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13524            } catch (PackageManagerException e) {
13525                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13526            }
13527
13528            synchronized (mPackages) {
13529                if (disabledSystem) {
13530                    enableSystemPackageLPw(deletedPackage);
13531                }
13532
13533                // Ensure the installer package name up to date
13534                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13535
13536                // Update permissions for restored package
13537                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13538
13539                mSettings.writeLPr();
13540            }
13541
13542            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13543                    + " after failed upgrade");
13544        }
13545    }
13546
13547    /**
13548     * Checks whether the parent or any of the child packages have a change shared
13549     * user. For a package to be a valid update the shred users of the parent and
13550     * the children should match. We may later support changing child shared users.
13551     * @param oldPkg The updated package.
13552     * @param newPkg The update package.
13553     * @return The shared user that change between the versions.
13554     */
13555    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13556            PackageParser.Package newPkg) {
13557        // Check parent shared user
13558        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13559            return newPkg.packageName;
13560        }
13561        // Check child shared users
13562        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13563        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13564        for (int i = 0; i < newChildCount; i++) {
13565            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13566            // If this child was present, did it have the same shared user?
13567            for (int j = 0; j < oldChildCount; j++) {
13568                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13569                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13570                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13571                    return newChildPkg.packageName;
13572                }
13573            }
13574        }
13575        return null;
13576    }
13577
13578    private void removeNativeBinariesLI(PackageSetting ps) {
13579        // Remove the lib path for the parent package
13580        if (ps != null) {
13581            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13582            // Remove the lib path for the child packages
13583            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13584            for (int i = 0; i < childCount; i++) {
13585                PackageSetting childPs = null;
13586                synchronized (mPackages) {
13587                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13588                }
13589                if (childPs != null) {
13590                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13591                            .legacyNativeLibraryPathString);
13592                }
13593            }
13594        }
13595    }
13596
13597    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13598        // Enable the parent package
13599        mSettings.enableSystemPackageLPw(pkg.packageName);
13600        // Enable the child packages
13601        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13602        for (int i = 0; i < childCount; i++) {
13603            PackageParser.Package childPkg = pkg.childPackages.get(i);
13604            mSettings.enableSystemPackageLPw(childPkg.packageName);
13605        }
13606    }
13607
13608    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13609            PackageParser.Package newPkg) {
13610        // Disable the parent package (parent always replaced)
13611        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13612        // Disable the child packages
13613        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13614        for (int i = 0; i < childCount; i++) {
13615            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13616            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13617            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13618        }
13619        return disabled;
13620    }
13621
13622    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13623            String installerPackageName) {
13624        // Enable the parent package
13625        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13626        // Enable the child packages
13627        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13628        for (int i = 0; i < childCount; i++) {
13629            PackageParser.Package childPkg = pkg.childPackages.get(i);
13630            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13631        }
13632    }
13633
13634    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13635        // Collect all used permissions in the UID
13636        ArraySet<String> usedPermissions = new ArraySet<>();
13637        final int packageCount = su.packages.size();
13638        for (int i = 0; i < packageCount; i++) {
13639            PackageSetting ps = su.packages.valueAt(i);
13640            if (ps.pkg == null) {
13641                continue;
13642            }
13643            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13644            for (int j = 0; j < requestedPermCount; j++) {
13645                String permission = ps.pkg.requestedPermissions.get(j);
13646                BasePermission bp = mSettings.mPermissions.get(permission);
13647                if (bp != null) {
13648                    usedPermissions.add(permission);
13649                }
13650            }
13651        }
13652
13653        PermissionsState permissionsState = su.getPermissionsState();
13654        // Prune install permissions
13655        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13656        final int installPermCount = installPermStates.size();
13657        for (int i = installPermCount - 1; i >= 0;  i--) {
13658            PermissionState permissionState = installPermStates.get(i);
13659            if (!usedPermissions.contains(permissionState.getName())) {
13660                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13661                if (bp != null) {
13662                    permissionsState.revokeInstallPermission(bp);
13663                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13664                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13665                }
13666            }
13667        }
13668
13669        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13670
13671        // Prune runtime permissions
13672        for (int userId : allUserIds) {
13673            List<PermissionState> runtimePermStates = permissionsState
13674                    .getRuntimePermissionStates(userId);
13675            final int runtimePermCount = runtimePermStates.size();
13676            for (int i = runtimePermCount - 1; i >= 0; i--) {
13677                PermissionState permissionState = runtimePermStates.get(i);
13678                if (!usedPermissions.contains(permissionState.getName())) {
13679                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13680                    if (bp != null) {
13681                        permissionsState.revokeRuntimePermission(bp, userId);
13682                        permissionsState.updatePermissionFlags(bp, userId,
13683                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13684                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13685                                runtimePermissionChangedUserIds, userId);
13686                    }
13687                }
13688            }
13689        }
13690
13691        return runtimePermissionChangedUserIds;
13692    }
13693
13694    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13695            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13696        // Update the parent package setting
13697        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13698                res, user);
13699        // Update the child packages setting
13700        final int childCount = (newPackage.childPackages != null)
13701                ? newPackage.childPackages.size() : 0;
13702        for (int i = 0; i < childCount; i++) {
13703            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13704            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13705            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13706                    childRes.origUsers, childRes, user);
13707        }
13708    }
13709
13710    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13711            String installerPackageName, int[] allUsers, int[] installedForUsers,
13712            PackageInstalledInfo res, UserHandle user) {
13713        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13714
13715        String pkgName = newPackage.packageName;
13716        synchronized (mPackages) {
13717            //write settings. the installStatus will be incomplete at this stage.
13718            //note that the new package setting would have already been
13719            //added to mPackages. It hasn't been persisted yet.
13720            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13721            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13722            mSettings.writeLPr();
13723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13724        }
13725
13726        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13727        synchronized (mPackages) {
13728            updatePermissionsLPw(newPackage.packageName, newPackage,
13729                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13730                            ? UPDATE_PERMISSIONS_ALL : 0));
13731            // For system-bundled packages, we assume that installing an upgraded version
13732            // of the package implies that the user actually wants to run that new code,
13733            // so we enable the package.
13734            PackageSetting ps = mSettings.mPackages.get(pkgName);
13735            final int userId = user.getIdentifier();
13736            if (ps != null) {
13737                if (isSystemApp(newPackage)) {
13738                    if (DEBUG_INSTALL) {
13739                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13740                    }
13741                    // Enable system package for requested users
13742                    if (res.origUsers != null) {
13743                        for (int origUserId : res.origUsers) {
13744                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13745                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13746                                        origUserId, installerPackageName);
13747                            }
13748                        }
13749                    }
13750                    // Also convey the prior install/uninstall state
13751                    if (allUsers != null && installedForUsers != null) {
13752                        for (int currentUserId : allUsers) {
13753                            final boolean installed = ArrayUtils.contains(
13754                                    installedForUsers, currentUserId);
13755                            if (DEBUG_INSTALL) {
13756                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13757                            }
13758                            ps.setInstalled(installed, currentUserId);
13759                        }
13760                        // these install state changes will be persisted in the
13761                        // upcoming call to mSettings.writeLPr().
13762                    }
13763                }
13764                // It's implied that when a user requests installation, they want the app to be
13765                // installed and enabled.
13766                if (userId != UserHandle.USER_ALL) {
13767                    ps.setInstalled(true, userId);
13768                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13769                }
13770            }
13771            res.name = pkgName;
13772            res.uid = newPackage.applicationInfo.uid;
13773            res.pkg = newPackage;
13774            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13775            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13776            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13777            //to update install status
13778            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13779            mSettings.writeLPr();
13780            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13781        }
13782
13783        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13784    }
13785
13786    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13787        try {
13788            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13789            installPackageLI(args, res);
13790        } finally {
13791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13792        }
13793    }
13794
13795    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13796        final int installFlags = args.installFlags;
13797        final String installerPackageName = args.installerPackageName;
13798        final String volumeUuid = args.volumeUuid;
13799        final File tmpPackageFile = new File(args.getCodePath());
13800        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13801        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13802                || (args.volumeUuid != null));
13803        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13804        boolean replace = false;
13805        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13806        if (args.move != null) {
13807            // moving a complete application; perform an initial scan on the new install location
13808            scanFlags |= SCAN_INITIAL;
13809        }
13810        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
13811            scanFlags |= SCAN_DONT_KILL_APP;
13812        }
13813
13814        // Result object to be returned
13815        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13816
13817        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13818
13819        // Sanity check
13820        if (ephemeral && (forwardLocked || onExternal)) {
13821            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13822                    + " external=" + onExternal);
13823            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13824            return;
13825        }
13826
13827        // Retrieve PackageSettings and parse package
13828        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13829                | PackageParser.PARSE_ENFORCE_CODE
13830                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13831                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13832                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13833        PackageParser pp = new PackageParser();
13834        pp.setSeparateProcesses(mSeparateProcesses);
13835        pp.setDisplayMetrics(mMetrics);
13836
13837        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13838        final PackageParser.Package pkg;
13839        try {
13840            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13841        } catch (PackageParserException e) {
13842            res.setError("Failed parse during installPackageLI", e);
13843            return;
13844        } finally {
13845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13846        }
13847
13848        // If we are installing a clustered package add results for the children
13849        if (pkg.childPackages != null) {
13850            synchronized (mPackages) {
13851                final int childCount = pkg.childPackages.size();
13852                for (int i = 0; i < childCount; i++) {
13853                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13854                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13855                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13856                    childRes.pkg = childPkg;
13857                    childRes.name = childPkg.packageName;
13858                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13859                    if (childPs != null) {
13860                        childRes.origUsers = childPs.queryInstalledUsers(
13861                                sUserManager.getUserIds(), true);
13862                    }
13863                    if ((mPackages.containsKey(childPkg.packageName))) {
13864                        childRes.removedInfo = new PackageRemovedInfo();
13865                        childRes.removedInfo.removedPackage = childPkg.packageName;
13866                    }
13867                    if (res.addedChildPackages == null) {
13868                        res.addedChildPackages = new ArrayMap<>();
13869                    }
13870                    res.addedChildPackages.put(childPkg.packageName, childRes);
13871                }
13872            }
13873        }
13874
13875        // If package doesn't declare API override, mark that we have an install
13876        // time CPU ABI override.
13877        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13878            pkg.cpuAbiOverride = args.abiOverride;
13879        }
13880
13881        String pkgName = res.name = pkg.packageName;
13882        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13883            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13884                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13885                return;
13886            }
13887        }
13888
13889        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13890        try {
13891            PackageParser.collectCertificates(pkg, parseFlags);
13892        } catch (PackageParserException e) {
13893            res.setError("Failed collect during installPackageLI", e);
13894            return;
13895        } finally {
13896            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13897        }
13898
13899        // Get rid of all references to package scan path via parser.
13900        pp = null;
13901        String oldCodePath = null;
13902        boolean systemApp = false;
13903        synchronized (mPackages) {
13904            // Check if installing already existing package
13905            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13906                String oldName = mSettings.mRenamedPackages.get(pkgName);
13907                if (pkg.mOriginalPackages != null
13908                        && pkg.mOriginalPackages.contains(oldName)
13909                        && mPackages.containsKey(oldName)) {
13910                    // This package is derived from an original package,
13911                    // and this device has been updating from that original
13912                    // name.  We must continue using the original name, so
13913                    // rename the new package here.
13914                    pkg.setPackageName(oldName);
13915                    pkgName = pkg.packageName;
13916                    replace = true;
13917                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13918                            + oldName + " pkgName=" + pkgName);
13919                } else if (mPackages.containsKey(pkgName)) {
13920                    // This package, under its official name, already exists
13921                    // on the device; we should replace it.
13922                    replace = true;
13923                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13924                }
13925
13926                // Child packages are installed through the parent package
13927                if (pkg.parentPackage != null) {
13928                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13929                            "Package " + pkg.packageName + " is child of package "
13930                                    + pkg.parentPackage.parentPackage + ". Child packages "
13931                                    + "can be updated only through the parent package.");
13932                    return;
13933                }
13934
13935                if (replace) {
13936                    // Prevent apps opting out from runtime permissions
13937                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13938                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13939                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13940                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13941                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13942                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13943                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13944                                        + " doesn't support runtime permissions but the old"
13945                                        + " target SDK " + oldTargetSdk + " does.");
13946                        return;
13947                    }
13948
13949                    // Prevent installing of child packages
13950                    if (oldPackage.parentPackage != null) {
13951                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13952                                "Package " + pkg.packageName + " is child of package "
13953                                        + oldPackage.parentPackage + ". Child packages "
13954                                        + "can be updated only through the parent package.");
13955                        return;
13956                    }
13957                }
13958            }
13959
13960            PackageSetting ps = mSettings.mPackages.get(pkgName);
13961            if (ps != null) {
13962                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13963
13964                // Quick sanity check that we're signed correctly if updating;
13965                // we'll check this again later when scanning, but we want to
13966                // bail early here before tripping over redefined permissions.
13967                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13968                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13969                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13970                                + pkg.packageName + " upgrade keys do not match the "
13971                                + "previously installed version");
13972                        return;
13973                    }
13974                } else {
13975                    try {
13976                        verifySignaturesLP(ps, pkg);
13977                    } catch (PackageManagerException e) {
13978                        res.setError(e.error, e.getMessage());
13979                        return;
13980                    }
13981                }
13982
13983                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13984                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13985                    systemApp = (ps.pkg.applicationInfo.flags &
13986                            ApplicationInfo.FLAG_SYSTEM) != 0;
13987                }
13988                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13989            }
13990
13991            // Check whether the newly-scanned package wants to define an already-defined perm
13992            int N = pkg.permissions.size();
13993            for (int i = N-1; i >= 0; i--) {
13994                PackageParser.Permission perm = pkg.permissions.get(i);
13995                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13996                if (bp != null) {
13997                    // If the defining package is signed with our cert, it's okay.  This
13998                    // also includes the "updating the same package" case, of course.
13999                    // "updating same package" could also involve key-rotation.
14000                    final boolean sigsOk;
14001                    if (bp.sourcePackage.equals(pkg.packageName)
14002                            && (bp.packageSetting instanceof PackageSetting)
14003                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14004                                    scanFlags))) {
14005                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14006                    } else {
14007                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14008                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14009                    }
14010                    if (!sigsOk) {
14011                        // If the owning package is the system itself, we log but allow
14012                        // install to proceed; we fail the install on all other permission
14013                        // redefinitions.
14014                        if (!bp.sourcePackage.equals("android")) {
14015                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14016                                    + pkg.packageName + " attempting to redeclare permission "
14017                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14018                            res.origPermission = perm.info.name;
14019                            res.origPackage = bp.sourcePackage;
14020                            return;
14021                        } else {
14022                            Slog.w(TAG, "Package " + pkg.packageName
14023                                    + " attempting to redeclare system permission "
14024                                    + perm.info.name + "; ignoring new declaration");
14025                            pkg.permissions.remove(i);
14026                        }
14027                    }
14028                }
14029            }
14030        }
14031
14032        if (systemApp) {
14033            if (onExternal) {
14034                // Abort update; system app can't be replaced with app on sdcard
14035                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14036                        "Cannot install updates to system apps on sdcard");
14037                return;
14038            } else if (ephemeral) {
14039                // Abort update; system app can't be replaced with an ephemeral app
14040                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14041                        "Cannot update a system app with an ephemeral app");
14042                return;
14043            }
14044        }
14045
14046        if (args.move != null) {
14047            // We did an in-place move, so dex is ready to roll
14048            scanFlags |= SCAN_NO_DEX;
14049            scanFlags |= SCAN_MOVE;
14050
14051            synchronized (mPackages) {
14052                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14053                if (ps == null) {
14054                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14055                            "Missing settings for moved package " + pkgName);
14056                }
14057
14058                // We moved the entire application as-is, so bring over the
14059                // previously derived ABI information.
14060                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14061                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14062            }
14063
14064        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14065            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14066            scanFlags |= SCAN_NO_DEX;
14067
14068            try {
14069                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14070                    args.abiOverride : pkg.cpuAbiOverride);
14071                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14072                        true /* extract libs */);
14073            } catch (PackageManagerException pme) {
14074                Slog.e(TAG, "Error deriving application ABI", pme);
14075                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14076                return;
14077            }
14078
14079
14080            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14081            // Do not run PackageDexOptimizer through the local performDexOpt
14082            // method because `pkg` is not in `mPackages` yet.
14083            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14084                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14085            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14086            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14087                String msg = "Extracking package failed for " + pkgName;
14088                res.setError(INSTALL_FAILED_DEXOPT, msg);
14089                return;
14090            }
14091        }
14092
14093        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14094            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14095            return;
14096        }
14097
14098        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14099
14100        if (replace) {
14101            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14102                    installerPackageName, res);
14103        } else {
14104            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14105                    args.user, installerPackageName, volumeUuid, res);
14106        }
14107        synchronized (mPackages) {
14108            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14109            if (ps != null) {
14110                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14111            }
14112
14113            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14114            for (int i = 0; i < childCount; i++) {
14115                PackageParser.Package childPkg = pkg.childPackages.get(i);
14116                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14117                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14118                if (childPs != null) {
14119                    childRes.newUsers = childPs.queryInstalledUsers(
14120                            sUserManager.getUserIds(), true);
14121                }
14122            }
14123        }
14124    }
14125
14126    private void startIntentFilterVerifications(int userId, boolean replacing,
14127            PackageParser.Package pkg) {
14128        if (mIntentFilterVerifierComponent == null) {
14129            Slog.w(TAG, "No IntentFilter verification will not be done as "
14130                    + "there is no IntentFilterVerifier available!");
14131            return;
14132        }
14133
14134        final int verifierUid = getPackageUid(
14135                mIntentFilterVerifierComponent.getPackageName(),
14136                MATCH_DEBUG_TRIAGED_MISSING,
14137                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14138
14139        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14140        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14141        mHandler.sendMessage(msg);
14142
14143        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14144        for (int i = 0; i < childCount; i++) {
14145            PackageParser.Package childPkg = pkg.childPackages.get(i);
14146            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14147            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14148            mHandler.sendMessage(msg);
14149        }
14150    }
14151
14152    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14153            PackageParser.Package pkg) {
14154        int size = pkg.activities.size();
14155        if (size == 0) {
14156            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14157                    "No activity, so no need to verify any IntentFilter!");
14158            return;
14159        }
14160
14161        final boolean hasDomainURLs = hasDomainURLs(pkg);
14162        if (!hasDomainURLs) {
14163            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14164                    "No domain URLs, so no need to verify any IntentFilter!");
14165            return;
14166        }
14167
14168        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14169                + " if any IntentFilter from the " + size
14170                + " Activities needs verification ...");
14171
14172        int count = 0;
14173        final String packageName = pkg.packageName;
14174
14175        synchronized (mPackages) {
14176            // If this is a new install and we see that we've already run verification for this
14177            // package, we have nothing to do: it means the state was restored from backup.
14178            if (!replacing) {
14179                IntentFilterVerificationInfo ivi =
14180                        mSettings.getIntentFilterVerificationLPr(packageName);
14181                if (ivi != null) {
14182                    if (DEBUG_DOMAIN_VERIFICATION) {
14183                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14184                                + ivi.getStatusString());
14185                    }
14186                    return;
14187                }
14188            }
14189
14190            // If any filters need to be verified, then all need to be.
14191            boolean needToVerify = false;
14192            for (PackageParser.Activity a : pkg.activities) {
14193                for (ActivityIntentInfo filter : a.intents) {
14194                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14195                        if (DEBUG_DOMAIN_VERIFICATION) {
14196                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14197                        }
14198                        needToVerify = true;
14199                        break;
14200                    }
14201                }
14202            }
14203
14204            if (needToVerify) {
14205                final int verificationId = mIntentFilterVerificationToken++;
14206                for (PackageParser.Activity a : pkg.activities) {
14207                    for (ActivityIntentInfo filter : a.intents) {
14208                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14209                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14210                                    "Verification needed for IntentFilter:" + filter.toString());
14211                            mIntentFilterVerifier.addOneIntentFilterVerification(
14212                                    verifierUid, userId, verificationId, filter, packageName);
14213                            count++;
14214                        }
14215                    }
14216                }
14217            }
14218        }
14219
14220        if (count > 0) {
14221            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14222                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14223                    +  " for userId:" + userId);
14224            mIntentFilterVerifier.startVerifications(userId);
14225        } else {
14226            if (DEBUG_DOMAIN_VERIFICATION) {
14227                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14228            }
14229        }
14230    }
14231
14232    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14233        final ComponentName cn  = filter.activity.getComponentName();
14234        final String packageName = cn.getPackageName();
14235
14236        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14237                packageName);
14238        if (ivi == null) {
14239            return true;
14240        }
14241        int status = ivi.getStatus();
14242        switch (status) {
14243            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14244            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14245                return true;
14246
14247            default:
14248                // Nothing to do
14249                return false;
14250        }
14251    }
14252
14253    private static boolean isMultiArch(ApplicationInfo info) {
14254        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14255    }
14256
14257    private static boolean isExternal(PackageParser.Package pkg) {
14258        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14259    }
14260
14261    private static boolean isExternal(PackageSetting ps) {
14262        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14263    }
14264
14265    private static boolean isEphemeral(PackageParser.Package pkg) {
14266        return pkg.applicationInfo.isEphemeralApp();
14267    }
14268
14269    private static boolean isEphemeral(PackageSetting ps) {
14270        return ps.pkg != null && isEphemeral(ps.pkg);
14271    }
14272
14273    private static boolean isSystemApp(PackageParser.Package pkg) {
14274        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14275    }
14276
14277    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14278        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14279    }
14280
14281    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14282        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14283    }
14284
14285    private static boolean isSystemApp(PackageSetting ps) {
14286        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14287    }
14288
14289    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14290        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14291    }
14292
14293    private int packageFlagsToInstallFlags(PackageSetting ps) {
14294        int installFlags = 0;
14295        if (isEphemeral(ps)) {
14296            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14297        }
14298        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14299            // This existing package was an external ASEC install when we have
14300            // the external flag without a UUID
14301            installFlags |= PackageManager.INSTALL_EXTERNAL;
14302        }
14303        if (ps.isForwardLocked()) {
14304            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14305        }
14306        return installFlags;
14307    }
14308
14309    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14310        if (isExternal(pkg)) {
14311            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14312                return StorageManager.UUID_PRIMARY_PHYSICAL;
14313            } else {
14314                return pkg.volumeUuid;
14315            }
14316        } else {
14317            return StorageManager.UUID_PRIVATE_INTERNAL;
14318        }
14319    }
14320
14321    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14322        if (isExternal(pkg)) {
14323            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14324                return mSettings.getExternalVersion();
14325            } else {
14326                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14327            }
14328        } else {
14329            return mSettings.getInternalVersion();
14330        }
14331    }
14332
14333    private void deleteTempPackageFiles() {
14334        final FilenameFilter filter = new FilenameFilter() {
14335            public boolean accept(File dir, String name) {
14336                return name.startsWith("vmdl") && name.endsWith(".tmp");
14337            }
14338        };
14339        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14340            file.delete();
14341        }
14342    }
14343
14344    @Override
14345    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14346            int flags) {
14347        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14348                flags);
14349    }
14350
14351    @Override
14352    public void deletePackage(final String packageName,
14353            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14354        mContext.enforceCallingOrSelfPermission(
14355                android.Manifest.permission.DELETE_PACKAGES, null);
14356        Preconditions.checkNotNull(packageName);
14357        Preconditions.checkNotNull(observer);
14358        final int uid = Binder.getCallingUid();
14359        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14360        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14361        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14362            mContext.enforceCallingOrSelfPermission(
14363                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14364                    "deletePackage for user " + userId);
14365        }
14366
14367        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14368            try {
14369                observer.onPackageDeleted(packageName,
14370                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14371            } catch (RemoteException re) {
14372            }
14373            return;
14374        }
14375
14376        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14377            try {
14378                observer.onPackageDeleted(packageName,
14379                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14380            } catch (RemoteException re) {
14381            }
14382            return;
14383        }
14384
14385        if (DEBUG_REMOVE) {
14386            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14387                    + " deleteAllUsers: " + deleteAllUsers );
14388        }
14389        // Queue up an async operation since the package deletion may take a little while.
14390        mHandler.post(new Runnable() {
14391            public void run() {
14392                mHandler.removeCallbacks(this);
14393                int returnCode;
14394                if (!deleteAllUsers) {
14395                    returnCode = deletePackageX(packageName, userId, flags);
14396                } else {
14397                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14398                    // If nobody is blocking uninstall, proceed with delete for all users
14399                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14400                        returnCode = deletePackageX(packageName, userId, flags);
14401                    } else {
14402                        // Otherwise uninstall individually for users with blockUninstalls=false
14403                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14404                        for (int userId : users) {
14405                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14406                                returnCode = deletePackageX(packageName, userId, userFlags);
14407                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14408                                    Slog.w(TAG, "Package delete failed for user " + userId
14409                                            + ", returnCode " + returnCode);
14410                                }
14411                            }
14412                        }
14413                        // The app has only been marked uninstalled for certain users.
14414                        // We still need to report that delete was blocked
14415                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14416                    }
14417                }
14418                try {
14419                    observer.onPackageDeleted(packageName, returnCode, null);
14420                } catch (RemoteException e) {
14421                    Log.i(TAG, "Observer no longer exists.");
14422                } //end catch
14423            } //end run
14424        });
14425    }
14426
14427    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14428        int[] result = EMPTY_INT_ARRAY;
14429        for (int userId : userIds) {
14430            if (getBlockUninstallForUser(packageName, userId)) {
14431                result = ArrayUtils.appendInt(result, userId);
14432            }
14433        }
14434        return result;
14435    }
14436
14437    @Override
14438    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14439        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14440    }
14441
14442    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14443        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14444                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14445        try {
14446            if (dpm != null) {
14447                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14448                        /* callingUserOnly =*/ false);
14449                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14450                        : deviceOwnerComponentName.getPackageName();
14451                // Does the package contains the device owner?
14452                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14453                // this check is probably not needed, since DO should be registered as a device
14454                // admin on some user too. (Original bug for this: b/17657954)
14455                if (packageName.equals(deviceOwnerPackageName)) {
14456                    return true;
14457                }
14458                // Does it contain a device admin for any user?
14459                int[] users;
14460                if (userId == UserHandle.USER_ALL) {
14461                    users = sUserManager.getUserIds();
14462                } else {
14463                    users = new int[]{userId};
14464                }
14465                for (int i = 0; i < users.length; ++i) {
14466                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14467                        return true;
14468                    }
14469                }
14470            }
14471        } catch (RemoteException e) {
14472        }
14473        return false;
14474    }
14475
14476    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14477        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14478    }
14479
14480    /**
14481     *  This method is an internal method that could be get invoked either
14482     *  to delete an installed package or to clean up a failed installation.
14483     *  After deleting an installed package, a broadcast is sent to notify any
14484     *  listeners that the package has been installed. For cleaning up a failed
14485     *  installation, the broadcast is not necessary since the package's
14486     *  installation wouldn't have sent the initial broadcast either
14487     *  The key steps in deleting a package are
14488     *  deleting the package information in internal structures like mPackages,
14489     *  deleting the packages base directories through installd
14490     *  updating mSettings to reflect current status
14491     *  persisting settings for later use
14492     *  sending a broadcast if necessary
14493     */
14494    private int deletePackageX(String packageName, int userId, int flags) {
14495        final PackageRemovedInfo info = new PackageRemovedInfo();
14496        final boolean res;
14497
14498        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14499                ? UserHandle.ALL : new UserHandle(userId);
14500
14501        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14502            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14503            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14504        }
14505
14506        PackageSetting uninstalledPs = null;
14507
14508        // for the uninstall-updates case and restricted profiles, remember the per-
14509        // user handle installed state
14510        int[] allUsers;
14511        synchronized (mPackages) {
14512            uninstalledPs = mSettings.mPackages.get(packageName);
14513            if (uninstalledPs == null) {
14514                Slog.w(TAG, "Not removing non-existent package " + packageName);
14515                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14516            }
14517            allUsers = sUserManager.getUserIds();
14518            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14519        }
14520
14521        synchronized (mInstallLock) {
14522            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14523            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14524                    flags | REMOVE_CHATTY, info, true, null);
14525            deleteProfilesLI(packageName, /*destroy*/ true);
14526            synchronized (mPackages) {
14527                if (res) {
14528                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14529                }
14530            }
14531        }
14532
14533        if (res) {
14534            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14535            info.sendPackageRemovedBroadcasts(killApp);
14536            info.sendSystemPackageUpdatedBroadcasts();
14537            info.sendSystemPackageAppearedBroadcasts();
14538        }
14539        // Force a gc here.
14540        Runtime.getRuntime().gc();
14541        // Delete the resources here after sending the broadcast to let
14542        // other processes clean up before deleting resources.
14543        if (info.args != null) {
14544            synchronized (mInstallLock) {
14545                info.args.doPostDeleteLI(true);
14546            }
14547        }
14548
14549        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14550    }
14551
14552    class PackageRemovedInfo {
14553        String removedPackage;
14554        int uid = -1;
14555        int removedAppId = -1;
14556        int[] origUsers;
14557        int[] removedUsers = null;
14558        boolean isRemovedPackageSystemUpdate = false;
14559        boolean isUpdate;
14560        boolean dataRemoved;
14561        boolean removedForAllUsers;
14562        // Clean up resources deleted packages.
14563        InstallArgs args = null;
14564        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14565        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14566
14567        void sendPackageRemovedBroadcasts(boolean killApp) {
14568            sendPackageRemovedBroadcastInternal(killApp);
14569            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14570            for (int i = 0; i < childCount; i++) {
14571                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14572                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14573            }
14574        }
14575
14576        void sendSystemPackageUpdatedBroadcasts() {
14577            if (isRemovedPackageSystemUpdate) {
14578                sendSystemPackageUpdatedBroadcastsInternal();
14579                final int childCount = (removedChildPackages != null)
14580                        ? removedChildPackages.size() : 0;
14581                for (int i = 0; i < childCount; i++) {
14582                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14583                    if (childInfo.isRemovedPackageSystemUpdate) {
14584                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14585                    }
14586                }
14587            }
14588        }
14589
14590        void sendSystemPackageAppearedBroadcasts() {
14591            final int packageCount = (appearedChildPackages != null)
14592                    ? appearedChildPackages.size() : 0;
14593            for (int i = 0; i < packageCount; i++) {
14594                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14595                for (int userId : installedInfo.newUsers) {
14596                    sendPackageAddedForUser(installedInfo.name, true,
14597                            UserHandle.getAppId(installedInfo.uid), userId);
14598                }
14599            }
14600        }
14601
14602        private void sendSystemPackageUpdatedBroadcastsInternal() {
14603            Bundle extras = new Bundle(2);
14604            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14605            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14606            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14607                    extras, 0, null, null, null);
14608            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14609                    extras, 0, null, null, null);
14610            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14611                    null, 0, removedPackage, null, null);
14612        }
14613
14614        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14615            Bundle extras = new Bundle(2);
14616            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14617            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14618            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14619            if (isUpdate || isRemovedPackageSystemUpdate) {
14620                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14621            }
14622            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14623            if (removedPackage != null) {
14624                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14625                        extras, 0, null, null, removedUsers);
14626                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14627                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14628                            removedPackage, extras, 0, null, null, removedUsers);
14629                }
14630            }
14631            if (removedAppId >= 0) {
14632                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14633                        removedUsers);
14634            }
14635        }
14636    }
14637
14638    /*
14639     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14640     * flag is not set, the data directory is removed as well.
14641     * make sure this flag is set for partially installed apps. If not its meaningless to
14642     * delete a partially installed application.
14643     */
14644    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14645            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14646        String packageName = ps.name;
14647        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14648        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14649        // Retrieve object to delete permissions for shared user later on
14650        final PackageSetting deletedPs;
14651        // reader
14652        synchronized (mPackages) {
14653            deletedPs = mSettings.mPackages.get(packageName);
14654            if (outInfo != null) {
14655                outInfo.removedPackage = packageName;
14656                outInfo.removedUsers = deletedPs != null
14657                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14658                        : null;
14659            }
14660        }
14661        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14662            removeDataDirsLI(ps.volumeUuid, packageName);
14663            if (outInfo != null) {
14664                outInfo.dataRemoved = true;
14665            }
14666            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14667        }
14668        // writer
14669        synchronized (mPackages) {
14670            if (deletedPs != null) {
14671                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14672                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14673                    clearDefaultBrowserIfNeeded(packageName);
14674                    if (outInfo != null) {
14675                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14676                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14677                    }
14678                    updatePermissionsLPw(deletedPs.name, null, 0);
14679                    if (deletedPs.sharedUser != null) {
14680                        // Remove permissions associated with package. Since runtime
14681                        // permissions are per user we have to kill the removed package
14682                        // or packages running under the shared user of the removed
14683                        // package if revoking the permissions requested only by the removed
14684                        // package is successful and this causes a change in gids.
14685                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14686                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14687                                    userId);
14688                            if (userIdToKill == UserHandle.USER_ALL
14689                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14690                                // If gids changed for this user, kill all affected packages.
14691                                mHandler.post(new Runnable() {
14692                                    @Override
14693                                    public void run() {
14694                                        // This has to happen with no lock held.
14695                                        killApplication(deletedPs.name, deletedPs.appId,
14696                                                KILL_APP_REASON_GIDS_CHANGED);
14697                                    }
14698                                });
14699                                break;
14700                            }
14701                        }
14702                    }
14703                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14704                }
14705                // make sure to preserve per-user disabled state if this removal was just
14706                // a downgrade of a system app to the factory package
14707                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14708                    if (DEBUG_REMOVE) {
14709                        Slog.d(TAG, "Propagating install state across downgrade");
14710                    }
14711                    for (int userId : allUserHandles) {
14712                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14713                        if (DEBUG_REMOVE) {
14714                            Slog.d(TAG, "    user " + userId + " => " + installed);
14715                        }
14716                        ps.setInstalled(installed, userId);
14717                    }
14718                }
14719            }
14720            // can downgrade to reader
14721            if (writeSettings) {
14722                // Save settings now
14723                mSettings.writeLPr();
14724            }
14725        }
14726        if (outInfo != null) {
14727            // A user ID was deleted here. Go through all users and remove it
14728            // from KeyStore.
14729            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14730        }
14731    }
14732
14733    static boolean locationIsPrivileged(File path) {
14734        try {
14735            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14736                    .getCanonicalPath();
14737            return path.getCanonicalPath().startsWith(privilegedAppDir);
14738        } catch (IOException e) {
14739            Slog.e(TAG, "Unable to access code path " + path);
14740        }
14741        return false;
14742    }
14743
14744    /*
14745     * Tries to delete system package.
14746     */
14747    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14748            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14749            boolean writeSettings) {
14750        if (deletedPs.parentPackageName != null) {
14751            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14752            return false;
14753        }
14754
14755        final boolean applyUserRestrictions
14756                = (allUserHandles != null) && (outInfo.origUsers != null);
14757        final PackageSetting disabledPs;
14758        // Confirm if the system package has been updated
14759        // An updated system app can be deleted. This will also have to restore
14760        // the system pkg from system partition
14761        // reader
14762        synchronized (mPackages) {
14763            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14764        }
14765
14766        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14767                + " disabledPs=" + disabledPs);
14768
14769        if (disabledPs == null) {
14770            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14771            return false;
14772        } else if (DEBUG_REMOVE) {
14773            Slog.d(TAG, "Deleting system pkg from data partition");
14774        }
14775
14776        if (DEBUG_REMOVE) {
14777            if (applyUserRestrictions) {
14778                Slog.d(TAG, "Remembering install states:");
14779                for (int userId : allUserHandles) {
14780                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14781                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14782                }
14783            }
14784        }
14785
14786        // Delete the updated package
14787        outInfo.isRemovedPackageSystemUpdate = true;
14788        if (outInfo.removedChildPackages != null) {
14789            final int childCount = (deletedPs.childPackageNames != null)
14790                    ? deletedPs.childPackageNames.size() : 0;
14791            for (int i = 0; i < childCount; i++) {
14792                String childPackageName = deletedPs.childPackageNames.get(i);
14793                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14794                        .contains(childPackageName)) {
14795                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14796                            childPackageName);
14797                    if (childInfo != null) {
14798                        childInfo.isRemovedPackageSystemUpdate = true;
14799                    }
14800                }
14801            }
14802        }
14803
14804        if (disabledPs.versionCode < deletedPs.versionCode) {
14805            // Delete data for downgrades
14806            flags &= ~PackageManager.DELETE_KEEP_DATA;
14807        } else {
14808            // Preserve data by setting flag
14809            flags |= PackageManager.DELETE_KEEP_DATA;
14810        }
14811
14812        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14813                outInfo, writeSettings, disabledPs.pkg);
14814        if (!ret) {
14815            return false;
14816        }
14817
14818        // writer
14819        synchronized (mPackages) {
14820            // Reinstate the old system package
14821            enableSystemPackageLPw(disabledPs.pkg);
14822            // Remove any native libraries from the upgraded package.
14823            removeNativeBinariesLI(deletedPs);
14824        }
14825
14826        // Install the system package
14827        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14828        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14829        if (locationIsPrivileged(disabledPs.codePath)) {
14830            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14831        }
14832
14833        final PackageParser.Package newPkg;
14834        try {
14835            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14836        } catch (PackageManagerException e) {
14837            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14838                    + e.getMessage());
14839            return false;
14840        }
14841
14842        prepareAppDataAfterInstall(newPkg);
14843
14844        // writer
14845        synchronized (mPackages) {
14846            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14847
14848            // Propagate the permissions state as we do not want to drop on the floor
14849            // runtime permissions. The update permissions method below will take
14850            // care of removing obsolete permissions and grant install permissions.
14851            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14852            updatePermissionsLPw(newPkg.packageName, newPkg,
14853                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14854
14855            if (applyUserRestrictions) {
14856                if (DEBUG_REMOVE) {
14857                    Slog.d(TAG, "Propagating install state across reinstall");
14858                }
14859                for (int userId : allUserHandles) {
14860                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14861                    if (DEBUG_REMOVE) {
14862                        Slog.d(TAG, "    user " + userId + " => " + installed);
14863                    }
14864                    ps.setInstalled(installed, userId);
14865
14866                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14867                }
14868                // Regardless of writeSettings we need to ensure that this restriction
14869                // state propagation is persisted
14870                mSettings.writeAllUsersPackageRestrictionsLPr();
14871            }
14872            // can downgrade to reader here
14873            if (writeSettings) {
14874                mSettings.writeLPr();
14875            }
14876        }
14877        return true;
14878    }
14879
14880    private boolean deleteInstalledPackageLI(PackageSetting ps,
14881            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14882            PackageRemovedInfo outInfo, boolean writeSettings,
14883            PackageParser.Package replacingPackage) {
14884        synchronized (mPackages) {
14885            if (outInfo != null) {
14886                outInfo.uid = ps.appId;
14887            }
14888
14889            if (outInfo != null && outInfo.removedChildPackages != null) {
14890                final int childCount = (ps.childPackageNames != null)
14891                        ? ps.childPackageNames.size() : 0;
14892                for (int i = 0; i < childCount; i++) {
14893                    String childPackageName = ps.childPackageNames.get(i);
14894                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14895                    if (childPs == null) {
14896                        return false;
14897                    }
14898                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14899                            childPackageName);
14900                    if (childInfo != null) {
14901                        childInfo.uid = childPs.appId;
14902                    }
14903                }
14904            }
14905        }
14906
14907        // Delete package data from internal structures and also remove data if flag is set
14908        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14909
14910        // Delete the child packages data
14911        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14912        for (int i = 0; i < childCount; i++) {
14913            PackageSetting childPs;
14914            synchronized (mPackages) {
14915                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14916            }
14917            if (childPs != null) {
14918                PackageRemovedInfo childOutInfo = (outInfo != null
14919                        && outInfo.removedChildPackages != null)
14920                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14921                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14922                        && (replacingPackage != null
14923                        && !replacingPackage.hasChildPackage(childPs.name))
14924                        ? flags & ~DELETE_KEEP_DATA : flags;
14925                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14926                        deleteFlags, writeSettings);
14927            }
14928        }
14929
14930        // Delete application code and resources only for parent packages
14931        if (ps.parentPackageName == null) {
14932            if (deleteCodeAndResources && (outInfo != null)) {
14933                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14934                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14935                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14936            }
14937        }
14938
14939        return true;
14940    }
14941
14942    @Override
14943    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14944            int userId) {
14945        mContext.enforceCallingOrSelfPermission(
14946                android.Manifest.permission.DELETE_PACKAGES, null);
14947        synchronized (mPackages) {
14948            PackageSetting ps = mSettings.mPackages.get(packageName);
14949            if (ps == null) {
14950                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14951                return false;
14952            }
14953            if (!ps.getInstalled(userId)) {
14954                // Can't block uninstall for an app that is not installed or enabled.
14955                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14956                return false;
14957            }
14958            ps.setBlockUninstall(blockUninstall, userId);
14959            mSettings.writePackageRestrictionsLPr(userId);
14960        }
14961        return true;
14962    }
14963
14964    @Override
14965    public boolean getBlockUninstallForUser(String packageName, int userId) {
14966        synchronized (mPackages) {
14967            PackageSetting ps = mSettings.mPackages.get(packageName);
14968            if (ps == null) {
14969                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14970                return false;
14971            }
14972            return ps.getBlockUninstall(userId);
14973        }
14974    }
14975
14976    @Override
14977    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14978        int callingUid = Binder.getCallingUid();
14979        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14980            throw new SecurityException(
14981                    "setRequiredForSystemUser can only be run by the system or root");
14982        }
14983        synchronized (mPackages) {
14984            PackageSetting ps = mSettings.mPackages.get(packageName);
14985            if (ps == null) {
14986                Log.w(TAG, "Package doesn't exist: " + packageName);
14987                return false;
14988            }
14989            if (systemUserApp) {
14990                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14991            } else {
14992                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14993            }
14994            mSettings.writeLPr();
14995        }
14996        return true;
14997    }
14998
14999    /*
15000     * This method handles package deletion in general
15001     */
15002    private boolean deletePackageLI(String packageName, UserHandle user,
15003            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15004            PackageRemovedInfo outInfo, boolean writeSettings,
15005            PackageParser.Package replacingPackage) {
15006        if (packageName == null) {
15007            Slog.w(TAG, "Attempt to delete null packageName.");
15008            return false;
15009        }
15010
15011        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15012
15013        PackageSetting ps;
15014
15015        synchronized (mPackages) {
15016            ps = mSettings.mPackages.get(packageName);
15017            if (ps == null) {
15018                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15019                return false;
15020            }
15021
15022            if (ps.parentPackageName != null && (!isSystemApp(ps)
15023                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15024                if (DEBUG_REMOVE) {
15025                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15026                            + ((user == null) ? UserHandle.USER_ALL : user));
15027                }
15028                final int removedUserId = (user != null) ? user.getIdentifier()
15029                        : UserHandle.USER_ALL;
15030                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
15031                    return false;
15032                }
15033                markPackageUninstalledForUserLPw(ps, user);
15034                scheduleWritePackageRestrictionsLocked(user);
15035                return true;
15036            }
15037        }
15038
15039        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15040                && user.getIdentifier() != UserHandle.USER_ALL)) {
15041            // The caller is asking that the package only be deleted for a single
15042            // user.  To do this, we just mark its uninstalled state and delete
15043            // its data. If this is a system app, we only allow this to happen if
15044            // they have set the special DELETE_SYSTEM_APP which requests different
15045            // semantics than normal for uninstalling system apps.
15046            markPackageUninstalledForUserLPw(ps, user);
15047
15048            if (!isSystemApp(ps)) {
15049                // Do not uninstall the APK if an app should be cached
15050                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15051                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15052                    // Other user still have this package installed, so all
15053                    // we need to do is clear this user's data and save that
15054                    // it is uninstalled.
15055                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15056                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15057                        return false;
15058                    }
15059                    scheduleWritePackageRestrictionsLocked(user);
15060                    return true;
15061                } else {
15062                    // We need to set it back to 'installed' so the uninstall
15063                    // broadcasts will be sent correctly.
15064                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15065                    ps.setInstalled(true, user.getIdentifier());
15066                }
15067            } else {
15068                // This is a system app, so we assume that the
15069                // other users still have this package installed, so all
15070                // we need to do is clear this user's data and save that
15071                // it is uninstalled.
15072                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15073                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15074                    return false;
15075                }
15076                scheduleWritePackageRestrictionsLocked(user);
15077                return true;
15078            }
15079        }
15080
15081        // If we are deleting a composite package for all users, keep track
15082        // of result for each child.
15083        if (ps.childPackageNames != null && outInfo != null) {
15084            synchronized (mPackages) {
15085                final int childCount = ps.childPackageNames.size();
15086                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15087                for (int i = 0; i < childCount; i++) {
15088                    String childPackageName = ps.childPackageNames.get(i);
15089                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15090                    childInfo.removedPackage = childPackageName;
15091                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15092                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15093                    if (childPs != null) {
15094                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15095                    }
15096                }
15097            }
15098        }
15099
15100        boolean ret = false;
15101        if (isSystemApp(ps)) {
15102            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15103            // When an updated system application is deleted we delete the existing resources
15104            // as well and fall back to existing code in system partition
15105            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15106        } else {
15107            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15108            // Kill application pre-emptively especially for apps on sd.
15109            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15110            if (killApp) {
15111                killApplication(packageName, ps.appId, "uninstall pkg");
15112            }
15113            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15114                    outInfo, writeSettings, replacingPackage);
15115        }
15116
15117        // Take a note whether we deleted the package for all users
15118        if (outInfo != null) {
15119            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15120            if (outInfo.removedChildPackages != null) {
15121                synchronized (mPackages) {
15122                    final int childCount = outInfo.removedChildPackages.size();
15123                    for (int i = 0; i < childCount; i++) {
15124                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15125                        if (childInfo != null) {
15126                            childInfo.removedForAllUsers = mPackages.get(
15127                                    childInfo.removedPackage) == null;
15128                        }
15129                    }
15130                }
15131            }
15132            // If we uninstalled an update to a system app there may be some
15133            // child packages that appeared as they are declared in the system
15134            // app but were not declared in the update.
15135            if (isSystemApp(ps)) {
15136                synchronized (mPackages) {
15137                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15138                    final int childCount = (updatedPs.childPackageNames != null)
15139                            ? updatedPs.childPackageNames.size() : 0;
15140                    for (int i = 0; i < childCount; i++) {
15141                        String childPackageName = updatedPs.childPackageNames.get(i);
15142                        if (outInfo.removedChildPackages == null
15143                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15144                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15145                            if (childPs == null) {
15146                                continue;
15147                            }
15148                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15149                            installRes.name = childPackageName;
15150                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15151                            installRes.pkg = mPackages.get(childPackageName);
15152                            installRes.uid = childPs.pkg.applicationInfo.uid;
15153                            if (outInfo.appearedChildPackages == null) {
15154                                outInfo.appearedChildPackages = new ArrayMap<>();
15155                            }
15156                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15157                        }
15158                    }
15159                }
15160            }
15161        }
15162
15163        return ret;
15164    }
15165
15166    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15167        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15168                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15169        for (int nextUserId : userIds) {
15170            if (DEBUG_REMOVE) {
15171                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15172            }
15173            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15174                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15175                    false /*hidden*/, false /*suspended*/, null, null, null,
15176                    false /*blockUninstall*/,
15177                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15178        }
15179    }
15180
15181    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15182            PackageRemovedInfo outInfo) {
15183        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15184                : new int[] {userId};
15185        for (int nextUserId : userIds) {
15186            if (DEBUG_REMOVE) {
15187                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15188                        + nextUserId);
15189            }
15190            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15191            try {
15192                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15193            } catch (InstallerException e) {
15194                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15195                return false;
15196            }
15197            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15198            schedulePackageCleaning(ps.name, nextUserId, false);
15199            synchronized (mPackages) {
15200                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15201                    scheduleWritePackageRestrictionsLocked(nextUserId);
15202                }
15203                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15204            }
15205        }
15206
15207        if (outInfo != null) {
15208            outInfo.removedPackage = ps.name;
15209            outInfo.removedAppId = ps.appId;
15210            outInfo.removedUsers = userIds;
15211        }
15212
15213        return true;
15214    }
15215
15216    private final class ClearStorageConnection implements ServiceConnection {
15217        IMediaContainerService mContainerService;
15218
15219        @Override
15220        public void onServiceConnected(ComponentName name, IBinder service) {
15221            synchronized (this) {
15222                mContainerService = IMediaContainerService.Stub.asInterface(service);
15223                notifyAll();
15224            }
15225        }
15226
15227        @Override
15228        public void onServiceDisconnected(ComponentName name) {
15229        }
15230    }
15231
15232    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15233        final boolean mounted;
15234        if (Environment.isExternalStorageEmulated()) {
15235            mounted = true;
15236        } else {
15237            final String status = Environment.getExternalStorageState();
15238
15239            mounted = status.equals(Environment.MEDIA_MOUNTED)
15240                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15241        }
15242
15243        if (!mounted) {
15244            return;
15245        }
15246
15247        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15248        int[] users;
15249        if (userId == UserHandle.USER_ALL) {
15250            users = sUserManager.getUserIds();
15251        } else {
15252            users = new int[] { userId };
15253        }
15254        final ClearStorageConnection conn = new ClearStorageConnection();
15255        if (mContext.bindServiceAsUser(
15256                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15257            try {
15258                for (int curUser : users) {
15259                    long timeout = SystemClock.uptimeMillis() + 5000;
15260                    synchronized (conn) {
15261                        long now = SystemClock.uptimeMillis();
15262                        while (conn.mContainerService == null && now < timeout) {
15263                            try {
15264                                conn.wait(timeout - now);
15265                            } catch (InterruptedException e) {
15266                            }
15267                        }
15268                    }
15269                    if (conn.mContainerService == null) {
15270                        return;
15271                    }
15272
15273                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15274                    clearDirectory(conn.mContainerService,
15275                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15276                    if (allData) {
15277                        clearDirectory(conn.mContainerService,
15278                                userEnv.buildExternalStorageAppDataDirs(packageName));
15279                        clearDirectory(conn.mContainerService,
15280                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15281                    }
15282                }
15283            } finally {
15284                mContext.unbindService(conn);
15285            }
15286        }
15287    }
15288
15289    @Override
15290    public void clearApplicationProfileData(String packageName) {
15291        enforceSystemOrRoot("Only the system can clear all profile data");
15292        try {
15293            mInstaller.clearAppProfiles(packageName);
15294        } catch (InstallerException ex) {
15295            Log.e(TAG, "Could not clear profile data of package " + packageName);
15296        }
15297    }
15298
15299    @Override
15300    public void clearApplicationUserData(final String packageName,
15301            final IPackageDataObserver observer, final int userId) {
15302        mContext.enforceCallingOrSelfPermission(
15303                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15304
15305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15306                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15307
15308        final DevicePolicyManagerInternal dpmi = LocalServices
15309                .getService(DevicePolicyManagerInternal.class);
15310        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15311            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15312        }
15313        // Queue up an async operation since the package deletion may take a little while.
15314        mHandler.post(new Runnable() {
15315            public void run() {
15316                mHandler.removeCallbacks(this);
15317                final boolean succeeded;
15318                synchronized (mInstallLock) {
15319                    succeeded = clearApplicationUserDataLI(packageName, userId);
15320                }
15321                clearExternalStorageDataSync(packageName, userId, true);
15322                if (succeeded) {
15323                    // invoke DeviceStorageMonitor's update method to clear any notifications
15324                    DeviceStorageMonitorInternal dsm = LocalServices
15325                            .getService(DeviceStorageMonitorInternal.class);
15326                    if (dsm != null) {
15327                        dsm.checkMemory();
15328                    }
15329                }
15330                if(observer != null) {
15331                    try {
15332                        observer.onRemoveCompleted(packageName, succeeded);
15333                    } catch (RemoteException e) {
15334                        Log.i(TAG, "Observer no longer exists.");
15335                    }
15336                } //end if observer
15337            } //end run
15338        });
15339    }
15340
15341    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15342        if (packageName == null) {
15343            Slog.w(TAG, "Attempt to delete null packageName.");
15344            return false;
15345        }
15346
15347        // Try finding details about the requested package
15348        PackageParser.Package pkg;
15349        synchronized (mPackages) {
15350            pkg = mPackages.get(packageName);
15351            if (pkg == null) {
15352                final PackageSetting ps = mSettings.mPackages.get(packageName);
15353                if (ps != null) {
15354                    pkg = ps.pkg;
15355                }
15356            }
15357
15358            if (pkg == null) {
15359                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15360                return false;
15361            }
15362
15363            PackageSetting ps = (PackageSetting) pkg.mExtras;
15364            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15365        }
15366
15367        // Always delete data directories for package, even if we found no other
15368        // record of app. This helps users recover from UID mismatches without
15369        // resorting to a full data wipe.
15370        // TODO: triage flags as part of 26466827
15371        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15372        try {
15373            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15374        } catch (InstallerException e) {
15375            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15376            return false;
15377        }
15378
15379        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15380        removeKeystoreDataIfNeeded(userId, appId);
15381
15382        // Create a native library symlink only if we have native libraries
15383        // and if the native libraries are 32 bit libraries. We do not provide
15384        // this symlink for 64 bit libraries.
15385        if (pkg.applicationInfo.primaryCpuAbi != null &&
15386                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15387            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15388            try {
15389                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15390                        nativeLibPath, userId);
15391            } catch (InstallerException e) {
15392                Slog.w(TAG, "Failed linking native library dir", e);
15393                return false;
15394            }
15395        }
15396
15397        return true;
15398    }
15399
15400    /**
15401     * Reverts user permission state changes (permissions and flags) in
15402     * all packages for a given user.
15403     *
15404     * @param userId The device user for which to do a reset.
15405     */
15406    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15407        final int packageCount = mPackages.size();
15408        for (int i = 0; i < packageCount; i++) {
15409            PackageParser.Package pkg = mPackages.valueAt(i);
15410            PackageSetting ps = (PackageSetting) pkg.mExtras;
15411            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15412        }
15413    }
15414
15415    /**
15416     * Reverts user permission state changes (permissions and flags).
15417     *
15418     * @param ps The package for which to reset.
15419     * @param userId The device user for which to do a reset.
15420     */
15421    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15422            final PackageSetting ps, final int userId) {
15423        if (ps.pkg == null) {
15424            return;
15425        }
15426
15427        // These are flags that can change base on user actions.
15428        final int userSettableMask = FLAG_PERMISSION_USER_SET
15429                | FLAG_PERMISSION_USER_FIXED
15430                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15431                | FLAG_PERMISSION_REVIEW_REQUIRED;
15432
15433        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15434                | FLAG_PERMISSION_POLICY_FIXED;
15435
15436        boolean writeInstallPermissions = false;
15437        boolean writeRuntimePermissions = false;
15438
15439        final int permissionCount = ps.pkg.requestedPermissions.size();
15440        for (int i = 0; i < permissionCount; i++) {
15441            String permission = ps.pkg.requestedPermissions.get(i);
15442
15443            BasePermission bp = mSettings.mPermissions.get(permission);
15444            if (bp == null) {
15445                continue;
15446            }
15447
15448            // If shared user we just reset the state to which only this app contributed.
15449            if (ps.sharedUser != null) {
15450                boolean used = false;
15451                final int packageCount = ps.sharedUser.packages.size();
15452                for (int j = 0; j < packageCount; j++) {
15453                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15454                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15455                            && pkg.pkg.requestedPermissions.contains(permission)) {
15456                        used = true;
15457                        break;
15458                    }
15459                }
15460                if (used) {
15461                    continue;
15462                }
15463            }
15464
15465            PermissionsState permissionsState = ps.getPermissionsState();
15466
15467            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15468
15469            // Always clear the user settable flags.
15470            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15471                    bp.name) != null;
15472            // If permission review is enabled and this is a legacy app, mark the
15473            // permission as requiring a review as this is the initial state.
15474            int flags = 0;
15475            if (Build.PERMISSIONS_REVIEW_REQUIRED
15476                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15477                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15478            }
15479            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15480                if (hasInstallState) {
15481                    writeInstallPermissions = true;
15482                } else {
15483                    writeRuntimePermissions = true;
15484                }
15485            }
15486
15487            // Below is only runtime permission handling.
15488            if (!bp.isRuntime()) {
15489                continue;
15490            }
15491
15492            // Never clobber system or policy.
15493            if ((oldFlags & policyOrSystemFlags) != 0) {
15494                continue;
15495            }
15496
15497            // If this permission was granted by default, make sure it is.
15498            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15499                if (permissionsState.grantRuntimePermission(bp, userId)
15500                        != PERMISSION_OPERATION_FAILURE) {
15501                    writeRuntimePermissions = true;
15502                }
15503            // If permission review is enabled the permissions for a legacy apps
15504            // are represented as constantly granted runtime ones, so don't revoke.
15505            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15506                // Otherwise, reset the permission.
15507                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15508                switch (revokeResult) {
15509                    case PERMISSION_OPERATION_SUCCESS: {
15510                        writeRuntimePermissions = true;
15511                    } break;
15512
15513                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15514                        writeRuntimePermissions = true;
15515                        final int appId = ps.appId;
15516                        mHandler.post(new Runnable() {
15517                            @Override
15518                            public void run() {
15519                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15520                            }
15521                        });
15522                    } break;
15523                }
15524            }
15525        }
15526
15527        // Synchronously write as we are taking permissions away.
15528        if (writeRuntimePermissions) {
15529            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15530        }
15531
15532        // Synchronously write as we are taking permissions away.
15533        if (writeInstallPermissions) {
15534            mSettings.writeLPr();
15535        }
15536    }
15537
15538    /**
15539     * Remove entries from the keystore daemon. Will only remove it if the
15540     * {@code appId} is valid.
15541     */
15542    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15543        if (appId < 0) {
15544            return;
15545        }
15546
15547        final KeyStore keyStore = KeyStore.getInstance();
15548        if (keyStore != null) {
15549            if (userId == UserHandle.USER_ALL) {
15550                for (final int individual : sUserManager.getUserIds()) {
15551                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15552                }
15553            } else {
15554                keyStore.clearUid(UserHandle.getUid(userId, appId));
15555            }
15556        } else {
15557            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15558        }
15559    }
15560
15561    @Override
15562    public void deleteApplicationCacheFiles(final String packageName,
15563            final IPackageDataObserver observer) {
15564        mContext.enforceCallingOrSelfPermission(
15565                android.Manifest.permission.DELETE_CACHE_FILES, null);
15566        // Queue up an async operation since the package deletion may take a little while.
15567        final int userId = UserHandle.getCallingUserId();
15568        mHandler.post(new Runnable() {
15569            public void run() {
15570                mHandler.removeCallbacks(this);
15571                final boolean succeded;
15572                synchronized (mInstallLock) {
15573                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15574                }
15575                clearExternalStorageDataSync(packageName, userId, false);
15576                if (observer != null) {
15577                    try {
15578                        observer.onRemoveCompleted(packageName, succeded);
15579                    } catch (RemoteException e) {
15580                        Log.i(TAG, "Observer no longer exists.");
15581                    }
15582                } //end if observer
15583            } //end run
15584        });
15585    }
15586
15587    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15588        if (packageName == null) {
15589            Slog.w(TAG, "Attempt to delete null packageName.");
15590            return false;
15591        }
15592        PackageParser.Package p;
15593        synchronized (mPackages) {
15594            p = mPackages.get(packageName);
15595        }
15596        if (p == null) {
15597            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15598            return false;
15599        }
15600        final ApplicationInfo applicationInfo = p.applicationInfo;
15601        if (applicationInfo == null) {
15602            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15603            return false;
15604        }
15605        // TODO: triage flags as part of 26466827
15606        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15607        try {
15608            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15609                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15610        } catch (InstallerException e) {
15611            Slog.w(TAG, "Couldn't remove cache files for package "
15612                    + packageName + " u" + userId, e);
15613            return false;
15614        }
15615        return true;
15616    }
15617
15618    @Override
15619    public void getPackageSizeInfo(final String packageName, int userHandle,
15620            final IPackageStatsObserver observer) {
15621        mContext.enforceCallingOrSelfPermission(
15622                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15623        if (packageName == null) {
15624            throw new IllegalArgumentException("Attempt to get size of null packageName");
15625        }
15626
15627        PackageStats stats = new PackageStats(packageName, userHandle);
15628
15629        /*
15630         * Queue up an async operation since the package measurement may take a
15631         * little while.
15632         */
15633        Message msg = mHandler.obtainMessage(INIT_COPY);
15634        msg.obj = new MeasureParams(stats, observer);
15635        mHandler.sendMessage(msg);
15636    }
15637
15638    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15639            PackageStats pStats) {
15640        if (packageName == null) {
15641            Slog.w(TAG, "Attempt to get size of null packageName.");
15642            return false;
15643        }
15644        PackageParser.Package p;
15645        boolean dataOnly = false;
15646        String libDirRoot = null;
15647        String asecPath = null;
15648        PackageSetting ps = null;
15649        synchronized (mPackages) {
15650            p = mPackages.get(packageName);
15651            ps = mSettings.mPackages.get(packageName);
15652            if(p == null) {
15653                dataOnly = true;
15654                if((ps == null) || (ps.pkg == null)) {
15655                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15656                    return false;
15657                }
15658                p = ps.pkg;
15659            }
15660            if (ps != null) {
15661                libDirRoot = ps.legacyNativeLibraryPathString;
15662            }
15663            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15664                final long token = Binder.clearCallingIdentity();
15665                try {
15666                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15667                    if (secureContainerId != null) {
15668                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15669                    }
15670                } finally {
15671                    Binder.restoreCallingIdentity(token);
15672                }
15673            }
15674        }
15675        String publicSrcDir = null;
15676        if(!dataOnly) {
15677            final ApplicationInfo applicationInfo = p.applicationInfo;
15678            if (applicationInfo == null) {
15679                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15680                return false;
15681            }
15682            if (p.isForwardLocked()) {
15683                publicSrcDir = applicationInfo.getBaseResourcePath();
15684            }
15685        }
15686        // TODO: extend to measure size of split APKs
15687        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15688        // not just the first level.
15689        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15690        // just the primary.
15691        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15692
15693        String apkPath;
15694        File packageDir = new File(p.codePath);
15695
15696        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15697            apkPath = packageDir.getAbsolutePath();
15698            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15699            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15700                libDirRoot = null;
15701            }
15702        } else {
15703            apkPath = p.baseCodePath;
15704        }
15705
15706        // TODO: triage flags as part of 26466827
15707        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15708        try {
15709            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15710                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15711        } catch (InstallerException e) {
15712            return false;
15713        }
15714
15715        // Fix-up for forward-locked applications in ASEC containers.
15716        if (!isExternal(p)) {
15717            pStats.codeSize += pStats.externalCodeSize;
15718            pStats.externalCodeSize = 0L;
15719        }
15720
15721        return true;
15722    }
15723
15724    private int getUidTargetSdkVersionLockedLPr(int uid) {
15725        Object obj = mSettings.getUserIdLPr(uid);
15726        if (obj instanceof SharedUserSetting) {
15727            final SharedUserSetting sus = (SharedUserSetting) obj;
15728            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15729            final Iterator<PackageSetting> it = sus.packages.iterator();
15730            while (it.hasNext()) {
15731                final PackageSetting ps = it.next();
15732                if (ps.pkg != null) {
15733                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15734                    if (v < vers) vers = v;
15735                }
15736            }
15737            return vers;
15738        } else if (obj instanceof PackageSetting) {
15739            final PackageSetting ps = (PackageSetting) obj;
15740            if (ps.pkg != null) {
15741                return ps.pkg.applicationInfo.targetSdkVersion;
15742            }
15743        }
15744        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15745    }
15746
15747    @Override
15748    public void addPreferredActivity(IntentFilter filter, int match,
15749            ComponentName[] set, ComponentName activity, int userId) {
15750        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15751                "Adding preferred");
15752    }
15753
15754    private void addPreferredActivityInternal(IntentFilter filter, int match,
15755            ComponentName[] set, ComponentName activity, boolean always, int userId,
15756            String opname) {
15757        // writer
15758        int callingUid = Binder.getCallingUid();
15759        enforceCrossUserPermission(callingUid, userId,
15760                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15761        if (filter.countActions() == 0) {
15762            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15763            return;
15764        }
15765        synchronized (mPackages) {
15766            if (mContext.checkCallingOrSelfPermission(
15767                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15768                    != PackageManager.PERMISSION_GRANTED) {
15769                if (getUidTargetSdkVersionLockedLPr(callingUid)
15770                        < Build.VERSION_CODES.FROYO) {
15771                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15772                            + callingUid);
15773                    return;
15774                }
15775                mContext.enforceCallingOrSelfPermission(
15776                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15777            }
15778
15779            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15780            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15781                    + userId + ":");
15782            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15783            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15784            scheduleWritePackageRestrictionsLocked(userId);
15785        }
15786    }
15787
15788    @Override
15789    public void replacePreferredActivity(IntentFilter filter, int match,
15790            ComponentName[] set, ComponentName activity, int userId) {
15791        if (filter.countActions() != 1) {
15792            throw new IllegalArgumentException(
15793                    "replacePreferredActivity expects filter to have only 1 action.");
15794        }
15795        if (filter.countDataAuthorities() != 0
15796                || filter.countDataPaths() != 0
15797                || filter.countDataSchemes() > 1
15798                || filter.countDataTypes() != 0) {
15799            throw new IllegalArgumentException(
15800                    "replacePreferredActivity expects filter to have no data authorities, " +
15801                    "paths, or types; and at most one scheme.");
15802        }
15803
15804        final int callingUid = Binder.getCallingUid();
15805        enforceCrossUserPermission(callingUid, userId,
15806                true /* requireFullPermission */, false /* checkShell */,
15807                "replace preferred activity");
15808        synchronized (mPackages) {
15809            if (mContext.checkCallingOrSelfPermission(
15810                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15811                    != PackageManager.PERMISSION_GRANTED) {
15812                if (getUidTargetSdkVersionLockedLPr(callingUid)
15813                        < Build.VERSION_CODES.FROYO) {
15814                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15815                            + Binder.getCallingUid());
15816                    return;
15817                }
15818                mContext.enforceCallingOrSelfPermission(
15819                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15820            }
15821
15822            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15823            if (pir != null) {
15824                // Get all of the existing entries that exactly match this filter.
15825                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15826                if (existing != null && existing.size() == 1) {
15827                    PreferredActivity cur = existing.get(0);
15828                    if (DEBUG_PREFERRED) {
15829                        Slog.i(TAG, "Checking replace of preferred:");
15830                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15831                        if (!cur.mPref.mAlways) {
15832                            Slog.i(TAG, "  -- CUR; not mAlways!");
15833                        } else {
15834                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15835                            Slog.i(TAG, "  -- CUR: mSet="
15836                                    + Arrays.toString(cur.mPref.mSetComponents));
15837                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15838                            Slog.i(TAG, "  -- NEW: mMatch="
15839                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15840                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15841                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15842                        }
15843                    }
15844                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15845                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15846                            && cur.mPref.sameSet(set)) {
15847                        // Setting the preferred activity to what it happens to be already
15848                        if (DEBUG_PREFERRED) {
15849                            Slog.i(TAG, "Replacing with same preferred activity "
15850                                    + cur.mPref.mShortComponent + " for user "
15851                                    + userId + ":");
15852                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15853                        }
15854                        return;
15855                    }
15856                }
15857
15858                if (existing != null) {
15859                    if (DEBUG_PREFERRED) {
15860                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15861                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15862                    }
15863                    for (int i = 0; i < existing.size(); i++) {
15864                        PreferredActivity pa = existing.get(i);
15865                        if (DEBUG_PREFERRED) {
15866                            Slog.i(TAG, "Removing existing preferred activity "
15867                                    + pa.mPref.mComponent + ":");
15868                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15869                        }
15870                        pir.removeFilter(pa);
15871                    }
15872                }
15873            }
15874            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15875                    "Replacing preferred");
15876        }
15877    }
15878
15879    @Override
15880    public void clearPackagePreferredActivities(String packageName) {
15881        final int uid = Binder.getCallingUid();
15882        // writer
15883        synchronized (mPackages) {
15884            PackageParser.Package pkg = mPackages.get(packageName);
15885            if (pkg == null || pkg.applicationInfo.uid != uid) {
15886                if (mContext.checkCallingOrSelfPermission(
15887                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15888                        != PackageManager.PERMISSION_GRANTED) {
15889                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15890                            < Build.VERSION_CODES.FROYO) {
15891                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15892                                + Binder.getCallingUid());
15893                        return;
15894                    }
15895                    mContext.enforceCallingOrSelfPermission(
15896                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15897                }
15898            }
15899
15900            int user = UserHandle.getCallingUserId();
15901            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15902                scheduleWritePackageRestrictionsLocked(user);
15903            }
15904        }
15905    }
15906
15907    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15908    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15909        ArrayList<PreferredActivity> removed = null;
15910        boolean changed = false;
15911        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15912            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15913            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15914            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15915                continue;
15916            }
15917            Iterator<PreferredActivity> it = pir.filterIterator();
15918            while (it.hasNext()) {
15919                PreferredActivity pa = it.next();
15920                // Mark entry for removal only if it matches the package name
15921                // and the entry is of type "always".
15922                if (packageName == null ||
15923                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15924                                && pa.mPref.mAlways)) {
15925                    if (removed == null) {
15926                        removed = new ArrayList<PreferredActivity>();
15927                    }
15928                    removed.add(pa);
15929                }
15930            }
15931            if (removed != null) {
15932                for (int j=0; j<removed.size(); j++) {
15933                    PreferredActivity pa = removed.get(j);
15934                    pir.removeFilter(pa);
15935                }
15936                changed = true;
15937            }
15938        }
15939        return changed;
15940    }
15941
15942    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15943    private void clearIntentFilterVerificationsLPw(int userId) {
15944        final int packageCount = mPackages.size();
15945        for (int i = 0; i < packageCount; i++) {
15946            PackageParser.Package pkg = mPackages.valueAt(i);
15947            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15948        }
15949    }
15950
15951    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15952    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15953        if (userId == UserHandle.USER_ALL) {
15954            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15955                    sUserManager.getUserIds())) {
15956                for (int oneUserId : sUserManager.getUserIds()) {
15957                    scheduleWritePackageRestrictionsLocked(oneUserId);
15958                }
15959            }
15960        } else {
15961            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15962                scheduleWritePackageRestrictionsLocked(userId);
15963            }
15964        }
15965    }
15966
15967    void clearDefaultBrowserIfNeeded(String packageName) {
15968        for (int oneUserId : sUserManager.getUserIds()) {
15969            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15970            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15971            if (packageName.equals(defaultBrowserPackageName)) {
15972                setDefaultBrowserPackageName(null, oneUserId);
15973            }
15974        }
15975    }
15976
15977    @Override
15978    public void resetApplicationPreferences(int userId) {
15979        mContext.enforceCallingOrSelfPermission(
15980                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15981        // writer
15982        synchronized (mPackages) {
15983            final long identity = Binder.clearCallingIdentity();
15984            try {
15985                clearPackagePreferredActivitiesLPw(null, userId);
15986                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15987                // TODO: We have to reset the default SMS and Phone. This requires
15988                // significant refactoring to keep all default apps in the package
15989                // manager (cleaner but more work) or have the services provide
15990                // callbacks to the package manager to request a default app reset.
15991                applyFactoryDefaultBrowserLPw(userId);
15992                clearIntentFilterVerificationsLPw(userId);
15993                primeDomainVerificationsLPw(userId);
15994                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15995                scheduleWritePackageRestrictionsLocked(userId);
15996            } finally {
15997                Binder.restoreCallingIdentity(identity);
15998            }
15999        }
16000    }
16001
16002    @Override
16003    public int getPreferredActivities(List<IntentFilter> outFilters,
16004            List<ComponentName> outActivities, String packageName) {
16005
16006        int num = 0;
16007        final int userId = UserHandle.getCallingUserId();
16008        // reader
16009        synchronized (mPackages) {
16010            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16011            if (pir != null) {
16012                final Iterator<PreferredActivity> it = pir.filterIterator();
16013                while (it.hasNext()) {
16014                    final PreferredActivity pa = it.next();
16015                    if (packageName == null
16016                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16017                                    && pa.mPref.mAlways)) {
16018                        if (outFilters != null) {
16019                            outFilters.add(new IntentFilter(pa));
16020                        }
16021                        if (outActivities != null) {
16022                            outActivities.add(pa.mPref.mComponent);
16023                        }
16024                    }
16025                }
16026            }
16027        }
16028
16029        return num;
16030    }
16031
16032    @Override
16033    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16034            int userId) {
16035        int callingUid = Binder.getCallingUid();
16036        if (callingUid != Process.SYSTEM_UID) {
16037            throw new SecurityException(
16038                    "addPersistentPreferredActivity can only be run by the system");
16039        }
16040        if (filter.countActions() == 0) {
16041            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16042            return;
16043        }
16044        synchronized (mPackages) {
16045            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16046                    ":");
16047            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16048            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16049                    new PersistentPreferredActivity(filter, activity));
16050            scheduleWritePackageRestrictionsLocked(userId);
16051        }
16052    }
16053
16054    @Override
16055    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16056        int callingUid = Binder.getCallingUid();
16057        if (callingUid != Process.SYSTEM_UID) {
16058            throw new SecurityException(
16059                    "clearPackagePersistentPreferredActivities can only be run by the system");
16060        }
16061        ArrayList<PersistentPreferredActivity> removed = null;
16062        boolean changed = false;
16063        synchronized (mPackages) {
16064            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16065                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16066                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16067                        .valueAt(i);
16068                if (userId != thisUserId) {
16069                    continue;
16070                }
16071                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16072                while (it.hasNext()) {
16073                    PersistentPreferredActivity ppa = it.next();
16074                    // Mark entry for removal only if it matches the package name.
16075                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16076                        if (removed == null) {
16077                            removed = new ArrayList<PersistentPreferredActivity>();
16078                        }
16079                        removed.add(ppa);
16080                    }
16081                }
16082                if (removed != null) {
16083                    for (int j=0; j<removed.size(); j++) {
16084                        PersistentPreferredActivity ppa = removed.get(j);
16085                        ppir.removeFilter(ppa);
16086                    }
16087                    changed = true;
16088                }
16089            }
16090
16091            if (changed) {
16092                scheduleWritePackageRestrictionsLocked(userId);
16093            }
16094        }
16095    }
16096
16097    /**
16098     * Common machinery for picking apart a restored XML blob and passing
16099     * it to a caller-supplied functor to be applied to the running system.
16100     */
16101    private void restoreFromXml(XmlPullParser parser, int userId,
16102            String expectedStartTag, BlobXmlRestorer functor)
16103            throws IOException, XmlPullParserException {
16104        int type;
16105        while ((type = parser.next()) != XmlPullParser.START_TAG
16106                && type != XmlPullParser.END_DOCUMENT) {
16107        }
16108        if (type != XmlPullParser.START_TAG) {
16109            // oops didn't find a start tag?!
16110            if (DEBUG_BACKUP) {
16111                Slog.e(TAG, "Didn't find start tag during restore");
16112            }
16113            return;
16114        }
16115Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16116        // this is supposed to be TAG_PREFERRED_BACKUP
16117        if (!expectedStartTag.equals(parser.getName())) {
16118            if (DEBUG_BACKUP) {
16119                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16120            }
16121            return;
16122        }
16123
16124        // skip interfering stuff, then we're aligned with the backing implementation
16125        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16126Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16127        functor.apply(parser, userId);
16128    }
16129
16130    private interface BlobXmlRestorer {
16131        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16132    }
16133
16134    /**
16135     * Non-Binder method, support for the backup/restore mechanism: write the
16136     * full set of preferred activities in its canonical XML format.  Returns the
16137     * XML output as a byte array, or null if there is none.
16138     */
16139    @Override
16140    public byte[] getPreferredActivityBackup(int userId) {
16141        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16142            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16143        }
16144
16145        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16146        try {
16147            final XmlSerializer serializer = new FastXmlSerializer();
16148            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16149            serializer.startDocument(null, true);
16150            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16151
16152            synchronized (mPackages) {
16153                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16154            }
16155
16156            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16157            serializer.endDocument();
16158            serializer.flush();
16159        } catch (Exception e) {
16160            if (DEBUG_BACKUP) {
16161                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16162            }
16163            return null;
16164        }
16165
16166        return dataStream.toByteArray();
16167    }
16168
16169    @Override
16170    public void restorePreferredActivities(byte[] backup, int userId) {
16171        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16172            throw new SecurityException("Only the system may call restorePreferredActivities()");
16173        }
16174
16175        try {
16176            final XmlPullParser parser = Xml.newPullParser();
16177            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16178            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16179                    new BlobXmlRestorer() {
16180                        @Override
16181                        public void apply(XmlPullParser parser, int userId)
16182                                throws XmlPullParserException, IOException {
16183                            synchronized (mPackages) {
16184                                mSettings.readPreferredActivitiesLPw(parser, userId);
16185                            }
16186                        }
16187                    } );
16188        } catch (Exception e) {
16189            if (DEBUG_BACKUP) {
16190                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16191            }
16192        }
16193    }
16194
16195    /**
16196     * Non-Binder method, support for the backup/restore mechanism: write the
16197     * default browser (etc) settings in its canonical XML format.  Returns the default
16198     * browser XML representation as a byte array, or null if there is none.
16199     */
16200    @Override
16201    public byte[] getDefaultAppsBackup(int userId) {
16202        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16203            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16204        }
16205
16206        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16207        try {
16208            final XmlSerializer serializer = new FastXmlSerializer();
16209            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16210            serializer.startDocument(null, true);
16211            serializer.startTag(null, TAG_DEFAULT_APPS);
16212
16213            synchronized (mPackages) {
16214                mSettings.writeDefaultAppsLPr(serializer, userId);
16215            }
16216
16217            serializer.endTag(null, TAG_DEFAULT_APPS);
16218            serializer.endDocument();
16219            serializer.flush();
16220        } catch (Exception e) {
16221            if (DEBUG_BACKUP) {
16222                Slog.e(TAG, "Unable to write default apps for backup", e);
16223            }
16224            return null;
16225        }
16226
16227        return dataStream.toByteArray();
16228    }
16229
16230    @Override
16231    public void restoreDefaultApps(byte[] backup, int userId) {
16232        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16233            throw new SecurityException("Only the system may call restoreDefaultApps()");
16234        }
16235
16236        try {
16237            final XmlPullParser parser = Xml.newPullParser();
16238            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16239            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16240                    new BlobXmlRestorer() {
16241                        @Override
16242                        public void apply(XmlPullParser parser, int userId)
16243                                throws XmlPullParserException, IOException {
16244                            synchronized (mPackages) {
16245                                mSettings.readDefaultAppsLPw(parser, userId);
16246                            }
16247                        }
16248                    } );
16249        } catch (Exception e) {
16250            if (DEBUG_BACKUP) {
16251                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16252            }
16253        }
16254    }
16255
16256    @Override
16257    public byte[] getIntentFilterVerificationBackup(int userId) {
16258        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16259            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16260        }
16261
16262        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16263        try {
16264            final XmlSerializer serializer = new FastXmlSerializer();
16265            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16266            serializer.startDocument(null, true);
16267            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16268
16269            synchronized (mPackages) {
16270                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16271            }
16272
16273            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16274            serializer.endDocument();
16275            serializer.flush();
16276        } catch (Exception e) {
16277            if (DEBUG_BACKUP) {
16278                Slog.e(TAG, "Unable to write default apps for backup", e);
16279            }
16280            return null;
16281        }
16282
16283        return dataStream.toByteArray();
16284    }
16285
16286    @Override
16287    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16288        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16289            throw new SecurityException("Only the system may call restorePreferredActivities()");
16290        }
16291
16292        try {
16293            final XmlPullParser parser = Xml.newPullParser();
16294            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16295            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16296                    new BlobXmlRestorer() {
16297                        @Override
16298                        public void apply(XmlPullParser parser, int userId)
16299                                throws XmlPullParserException, IOException {
16300                            synchronized (mPackages) {
16301                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16302                                mSettings.writeLPr();
16303                            }
16304                        }
16305                    } );
16306        } catch (Exception e) {
16307            if (DEBUG_BACKUP) {
16308                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16309            }
16310        }
16311    }
16312
16313    @Override
16314    public byte[] getPermissionGrantBackup(int userId) {
16315        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16316            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16317        }
16318
16319        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16320        try {
16321            final XmlSerializer serializer = new FastXmlSerializer();
16322            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16323            serializer.startDocument(null, true);
16324            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16325
16326            synchronized (mPackages) {
16327                serializeRuntimePermissionGrantsLPr(serializer, userId);
16328            }
16329
16330            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16331            serializer.endDocument();
16332            serializer.flush();
16333        } catch (Exception e) {
16334            if (DEBUG_BACKUP) {
16335                Slog.e(TAG, "Unable to write default apps for backup", e);
16336            }
16337            return null;
16338        }
16339
16340        return dataStream.toByteArray();
16341    }
16342
16343    @Override
16344    public void restorePermissionGrants(byte[] backup, int userId) {
16345        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16346            throw new SecurityException("Only the system may call restorePermissionGrants()");
16347        }
16348
16349        try {
16350            final XmlPullParser parser = Xml.newPullParser();
16351            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16352            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16353                    new BlobXmlRestorer() {
16354                        @Override
16355                        public void apply(XmlPullParser parser, int userId)
16356                                throws XmlPullParserException, IOException {
16357                            synchronized (mPackages) {
16358                                processRestoredPermissionGrantsLPr(parser, userId);
16359                            }
16360                        }
16361                    } );
16362        } catch (Exception e) {
16363            if (DEBUG_BACKUP) {
16364                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16365            }
16366        }
16367    }
16368
16369    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16370            throws IOException {
16371        serializer.startTag(null, TAG_ALL_GRANTS);
16372
16373        final int N = mSettings.mPackages.size();
16374        for (int i = 0; i < N; i++) {
16375            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16376            boolean pkgGrantsKnown = false;
16377
16378            PermissionsState packagePerms = ps.getPermissionsState();
16379
16380            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16381                final int grantFlags = state.getFlags();
16382                // only look at grants that are not system/policy fixed
16383                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16384                    final boolean isGranted = state.isGranted();
16385                    // And only back up the user-twiddled state bits
16386                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16387                        final String packageName = mSettings.mPackages.keyAt(i);
16388                        if (!pkgGrantsKnown) {
16389                            serializer.startTag(null, TAG_GRANT);
16390                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16391                            pkgGrantsKnown = true;
16392                        }
16393
16394                        final boolean userSet =
16395                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16396                        final boolean userFixed =
16397                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16398                        final boolean revoke =
16399                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16400
16401                        serializer.startTag(null, TAG_PERMISSION);
16402                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16403                        if (isGranted) {
16404                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16405                        }
16406                        if (userSet) {
16407                            serializer.attribute(null, ATTR_USER_SET, "true");
16408                        }
16409                        if (userFixed) {
16410                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16411                        }
16412                        if (revoke) {
16413                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16414                        }
16415                        serializer.endTag(null, TAG_PERMISSION);
16416                    }
16417                }
16418            }
16419
16420            if (pkgGrantsKnown) {
16421                serializer.endTag(null, TAG_GRANT);
16422            }
16423        }
16424
16425        serializer.endTag(null, TAG_ALL_GRANTS);
16426    }
16427
16428    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16429            throws XmlPullParserException, IOException {
16430        String pkgName = null;
16431        int outerDepth = parser.getDepth();
16432        int type;
16433        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16434                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16435            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16436                continue;
16437            }
16438
16439            final String tagName = parser.getName();
16440            if (tagName.equals(TAG_GRANT)) {
16441                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16442                if (DEBUG_BACKUP) {
16443                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16444                }
16445            } else if (tagName.equals(TAG_PERMISSION)) {
16446
16447                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16448                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16449
16450                int newFlagSet = 0;
16451                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16452                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16453                }
16454                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16455                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16456                }
16457                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16458                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16459                }
16460                if (DEBUG_BACKUP) {
16461                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16462                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16463                }
16464                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16465                if (ps != null) {
16466                    // Already installed so we apply the grant immediately
16467                    if (DEBUG_BACKUP) {
16468                        Slog.v(TAG, "        + already installed; applying");
16469                    }
16470                    PermissionsState perms = ps.getPermissionsState();
16471                    BasePermission bp = mSettings.mPermissions.get(permName);
16472                    if (bp != null) {
16473                        if (isGranted) {
16474                            perms.grantRuntimePermission(bp, userId);
16475                        }
16476                        if (newFlagSet != 0) {
16477                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16478                        }
16479                    }
16480                } else {
16481                    // Need to wait for post-restore install to apply the grant
16482                    if (DEBUG_BACKUP) {
16483                        Slog.v(TAG, "        - not yet installed; saving for later");
16484                    }
16485                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16486                            isGranted, newFlagSet, userId);
16487                }
16488            } else {
16489                PackageManagerService.reportSettingsProblem(Log.WARN,
16490                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16491                XmlUtils.skipCurrentTag(parser);
16492            }
16493        }
16494
16495        scheduleWriteSettingsLocked();
16496        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16497    }
16498
16499    @Override
16500    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16501            int sourceUserId, int targetUserId, int flags) {
16502        mContext.enforceCallingOrSelfPermission(
16503                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16504        int callingUid = Binder.getCallingUid();
16505        enforceOwnerRights(ownerPackage, callingUid);
16506        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16507        if (intentFilter.countActions() == 0) {
16508            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16509            return;
16510        }
16511        synchronized (mPackages) {
16512            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16513                    ownerPackage, targetUserId, flags);
16514            CrossProfileIntentResolver resolver =
16515                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16516            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16517            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16518            if (existing != null) {
16519                int size = existing.size();
16520                for (int i = 0; i < size; i++) {
16521                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16522                        return;
16523                    }
16524                }
16525            }
16526            resolver.addFilter(newFilter);
16527            scheduleWritePackageRestrictionsLocked(sourceUserId);
16528        }
16529    }
16530
16531    @Override
16532    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16533        mContext.enforceCallingOrSelfPermission(
16534                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16535        int callingUid = Binder.getCallingUid();
16536        enforceOwnerRights(ownerPackage, callingUid);
16537        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16538        synchronized (mPackages) {
16539            CrossProfileIntentResolver resolver =
16540                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16541            ArraySet<CrossProfileIntentFilter> set =
16542                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16543            for (CrossProfileIntentFilter filter : set) {
16544                if (filter.getOwnerPackage().equals(ownerPackage)) {
16545                    resolver.removeFilter(filter);
16546                }
16547            }
16548            scheduleWritePackageRestrictionsLocked(sourceUserId);
16549        }
16550    }
16551
16552    // Enforcing that callingUid is owning pkg on userId
16553    private void enforceOwnerRights(String pkg, int callingUid) {
16554        // The system owns everything.
16555        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16556            return;
16557        }
16558        int callingUserId = UserHandle.getUserId(callingUid);
16559        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16560        if (pi == null) {
16561            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16562                    + callingUserId);
16563        }
16564        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16565            throw new SecurityException("Calling uid " + callingUid
16566                    + " does not own package " + pkg);
16567        }
16568    }
16569
16570    @Override
16571    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16572        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16573    }
16574
16575    private Intent getHomeIntent() {
16576        Intent intent = new Intent(Intent.ACTION_MAIN);
16577        intent.addCategory(Intent.CATEGORY_HOME);
16578        return intent;
16579    }
16580
16581    private IntentFilter getHomeFilter() {
16582        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16583        filter.addCategory(Intent.CATEGORY_HOME);
16584        filter.addCategory(Intent.CATEGORY_DEFAULT);
16585        return filter;
16586    }
16587
16588    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16589            int userId) {
16590        Intent intent  = getHomeIntent();
16591        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16592                PackageManager.GET_META_DATA, userId);
16593        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16594                true, false, false, userId);
16595
16596        allHomeCandidates.clear();
16597        if (list != null) {
16598            for (ResolveInfo ri : list) {
16599                allHomeCandidates.add(ri);
16600            }
16601        }
16602        return (preferred == null || preferred.activityInfo == null)
16603                ? null
16604                : new ComponentName(preferred.activityInfo.packageName,
16605                        preferred.activityInfo.name);
16606    }
16607
16608    @Override
16609    public void setHomeActivity(ComponentName comp, int userId) {
16610        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16611        getHomeActivitiesAsUser(homeActivities, userId);
16612
16613        boolean found = false;
16614
16615        final int size = homeActivities.size();
16616        final ComponentName[] set = new ComponentName[size];
16617        for (int i = 0; i < size; i++) {
16618            final ResolveInfo candidate = homeActivities.get(i);
16619            final ActivityInfo info = candidate.activityInfo;
16620            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16621            set[i] = activityName;
16622            if (!found && activityName.equals(comp)) {
16623                found = true;
16624            }
16625        }
16626        if (!found) {
16627            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16628                    + userId);
16629        }
16630        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16631                set, comp, userId);
16632    }
16633
16634    @Override
16635    public void setApplicationEnabledSetting(String appPackageName,
16636            int newState, int flags, int userId, String callingPackage) {
16637        if (!sUserManager.exists(userId)) return;
16638        if (callingPackage == null) {
16639            callingPackage = Integer.toString(Binder.getCallingUid());
16640        }
16641        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16642    }
16643
16644    @Override
16645    public void setComponentEnabledSetting(ComponentName componentName,
16646            int newState, int flags, int userId) {
16647        if (!sUserManager.exists(userId)) return;
16648        setEnabledSetting(componentName.getPackageName(),
16649                componentName.getClassName(), newState, flags, userId, null);
16650    }
16651
16652    private void setEnabledSetting(final String packageName, String className, int newState,
16653            final int flags, int userId, String callingPackage) {
16654        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16655              || newState == COMPONENT_ENABLED_STATE_ENABLED
16656              || newState == COMPONENT_ENABLED_STATE_DISABLED
16657              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16658              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16659            throw new IllegalArgumentException("Invalid new component state: "
16660                    + newState);
16661        }
16662        PackageSetting pkgSetting;
16663        final int uid = Binder.getCallingUid();
16664        final int permission = mContext.checkCallingOrSelfPermission(
16665                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16666        enforceCrossUserPermission(uid, userId,
16667                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16668        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16669        boolean sendNow = false;
16670        boolean isApp = (className == null);
16671        String componentName = isApp ? packageName : className;
16672        int packageUid = -1;
16673        ArrayList<String> components;
16674
16675        // writer
16676        synchronized (mPackages) {
16677            pkgSetting = mSettings.mPackages.get(packageName);
16678            if (pkgSetting == null) {
16679                if (className == null) {
16680                    throw new IllegalArgumentException("Unknown package: " + packageName);
16681                }
16682                throw new IllegalArgumentException(
16683                        "Unknown component: " + packageName + "/" + className);
16684            }
16685            // Allow root and verify that userId is not being specified by a different user
16686            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16687                throw new SecurityException(
16688                        "Permission Denial: attempt to change component state from pid="
16689                        + Binder.getCallingPid()
16690                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16691            }
16692            if (className == null) {
16693                // We're dealing with an application/package level state change
16694                if (pkgSetting.getEnabled(userId) == newState) {
16695                    // Nothing to do
16696                    return;
16697                }
16698                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16699                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16700                    // Don't care about who enables an app.
16701                    callingPackage = null;
16702                }
16703                pkgSetting.setEnabled(newState, userId, callingPackage);
16704                // pkgSetting.pkg.mSetEnabled = newState;
16705            } else {
16706                // We're dealing with a component level state change
16707                // First, verify that this is a valid class name.
16708                PackageParser.Package pkg = pkgSetting.pkg;
16709                if (pkg == null || !pkg.hasComponentClassName(className)) {
16710                    if (pkg != null &&
16711                            pkg.applicationInfo.targetSdkVersion >=
16712                                    Build.VERSION_CODES.JELLY_BEAN) {
16713                        throw new IllegalArgumentException("Component class " + className
16714                                + " does not exist in " + packageName);
16715                    } else {
16716                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16717                                + className + " does not exist in " + packageName);
16718                    }
16719                }
16720                switch (newState) {
16721                case COMPONENT_ENABLED_STATE_ENABLED:
16722                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16723                        return;
16724                    }
16725                    break;
16726                case COMPONENT_ENABLED_STATE_DISABLED:
16727                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16728                        return;
16729                    }
16730                    break;
16731                case COMPONENT_ENABLED_STATE_DEFAULT:
16732                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16733                        return;
16734                    }
16735                    break;
16736                default:
16737                    Slog.e(TAG, "Invalid new component state: " + newState);
16738                    return;
16739                }
16740            }
16741            scheduleWritePackageRestrictionsLocked(userId);
16742            components = mPendingBroadcasts.get(userId, packageName);
16743            final boolean newPackage = components == null;
16744            if (newPackage) {
16745                components = new ArrayList<String>();
16746            }
16747            if (!components.contains(componentName)) {
16748                components.add(componentName);
16749            }
16750            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16751                sendNow = true;
16752                // Purge entry from pending broadcast list if another one exists already
16753                // since we are sending one right away.
16754                mPendingBroadcasts.remove(userId, packageName);
16755            } else {
16756                if (newPackage) {
16757                    mPendingBroadcasts.put(userId, packageName, components);
16758                }
16759                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16760                    // Schedule a message
16761                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16762                }
16763            }
16764        }
16765
16766        long callingId = Binder.clearCallingIdentity();
16767        try {
16768            if (sendNow) {
16769                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16770                sendPackageChangedBroadcast(packageName,
16771                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16772            }
16773        } finally {
16774            Binder.restoreCallingIdentity(callingId);
16775        }
16776    }
16777
16778    @Override
16779    public void flushPackageRestrictionsAsUser(int userId) {
16780        if (!sUserManager.exists(userId)) {
16781            return;
16782        }
16783        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
16784                false /* checkShell */, "flushPackageRestrictions");
16785        synchronized (mPackages) {
16786            mSettings.writePackageRestrictionsLPr(userId);
16787            mDirtyUsers.remove(userId);
16788            if (mDirtyUsers.isEmpty()) {
16789                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
16790            }
16791        }
16792    }
16793
16794    private void sendPackageChangedBroadcast(String packageName,
16795            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16796        if (DEBUG_INSTALL)
16797            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16798                    + componentNames);
16799        Bundle extras = new Bundle(4);
16800        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16801        String nameList[] = new String[componentNames.size()];
16802        componentNames.toArray(nameList);
16803        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16804        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16805        extras.putInt(Intent.EXTRA_UID, packageUid);
16806        // If this is not reporting a change of the overall package, then only send it
16807        // to registered receivers.  We don't want to launch a swath of apps for every
16808        // little component state change.
16809        final int flags = !componentNames.contains(packageName)
16810                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16811        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16812                new int[] {UserHandle.getUserId(packageUid)});
16813    }
16814
16815    @Override
16816    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16817        if (!sUserManager.exists(userId)) return;
16818        final int uid = Binder.getCallingUid();
16819        final int permission = mContext.checkCallingOrSelfPermission(
16820                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16821        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16822        enforceCrossUserPermission(uid, userId,
16823                true /* requireFullPermission */, true /* checkShell */, "stop package");
16824        // writer
16825        synchronized (mPackages) {
16826            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16827                    allowedByPermission, uid, userId)) {
16828                scheduleWritePackageRestrictionsLocked(userId);
16829            }
16830        }
16831    }
16832
16833    @Override
16834    public String getInstallerPackageName(String packageName) {
16835        // reader
16836        synchronized (mPackages) {
16837            return mSettings.getInstallerPackageNameLPr(packageName);
16838        }
16839    }
16840
16841    @Override
16842    public int getApplicationEnabledSetting(String packageName, int userId) {
16843        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16844        int uid = Binder.getCallingUid();
16845        enforceCrossUserPermission(uid, userId,
16846                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16847        // reader
16848        synchronized (mPackages) {
16849            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16850        }
16851    }
16852
16853    @Override
16854    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16855        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16856        int uid = Binder.getCallingUid();
16857        enforceCrossUserPermission(uid, userId,
16858                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16859        // reader
16860        synchronized (mPackages) {
16861            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16862        }
16863    }
16864
16865    @Override
16866    public void enterSafeMode() {
16867        enforceSystemOrRoot("Only the system can request entering safe mode");
16868
16869        if (!mSystemReady) {
16870            mSafeMode = true;
16871        }
16872    }
16873
16874    @Override
16875    public void systemReady() {
16876        mSystemReady = true;
16877
16878        // Read the compatibilty setting when the system is ready.
16879        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16880                mContext.getContentResolver(),
16881                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16882        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16883        if (DEBUG_SETTINGS) {
16884            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16885        }
16886
16887        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16888
16889        synchronized (mPackages) {
16890            // Verify that all of the preferred activity components actually
16891            // exist.  It is possible for applications to be updated and at
16892            // that point remove a previously declared activity component that
16893            // had been set as a preferred activity.  We try to clean this up
16894            // the next time we encounter that preferred activity, but it is
16895            // possible for the user flow to never be able to return to that
16896            // situation so here we do a sanity check to make sure we haven't
16897            // left any junk around.
16898            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16899            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16900                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16901                removed.clear();
16902                for (PreferredActivity pa : pir.filterSet()) {
16903                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16904                        removed.add(pa);
16905                    }
16906                }
16907                if (removed.size() > 0) {
16908                    for (int r=0; r<removed.size(); r++) {
16909                        PreferredActivity pa = removed.get(r);
16910                        Slog.w(TAG, "Removing dangling preferred activity: "
16911                                + pa.mPref.mComponent);
16912                        pir.removeFilter(pa);
16913                    }
16914                    mSettings.writePackageRestrictionsLPr(
16915                            mSettings.mPreferredActivities.keyAt(i));
16916                }
16917            }
16918
16919            for (int userId : UserManagerService.getInstance().getUserIds()) {
16920                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16921                    grantPermissionsUserIds = ArrayUtils.appendInt(
16922                            grantPermissionsUserIds, userId);
16923                }
16924            }
16925        }
16926        sUserManager.systemReady();
16927
16928        // If we upgraded grant all default permissions before kicking off.
16929        for (int userId : grantPermissionsUserIds) {
16930            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16931        }
16932
16933        // Kick off any messages waiting for system ready
16934        if (mPostSystemReadyMessages != null) {
16935            for (Message msg : mPostSystemReadyMessages) {
16936                msg.sendToTarget();
16937            }
16938            mPostSystemReadyMessages = null;
16939        }
16940
16941        // Watch for external volumes that come and go over time
16942        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16943        storage.registerListener(mStorageListener);
16944
16945        mInstallerService.systemReady();
16946        mPackageDexOptimizer.systemReady();
16947
16948        MountServiceInternal mountServiceInternal = LocalServices.getService(
16949                MountServiceInternal.class);
16950        mountServiceInternal.addExternalStoragePolicy(
16951                new MountServiceInternal.ExternalStorageMountPolicy() {
16952            @Override
16953            public int getMountMode(int uid, String packageName) {
16954                if (Process.isIsolated(uid)) {
16955                    return Zygote.MOUNT_EXTERNAL_NONE;
16956                }
16957                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16958                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16959                }
16960                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16961                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16962                }
16963                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16964                    return Zygote.MOUNT_EXTERNAL_READ;
16965                }
16966                return Zygote.MOUNT_EXTERNAL_WRITE;
16967            }
16968
16969            @Override
16970            public boolean hasExternalStorage(int uid, String packageName) {
16971                return true;
16972            }
16973        });
16974    }
16975
16976    @Override
16977    public boolean isSafeMode() {
16978        return mSafeMode;
16979    }
16980
16981    @Override
16982    public boolean hasSystemUidErrors() {
16983        return mHasSystemUidErrors;
16984    }
16985
16986    static String arrayToString(int[] array) {
16987        StringBuffer buf = new StringBuffer(128);
16988        buf.append('[');
16989        if (array != null) {
16990            for (int i=0; i<array.length; i++) {
16991                if (i > 0) buf.append(", ");
16992                buf.append(array[i]);
16993            }
16994        }
16995        buf.append(']');
16996        return buf.toString();
16997    }
16998
16999    static class DumpState {
17000        public static final int DUMP_LIBS = 1 << 0;
17001        public static final int DUMP_FEATURES = 1 << 1;
17002        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17003        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17004        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17005        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17006        public static final int DUMP_PERMISSIONS = 1 << 6;
17007        public static final int DUMP_PACKAGES = 1 << 7;
17008        public static final int DUMP_SHARED_USERS = 1 << 8;
17009        public static final int DUMP_MESSAGES = 1 << 9;
17010        public static final int DUMP_PROVIDERS = 1 << 10;
17011        public static final int DUMP_VERIFIERS = 1 << 11;
17012        public static final int DUMP_PREFERRED = 1 << 12;
17013        public static final int DUMP_PREFERRED_XML = 1 << 13;
17014        public static final int DUMP_KEYSETS = 1 << 14;
17015        public static final int DUMP_VERSION = 1 << 15;
17016        public static final int DUMP_INSTALLS = 1 << 16;
17017        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17018        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17019
17020        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17021
17022        private int mTypes;
17023
17024        private int mOptions;
17025
17026        private boolean mTitlePrinted;
17027
17028        private SharedUserSetting mSharedUser;
17029
17030        public boolean isDumping(int type) {
17031            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17032                return true;
17033            }
17034
17035            return (mTypes & type) != 0;
17036        }
17037
17038        public void setDump(int type) {
17039            mTypes |= type;
17040        }
17041
17042        public boolean isOptionEnabled(int option) {
17043            return (mOptions & option) != 0;
17044        }
17045
17046        public void setOptionEnabled(int option) {
17047            mOptions |= option;
17048        }
17049
17050        public boolean onTitlePrinted() {
17051            final boolean printed = mTitlePrinted;
17052            mTitlePrinted = true;
17053            return printed;
17054        }
17055
17056        public boolean getTitlePrinted() {
17057            return mTitlePrinted;
17058        }
17059
17060        public void setTitlePrinted(boolean enabled) {
17061            mTitlePrinted = enabled;
17062        }
17063
17064        public SharedUserSetting getSharedUser() {
17065            return mSharedUser;
17066        }
17067
17068        public void setSharedUser(SharedUserSetting user) {
17069            mSharedUser = user;
17070        }
17071    }
17072
17073    @Override
17074    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17075            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17076        (new PackageManagerShellCommand(this)).exec(
17077                this, in, out, err, args, resultReceiver);
17078    }
17079
17080    @Override
17081    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17082        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17083                != PackageManager.PERMISSION_GRANTED) {
17084            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17085                    + Binder.getCallingPid()
17086                    + ", uid=" + Binder.getCallingUid()
17087                    + " without permission "
17088                    + android.Manifest.permission.DUMP);
17089            return;
17090        }
17091
17092        DumpState dumpState = new DumpState();
17093        boolean fullPreferred = false;
17094        boolean checkin = false;
17095
17096        String packageName = null;
17097        ArraySet<String> permissionNames = null;
17098
17099        int opti = 0;
17100        while (opti < args.length) {
17101            String opt = args[opti];
17102            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17103                break;
17104            }
17105            opti++;
17106
17107            if ("-a".equals(opt)) {
17108                // Right now we only know how to print all.
17109            } else if ("-h".equals(opt)) {
17110                pw.println("Package manager dump options:");
17111                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17112                pw.println("    --checkin: dump for a checkin");
17113                pw.println("    -f: print details of intent filters");
17114                pw.println("    -h: print this help");
17115                pw.println("  cmd may be one of:");
17116                pw.println("    l[ibraries]: list known shared libraries");
17117                pw.println("    f[eatures]: list device features");
17118                pw.println("    k[eysets]: print known keysets");
17119                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17120                pw.println("    perm[issions]: dump permissions");
17121                pw.println("    permission [name ...]: dump declaration and use of given permission");
17122                pw.println("    pref[erred]: print preferred package settings");
17123                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17124                pw.println("    prov[iders]: dump content providers");
17125                pw.println("    p[ackages]: dump installed packages");
17126                pw.println("    s[hared-users]: dump shared user IDs");
17127                pw.println("    m[essages]: print collected runtime messages");
17128                pw.println("    v[erifiers]: print package verifier info");
17129                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17130                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17131                pw.println("    version: print database version info");
17132                pw.println("    write: write current settings now");
17133                pw.println("    installs: details about install sessions");
17134                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17135                pw.println("    <package.name>: info about given package");
17136                return;
17137            } else if ("--checkin".equals(opt)) {
17138                checkin = true;
17139            } else if ("-f".equals(opt)) {
17140                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17141            } else {
17142                pw.println("Unknown argument: " + opt + "; use -h for help");
17143            }
17144        }
17145
17146        // Is the caller requesting to dump a particular piece of data?
17147        if (opti < args.length) {
17148            String cmd = args[opti];
17149            opti++;
17150            // Is this a package name?
17151            if ("android".equals(cmd) || cmd.contains(".")) {
17152                packageName = cmd;
17153                // When dumping a single package, we always dump all of its
17154                // filter information since the amount of data will be reasonable.
17155                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17156            } else if ("check-permission".equals(cmd)) {
17157                if (opti >= args.length) {
17158                    pw.println("Error: check-permission missing permission argument");
17159                    return;
17160                }
17161                String perm = args[opti];
17162                opti++;
17163                if (opti >= args.length) {
17164                    pw.println("Error: check-permission missing package argument");
17165                    return;
17166                }
17167                String pkg = args[opti];
17168                opti++;
17169                int user = UserHandle.getUserId(Binder.getCallingUid());
17170                if (opti < args.length) {
17171                    try {
17172                        user = Integer.parseInt(args[opti]);
17173                    } catch (NumberFormatException e) {
17174                        pw.println("Error: check-permission user argument is not a number: "
17175                                + args[opti]);
17176                        return;
17177                    }
17178                }
17179                pw.println(checkPermission(perm, pkg, user));
17180                return;
17181            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17182                dumpState.setDump(DumpState.DUMP_LIBS);
17183            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17184                dumpState.setDump(DumpState.DUMP_FEATURES);
17185            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17186                if (opti >= args.length) {
17187                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17188                            | DumpState.DUMP_SERVICE_RESOLVERS
17189                            | DumpState.DUMP_RECEIVER_RESOLVERS
17190                            | DumpState.DUMP_CONTENT_RESOLVERS);
17191                } else {
17192                    while (opti < args.length) {
17193                        String name = args[opti];
17194                        if ("a".equals(name) || "activity".equals(name)) {
17195                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17196                        } else if ("s".equals(name) || "service".equals(name)) {
17197                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17198                        } else if ("r".equals(name) || "receiver".equals(name)) {
17199                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17200                        } else if ("c".equals(name) || "content".equals(name)) {
17201                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17202                        } else {
17203                            pw.println("Error: unknown resolver table type: " + name);
17204                            return;
17205                        }
17206                        opti++;
17207                    }
17208                }
17209            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17210                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17211            } else if ("permission".equals(cmd)) {
17212                if (opti >= args.length) {
17213                    pw.println("Error: permission requires permission name");
17214                    return;
17215                }
17216                permissionNames = new ArraySet<>();
17217                while (opti < args.length) {
17218                    permissionNames.add(args[opti]);
17219                    opti++;
17220                }
17221                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17222                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17223            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17224                dumpState.setDump(DumpState.DUMP_PREFERRED);
17225            } else if ("preferred-xml".equals(cmd)) {
17226                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17227                if (opti < args.length && "--full".equals(args[opti])) {
17228                    fullPreferred = true;
17229                    opti++;
17230                }
17231            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17232                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17233            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17234                dumpState.setDump(DumpState.DUMP_PACKAGES);
17235            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17236                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17237            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17238                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17239            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17240                dumpState.setDump(DumpState.DUMP_MESSAGES);
17241            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17242                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17243            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17244                    || "intent-filter-verifiers".equals(cmd)) {
17245                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17246            } else if ("version".equals(cmd)) {
17247                dumpState.setDump(DumpState.DUMP_VERSION);
17248            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17249                dumpState.setDump(DumpState.DUMP_KEYSETS);
17250            } else if ("installs".equals(cmd)) {
17251                dumpState.setDump(DumpState.DUMP_INSTALLS);
17252            } else if ("write".equals(cmd)) {
17253                synchronized (mPackages) {
17254                    mSettings.writeLPr();
17255                    pw.println("Settings written.");
17256                    return;
17257                }
17258            }
17259        }
17260
17261        if (checkin) {
17262            pw.println("vers,1");
17263        }
17264
17265        // reader
17266        synchronized (mPackages) {
17267            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17268                if (!checkin) {
17269                    if (dumpState.onTitlePrinted())
17270                        pw.println();
17271                    pw.println("Database versions:");
17272                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17273                }
17274            }
17275
17276            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17277                if (!checkin) {
17278                    if (dumpState.onTitlePrinted())
17279                        pw.println();
17280                    pw.println("Verifiers:");
17281                    pw.print("  Required: ");
17282                    pw.print(mRequiredVerifierPackage);
17283                    pw.print(" (uid=");
17284                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17285                            UserHandle.USER_SYSTEM));
17286                    pw.println(")");
17287                } else if (mRequiredVerifierPackage != null) {
17288                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17289                    pw.print(",");
17290                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17291                            UserHandle.USER_SYSTEM));
17292                }
17293            }
17294
17295            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17296                    packageName == null) {
17297                if (mIntentFilterVerifierComponent != null) {
17298                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17299                    if (!checkin) {
17300                        if (dumpState.onTitlePrinted())
17301                            pw.println();
17302                        pw.println("Intent Filter Verifier:");
17303                        pw.print("  Using: ");
17304                        pw.print(verifierPackageName);
17305                        pw.print(" (uid=");
17306                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17307                                UserHandle.USER_SYSTEM));
17308                        pw.println(")");
17309                    } else if (verifierPackageName != null) {
17310                        pw.print("ifv,"); pw.print(verifierPackageName);
17311                        pw.print(",");
17312                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17313                                UserHandle.USER_SYSTEM));
17314                    }
17315                } else {
17316                    pw.println();
17317                    pw.println("No Intent Filter Verifier available!");
17318                }
17319            }
17320
17321            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17322                boolean printedHeader = false;
17323                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17324                while (it.hasNext()) {
17325                    String name = it.next();
17326                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17327                    if (!checkin) {
17328                        if (!printedHeader) {
17329                            if (dumpState.onTitlePrinted())
17330                                pw.println();
17331                            pw.println("Libraries:");
17332                            printedHeader = true;
17333                        }
17334                        pw.print("  ");
17335                    } else {
17336                        pw.print("lib,");
17337                    }
17338                    pw.print(name);
17339                    if (!checkin) {
17340                        pw.print(" -> ");
17341                    }
17342                    if (ent.path != null) {
17343                        if (!checkin) {
17344                            pw.print("(jar) ");
17345                            pw.print(ent.path);
17346                        } else {
17347                            pw.print(",jar,");
17348                            pw.print(ent.path);
17349                        }
17350                    } else {
17351                        if (!checkin) {
17352                            pw.print("(apk) ");
17353                            pw.print(ent.apk);
17354                        } else {
17355                            pw.print(",apk,");
17356                            pw.print(ent.apk);
17357                        }
17358                    }
17359                    pw.println();
17360                }
17361            }
17362
17363            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17364                if (dumpState.onTitlePrinted())
17365                    pw.println();
17366                if (!checkin) {
17367                    pw.println("Features:");
17368                }
17369
17370                for (FeatureInfo feat : mAvailableFeatures.values()) {
17371                    if (checkin) {
17372                        pw.print("feat,");
17373                        pw.print(feat.name);
17374                        pw.print(",");
17375                        pw.println(feat.version);
17376                    } else {
17377                        pw.print("  ");
17378                        pw.print(feat.name);
17379                        if (feat.version > 0) {
17380                            pw.print(" version=");
17381                            pw.print(feat.version);
17382                        }
17383                        pw.println();
17384                    }
17385                }
17386            }
17387
17388            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17389                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17390                        : "Activity Resolver Table:", "  ", packageName,
17391                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17392                    dumpState.setTitlePrinted(true);
17393                }
17394            }
17395            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17396                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17397                        : "Receiver Resolver Table:", "  ", packageName,
17398                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17399                    dumpState.setTitlePrinted(true);
17400                }
17401            }
17402            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17403                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17404                        : "Service Resolver Table:", "  ", packageName,
17405                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17406                    dumpState.setTitlePrinted(true);
17407                }
17408            }
17409            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17410                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17411                        : "Provider Resolver Table:", "  ", packageName,
17412                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17413                    dumpState.setTitlePrinted(true);
17414                }
17415            }
17416
17417            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17418                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17419                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17420                    int user = mSettings.mPreferredActivities.keyAt(i);
17421                    if (pir.dump(pw,
17422                            dumpState.getTitlePrinted()
17423                                ? "\nPreferred Activities User " + user + ":"
17424                                : "Preferred Activities User " + user + ":", "  ",
17425                            packageName, true, false)) {
17426                        dumpState.setTitlePrinted(true);
17427                    }
17428                }
17429            }
17430
17431            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17432                pw.flush();
17433                FileOutputStream fout = new FileOutputStream(fd);
17434                BufferedOutputStream str = new BufferedOutputStream(fout);
17435                XmlSerializer serializer = new FastXmlSerializer();
17436                try {
17437                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17438                    serializer.startDocument(null, true);
17439                    serializer.setFeature(
17440                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17441                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17442                    serializer.endDocument();
17443                    serializer.flush();
17444                } catch (IllegalArgumentException e) {
17445                    pw.println("Failed writing: " + e);
17446                } catch (IllegalStateException e) {
17447                    pw.println("Failed writing: " + e);
17448                } catch (IOException e) {
17449                    pw.println("Failed writing: " + e);
17450                }
17451            }
17452
17453            if (!checkin
17454                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17455                    && packageName == null) {
17456                pw.println();
17457                int count = mSettings.mPackages.size();
17458                if (count == 0) {
17459                    pw.println("No applications!");
17460                    pw.println();
17461                } else {
17462                    final String prefix = "  ";
17463                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17464                    if (allPackageSettings.size() == 0) {
17465                        pw.println("No domain preferred apps!");
17466                        pw.println();
17467                    } else {
17468                        pw.println("App verification status:");
17469                        pw.println();
17470                        count = 0;
17471                        for (PackageSetting ps : allPackageSettings) {
17472                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17473                            if (ivi == null || ivi.getPackageName() == null) continue;
17474                            pw.println(prefix + "Package: " + ivi.getPackageName());
17475                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17476                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17477                            pw.println();
17478                            count++;
17479                        }
17480                        if (count == 0) {
17481                            pw.println(prefix + "No app verification established.");
17482                            pw.println();
17483                        }
17484                        for (int userId : sUserManager.getUserIds()) {
17485                            pw.println("App linkages for user " + userId + ":");
17486                            pw.println();
17487                            count = 0;
17488                            for (PackageSetting ps : allPackageSettings) {
17489                                final long status = ps.getDomainVerificationStatusForUser(userId);
17490                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17491                                    continue;
17492                                }
17493                                pw.println(prefix + "Package: " + ps.name);
17494                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17495                                String statusStr = IntentFilterVerificationInfo.
17496                                        getStatusStringFromValue(status);
17497                                pw.println(prefix + "Status:  " + statusStr);
17498                                pw.println();
17499                                count++;
17500                            }
17501                            if (count == 0) {
17502                                pw.println(prefix + "No configured app linkages.");
17503                                pw.println();
17504                            }
17505                        }
17506                    }
17507                }
17508            }
17509
17510            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17511                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17512                if (packageName == null && permissionNames == null) {
17513                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17514                        if (iperm == 0) {
17515                            if (dumpState.onTitlePrinted())
17516                                pw.println();
17517                            pw.println("AppOp Permissions:");
17518                        }
17519                        pw.print("  AppOp Permission ");
17520                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17521                        pw.println(":");
17522                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17523                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17524                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17525                        }
17526                    }
17527                }
17528            }
17529
17530            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17531                boolean printedSomething = false;
17532                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17533                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17534                        continue;
17535                    }
17536                    if (!printedSomething) {
17537                        if (dumpState.onTitlePrinted())
17538                            pw.println();
17539                        pw.println("Registered ContentProviders:");
17540                        printedSomething = true;
17541                    }
17542                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17543                    pw.print("    "); pw.println(p.toString());
17544                }
17545                printedSomething = false;
17546                for (Map.Entry<String, PackageParser.Provider> entry :
17547                        mProvidersByAuthority.entrySet()) {
17548                    PackageParser.Provider p = entry.getValue();
17549                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17550                        continue;
17551                    }
17552                    if (!printedSomething) {
17553                        if (dumpState.onTitlePrinted())
17554                            pw.println();
17555                        pw.println("ContentProvider Authorities:");
17556                        printedSomething = true;
17557                    }
17558                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17559                    pw.print("    "); pw.println(p.toString());
17560                    if (p.info != null && p.info.applicationInfo != null) {
17561                        final String appInfo = p.info.applicationInfo.toString();
17562                        pw.print("      applicationInfo="); pw.println(appInfo);
17563                    }
17564                }
17565            }
17566
17567            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17568                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17569            }
17570
17571            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17572                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17573            }
17574
17575            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17576                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17577            }
17578
17579            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17580                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17581            }
17582
17583            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17584                // XXX should handle packageName != null by dumping only install data that
17585                // the given package is involved with.
17586                if (dumpState.onTitlePrinted()) pw.println();
17587                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17588            }
17589
17590            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17591                if (dumpState.onTitlePrinted()) pw.println();
17592                mSettings.dumpReadMessagesLPr(pw, dumpState);
17593
17594                pw.println();
17595                pw.println("Package warning messages:");
17596                BufferedReader in = null;
17597                String line = null;
17598                try {
17599                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17600                    while ((line = in.readLine()) != null) {
17601                        if (line.contains("ignored: updated version")) continue;
17602                        pw.println(line);
17603                    }
17604                } catch (IOException ignored) {
17605                } finally {
17606                    IoUtils.closeQuietly(in);
17607                }
17608            }
17609
17610            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17611                BufferedReader in = null;
17612                String line = null;
17613                try {
17614                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17615                    while ((line = in.readLine()) != null) {
17616                        if (line.contains("ignored: updated version")) continue;
17617                        pw.print("msg,");
17618                        pw.println(line);
17619                    }
17620                } catch (IOException ignored) {
17621                } finally {
17622                    IoUtils.closeQuietly(in);
17623                }
17624            }
17625        }
17626    }
17627
17628    private String dumpDomainString(String packageName) {
17629        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
17630                .getList();
17631        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
17632
17633        ArraySet<String> result = new ArraySet<>();
17634        if (iviList.size() > 0) {
17635            for (IntentFilterVerificationInfo ivi : iviList) {
17636                for (String host : ivi.getDomains()) {
17637                    result.add(host);
17638                }
17639            }
17640        }
17641        if (filters != null && filters.size() > 0) {
17642            for (IntentFilter filter : filters) {
17643                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17644                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17645                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17646                    result.addAll(filter.getHostsList());
17647                }
17648            }
17649        }
17650
17651        StringBuilder sb = new StringBuilder(result.size() * 16);
17652        for (String domain : result) {
17653            if (sb.length() > 0) sb.append(" ");
17654            sb.append(domain);
17655        }
17656        return sb.toString();
17657    }
17658
17659    // ------- apps on sdcard specific code -------
17660    static final boolean DEBUG_SD_INSTALL = false;
17661
17662    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17663
17664    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17665
17666    private boolean mMediaMounted = false;
17667
17668    static String getEncryptKey() {
17669        try {
17670            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17671                    SD_ENCRYPTION_KEYSTORE_NAME);
17672            if (sdEncKey == null) {
17673                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17674                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17675                if (sdEncKey == null) {
17676                    Slog.e(TAG, "Failed to create encryption keys");
17677                    return null;
17678                }
17679            }
17680            return sdEncKey;
17681        } catch (NoSuchAlgorithmException nsae) {
17682            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17683            return null;
17684        } catch (IOException ioe) {
17685            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17686            return null;
17687        }
17688    }
17689
17690    /*
17691     * Update media status on PackageManager.
17692     */
17693    @Override
17694    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17695        int callingUid = Binder.getCallingUid();
17696        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17697            throw new SecurityException("Media status can only be updated by the system");
17698        }
17699        // reader; this apparently protects mMediaMounted, but should probably
17700        // be a different lock in that case.
17701        synchronized (mPackages) {
17702            Log.i(TAG, "Updating external media status from "
17703                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17704                    + (mediaStatus ? "mounted" : "unmounted"));
17705            if (DEBUG_SD_INSTALL)
17706                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17707                        + ", mMediaMounted=" + mMediaMounted);
17708            if (mediaStatus == mMediaMounted) {
17709                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17710                        : 0, -1);
17711                mHandler.sendMessage(msg);
17712                return;
17713            }
17714            mMediaMounted = mediaStatus;
17715        }
17716        // Queue up an async operation since the package installation may take a
17717        // little while.
17718        mHandler.post(new Runnable() {
17719            public void run() {
17720                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17721            }
17722        });
17723    }
17724
17725    /**
17726     * Called by MountService when the initial ASECs to scan are available.
17727     * Should block until all the ASEC containers are finished being scanned.
17728     */
17729    public void scanAvailableAsecs() {
17730        updateExternalMediaStatusInner(true, false, false);
17731    }
17732
17733    /*
17734     * Collect information of applications on external media, map them against
17735     * existing containers and update information based on current mount status.
17736     * Please note that we always have to report status if reportStatus has been
17737     * set to true especially when unloading packages.
17738     */
17739    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17740            boolean externalStorage) {
17741        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17742        int[] uidArr = EmptyArray.INT;
17743
17744        final String[] list = PackageHelper.getSecureContainerList();
17745        if (ArrayUtils.isEmpty(list)) {
17746            Log.i(TAG, "No secure containers found");
17747        } else {
17748            // Process list of secure containers and categorize them
17749            // as active or stale based on their package internal state.
17750
17751            // reader
17752            synchronized (mPackages) {
17753                for (String cid : list) {
17754                    // Leave stages untouched for now; installer service owns them
17755                    if (PackageInstallerService.isStageName(cid)) continue;
17756
17757                    if (DEBUG_SD_INSTALL)
17758                        Log.i(TAG, "Processing container " + cid);
17759                    String pkgName = getAsecPackageName(cid);
17760                    if (pkgName == null) {
17761                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17762                        continue;
17763                    }
17764                    if (DEBUG_SD_INSTALL)
17765                        Log.i(TAG, "Looking for pkg : " + pkgName);
17766
17767                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17768                    if (ps == null) {
17769                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17770                        continue;
17771                    }
17772
17773                    /*
17774                     * Skip packages that are not external if we're unmounting
17775                     * external storage.
17776                     */
17777                    if (externalStorage && !isMounted && !isExternal(ps)) {
17778                        continue;
17779                    }
17780
17781                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17782                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17783                    // The package status is changed only if the code path
17784                    // matches between settings and the container id.
17785                    if (ps.codePathString != null
17786                            && ps.codePathString.startsWith(args.getCodePath())) {
17787                        if (DEBUG_SD_INSTALL) {
17788                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17789                                    + " at code path: " + ps.codePathString);
17790                        }
17791
17792                        // We do have a valid package installed on sdcard
17793                        processCids.put(args, ps.codePathString);
17794                        final int uid = ps.appId;
17795                        if (uid != -1) {
17796                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17797                        }
17798                    } else {
17799                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17800                                + ps.codePathString);
17801                    }
17802                }
17803            }
17804
17805            Arrays.sort(uidArr);
17806        }
17807
17808        // Process packages with valid entries.
17809        if (isMounted) {
17810            if (DEBUG_SD_INSTALL)
17811                Log.i(TAG, "Loading packages");
17812            loadMediaPackages(processCids, uidArr, externalStorage);
17813            startCleaningPackages();
17814            mInstallerService.onSecureContainersAvailable();
17815        } else {
17816            if (DEBUG_SD_INSTALL)
17817                Log.i(TAG, "Unloading packages");
17818            unloadMediaPackages(processCids, uidArr, reportStatus);
17819        }
17820    }
17821
17822    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17823            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17824        final int size = infos.size();
17825        final String[] packageNames = new String[size];
17826        final int[] packageUids = new int[size];
17827        for (int i = 0; i < size; i++) {
17828            final ApplicationInfo info = infos.get(i);
17829            packageNames[i] = info.packageName;
17830            packageUids[i] = info.uid;
17831        }
17832        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17833                finishedReceiver);
17834    }
17835
17836    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17837            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17838        sendResourcesChangedBroadcast(mediaStatus, replacing,
17839                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17840    }
17841
17842    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17843            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17844        int size = pkgList.length;
17845        if (size > 0) {
17846            // Send broadcasts here
17847            Bundle extras = new Bundle();
17848            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17849            if (uidArr != null) {
17850                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17851            }
17852            if (replacing) {
17853                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17854            }
17855            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17856                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17857            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17858        }
17859    }
17860
17861   /*
17862     * Look at potentially valid container ids from processCids If package
17863     * information doesn't match the one on record or package scanning fails,
17864     * the cid is added to list of removeCids. We currently don't delete stale
17865     * containers.
17866     */
17867    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17868            boolean externalStorage) {
17869        ArrayList<String> pkgList = new ArrayList<String>();
17870        Set<AsecInstallArgs> keys = processCids.keySet();
17871
17872        for (AsecInstallArgs args : keys) {
17873            String codePath = processCids.get(args);
17874            if (DEBUG_SD_INSTALL)
17875                Log.i(TAG, "Loading container : " + args.cid);
17876            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17877            try {
17878                // Make sure there are no container errors first.
17879                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17880                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17881                            + " when installing from sdcard");
17882                    continue;
17883                }
17884                // Check code path here.
17885                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17886                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17887                            + " does not match one in settings " + codePath);
17888                    continue;
17889                }
17890                // Parse package
17891                int parseFlags = mDefParseFlags;
17892                if (args.isExternalAsec()) {
17893                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17894                }
17895                if (args.isFwdLocked()) {
17896                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17897                }
17898
17899                synchronized (mInstallLock) {
17900                    PackageParser.Package pkg = null;
17901                    try {
17902                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17903                    } catch (PackageManagerException e) {
17904                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17905                    }
17906                    // Scan the package
17907                    if (pkg != null) {
17908                        /*
17909                         * TODO why is the lock being held? doPostInstall is
17910                         * called in other places without the lock. This needs
17911                         * to be straightened out.
17912                         */
17913                        // writer
17914                        synchronized (mPackages) {
17915                            retCode = PackageManager.INSTALL_SUCCEEDED;
17916                            pkgList.add(pkg.packageName);
17917                            // Post process args
17918                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17919                                    pkg.applicationInfo.uid);
17920                        }
17921                    } else {
17922                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17923                    }
17924                }
17925
17926            } finally {
17927                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17928                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17929                }
17930            }
17931        }
17932        // writer
17933        synchronized (mPackages) {
17934            // If the platform SDK has changed since the last time we booted,
17935            // we need to re-grant app permission to catch any new ones that
17936            // appear. This is really a hack, and means that apps can in some
17937            // cases get permissions that the user didn't initially explicitly
17938            // allow... it would be nice to have some better way to handle
17939            // this situation.
17940            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17941                    : mSettings.getInternalVersion();
17942            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17943                    : StorageManager.UUID_PRIVATE_INTERNAL;
17944
17945            int updateFlags = UPDATE_PERMISSIONS_ALL;
17946            if (ver.sdkVersion != mSdkVersion) {
17947                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17948                        + mSdkVersion + "; regranting permissions for external");
17949                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17950            }
17951            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17952
17953            // Yay, everything is now upgraded
17954            ver.forceCurrent();
17955
17956            // can downgrade to reader
17957            // Persist settings
17958            mSettings.writeLPr();
17959        }
17960        // Send a broadcast to let everyone know we are done processing
17961        if (pkgList.size() > 0) {
17962            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17963        }
17964    }
17965
17966   /*
17967     * Utility method to unload a list of specified containers
17968     */
17969    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17970        // Just unmount all valid containers.
17971        for (AsecInstallArgs arg : cidArgs) {
17972            synchronized (mInstallLock) {
17973                arg.doPostDeleteLI(false);
17974           }
17975       }
17976   }
17977
17978    /*
17979     * Unload packages mounted on external media. This involves deleting package
17980     * data from internal structures, sending broadcasts about disabled packages,
17981     * gc'ing to free up references, unmounting all secure containers
17982     * corresponding to packages on external media, and posting a
17983     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17984     * that we always have to post this message if status has been requested no
17985     * matter what.
17986     */
17987    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17988            final boolean reportStatus) {
17989        if (DEBUG_SD_INSTALL)
17990            Log.i(TAG, "unloading media packages");
17991        ArrayList<String> pkgList = new ArrayList<String>();
17992        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17993        final Set<AsecInstallArgs> keys = processCids.keySet();
17994        for (AsecInstallArgs args : keys) {
17995            String pkgName = args.getPackageName();
17996            if (DEBUG_SD_INSTALL)
17997                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17998            // Delete package internally
17999            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18000            synchronized (mInstallLock) {
18001                boolean res = deletePackageLI(pkgName, null, false, null,
18002                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
18003                if (res) {
18004                    pkgList.add(pkgName);
18005                } else {
18006                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18007                    failedList.add(args);
18008                }
18009            }
18010        }
18011
18012        // reader
18013        synchronized (mPackages) {
18014            // We didn't update the settings after removing each package;
18015            // write them now for all packages.
18016            mSettings.writeLPr();
18017        }
18018
18019        // We have to absolutely send UPDATED_MEDIA_STATUS only
18020        // after confirming that all the receivers processed the ordered
18021        // broadcast when packages get disabled, force a gc to clean things up.
18022        // and unload all the containers.
18023        if (pkgList.size() > 0) {
18024            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18025                    new IIntentReceiver.Stub() {
18026                public void performReceive(Intent intent, int resultCode, String data,
18027                        Bundle extras, boolean ordered, boolean sticky,
18028                        int sendingUser) throws RemoteException {
18029                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18030                            reportStatus ? 1 : 0, 1, keys);
18031                    mHandler.sendMessage(msg);
18032                }
18033            });
18034        } else {
18035            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18036                    keys);
18037            mHandler.sendMessage(msg);
18038        }
18039    }
18040
18041    private void loadPrivatePackages(final VolumeInfo vol) {
18042        mHandler.post(new Runnable() {
18043            @Override
18044            public void run() {
18045                loadPrivatePackagesInner(vol);
18046            }
18047        });
18048    }
18049
18050    private void loadPrivatePackagesInner(VolumeInfo vol) {
18051        final String volumeUuid = vol.fsUuid;
18052        if (TextUtils.isEmpty(volumeUuid)) {
18053            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18054            return;
18055        }
18056
18057        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18058        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18059
18060        final VersionInfo ver;
18061        final List<PackageSetting> packages;
18062        synchronized (mPackages) {
18063            ver = mSettings.findOrCreateVersion(volumeUuid);
18064            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18065        }
18066
18067        // TODO: introduce a new concept similar to "frozen" to prevent these
18068        // apps from being launched until after data has been fully reconciled
18069        for (PackageSetting ps : packages) {
18070            synchronized (mInstallLock) {
18071                final PackageParser.Package pkg;
18072                try {
18073                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18074                    loaded.add(pkg.applicationInfo);
18075
18076                } catch (PackageManagerException e) {
18077                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18078                }
18079
18080                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18081                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
18082                }
18083            }
18084        }
18085
18086        // Reconcile app data for all started/unlocked users
18087        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18088        final UserManager um = mContext.getSystemService(UserManager.class);
18089        for (UserInfo user : um.getUsers()) {
18090            final int flags;
18091            if (um.isUserUnlocked(user.id)) {
18092                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18093            } else if (um.isUserRunning(user.id)) {
18094                flags = StorageManager.FLAG_STORAGE_DE;
18095            } else {
18096                continue;
18097            }
18098
18099            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18100            reconcileAppsData(volumeUuid, user.id, flags);
18101        }
18102
18103        synchronized (mPackages) {
18104            int updateFlags = UPDATE_PERMISSIONS_ALL;
18105            if (ver.sdkVersion != mSdkVersion) {
18106                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18107                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18108                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18109            }
18110            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18111
18112            // Yay, everything is now upgraded
18113            ver.forceCurrent();
18114
18115            mSettings.writeLPr();
18116        }
18117
18118        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18119        sendResourcesChangedBroadcast(true, false, loaded, null);
18120    }
18121
18122    private void unloadPrivatePackages(final VolumeInfo vol) {
18123        mHandler.post(new Runnable() {
18124            @Override
18125            public void run() {
18126                unloadPrivatePackagesInner(vol);
18127            }
18128        });
18129    }
18130
18131    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18132        final String volumeUuid = vol.fsUuid;
18133        if (TextUtils.isEmpty(volumeUuid)) {
18134            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18135            return;
18136        }
18137
18138        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18139        synchronized (mInstallLock) {
18140        synchronized (mPackages) {
18141            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18142            for (PackageSetting ps : packages) {
18143                if (ps.pkg == null) continue;
18144
18145                final ApplicationInfo info = ps.pkg.applicationInfo;
18146                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18147                if (deletePackageLI(ps.name, null, false, null,
18148                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18149                    unloaded.add(info);
18150                } else {
18151                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18152                }
18153            }
18154
18155            mSettings.writeLPr();
18156        }
18157        }
18158
18159        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18160        sendResourcesChangedBroadcast(false, false, unloaded, null);
18161    }
18162
18163    /**
18164     * Examine all users present on given mounted volume, and destroy data
18165     * belonging to users that are no longer valid, or whose user ID has been
18166     * recycled.
18167     */
18168    private void reconcileUsers(String volumeUuid) {
18169        // TODO: also reconcile DE directories
18170        final File[] files = FileUtils
18171                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18172        for (File file : files) {
18173            if (!file.isDirectory()) continue;
18174
18175            final int userId;
18176            final UserInfo info;
18177            try {
18178                userId = Integer.parseInt(file.getName());
18179                info = sUserManager.getUserInfo(userId);
18180            } catch (NumberFormatException e) {
18181                Slog.w(TAG, "Invalid user directory " + file);
18182                continue;
18183            }
18184
18185            boolean destroyUser = false;
18186            if (info == null) {
18187                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18188                        + " because no matching user was found");
18189                destroyUser = true;
18190            } else {
18191                try {
18192                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18193                } catch (IOException e) {
18194                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18195                            + " because we failed to enforce serial number: " + e);
18196                    destroyUser = true;
18197                }
18198            }
18199
18200            if (destroyUser) {
18201                synchronized (mInstallLock) {
18202                    try {
18203                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18204                    } catch (InstallerException e) {
18205                        Slog.w(TAG, "Failed to clean up user dirs", e);
18206                    }
18207                }
18208            }
18209        }
18210    }
18211
18212    private void assertPackageKnown(String volumeUuid, String packageName)
18213            throws PackageManagerException {
18214        synchronized (mPackages) {
18215            final PackageSetting ps = mSettings.mPackages.get(packageName);
18216            if (ps == null) {
18217                throw new PackageManagerException("Package " + packageName + " is unknown");
18218            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18219                throw new PackageManagerException(
18220                        "Package " + packageName + " found on unknown volume " + volumeUuid
18221                                + "; expected volume " + ps.volumeUuid);
18222            }
18223        }
18224    }
18225
18226    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18227            throws PackageManagerException {
18228        synchronized (mPackages) {
18229            final PackageSetting ps = mSettings.mPackages.get(packageName);
18230            if (ps == null) {
18231                throw new PackageManagerException("Package " + packageName + " is unknown");
18232            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18233                throw new PackageManagerException(
18234                        "Package " + packageName + " found on unknown volume " + volumeUuid
18235                                + "; expected volume " + ps.volumeUuid);
18236            } else if (!ps.getInstalled(userId)) {
18237                throw new PackageManagerException(
18238                        "Package " + packageName + " not installed for user " + userId);
18239            }
18240        }
18241    }
18242
18243    /**
18244     * Examine all apps present on given mounted volume, and destroy apps that
18245     * aren't expected, either due to uninstallation or reinstallation on
18246     * another volume.
18247     */
18248    private void reconcileApps(String volumeUuid) {
18249        final File[] files = FileUtils
18250                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18251        for (File file : files) {
18252            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18253                    && !PackageInstallerService.isStageName(file.getName());
18254            if (!isPackage) {
18255                // Ignore entries which are not packages
18256                continue;
18257            }
18258
18259            try {
18260                final PackageLite pkg = PackageParser.parsePackageLite(file,
18261                        PackageParser.PARSE_MUST_BE_APK);
18262                assertPackageKnown(volumeUuid, pkg.packageName);
18263
18264            } catch (PackageParserException | PackageManagerException e) {
18265                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18266                synchronized (mInstallLock) {
18267                    removeCodePathLI(file);
18268                }
18269            }
18270        }
18271    }
18272
18273    /**
18274     * Reconcile all app data for the given user.
18275     * <p>
18276     * Verifies that directories exist and that ownership and labeling is
18277     * correct for all installed apps on all mounted volumes.
18278     */
18279    void reconcileAppsData(int userId, int flags) {
18280        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18281        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18282            final String volumeUuid = vol.getFsUuid();
18283            reconcileAppsData(volumeUuid, userId, flags);
18284        }
18285    }
18286
18287    /**
18288     * Reconcile all app data on given mounted volume.
18289     * <p>
18290     * Destroys app data that isn't expected, either due to uninstallation or
18291     * reinstallation on another volume.
18292     * <p>
18293     * Verifies that directories exist and that ownership and labeling is
18294     * correct for all installed apps.
18295     */
18296    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18297        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18298                + Integer.toHexString(flags));
18299
18300        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18301        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18302
18303        boolean restoreconNeeded = false;
18304
18305        // First look for stale data that doesn't belong, and check if things
18306        // have changed since we did our last restorecon
18307        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18308            if (!isUserKeyUnlocked(userId)) {
18309                throw new RuntimeException(
18310                        "Yikes, someone asked us to reconcile CE storage while " + userId
18311                                + " was still locked; this would have caused massive data loss!");
18312            }
18313
18314            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18315
18316            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18317            for (File file : files) {
18318                final String packageName = file.getName();
18319                try {
18320                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18321                } catch (PackageManagerException e) {
18322                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18323                    synchronized (mInstallLock) {
18324                        destroyAppDataLI(volumeUuid, packageName, userId,
18325                                StorageManager.FLAG_STORAGE_CE);
18326                    }
18327                }
18328            }
18329        }
18330        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18331            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18332
18333            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18334            for (File file : files) {
18335                final String packageName = file.getName();
18336                try {
18337                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18338                } catch (PackageManagerException e) {
18339                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18340                    synchronized (mInstallLock) {
18341                        destroyAppDataLI(volumeUuid, packageName, userId,
18342                                StorageManager.FLAG_STORAGE_DE);
18343                    }
18344                }
18345            }
18346        }
18347
18348        // Ensure that data directories are ready to roll for all packages
18349        // installed for this volume and user
18350        final List<PackageSetting> packages;
18351        synchronized (mPackages) {
18352            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18353        }
18354        int preparedCount = 0;
18355        for (PackageSetting ps : packages) {
18356            final String packageName = ps.name;
18357            if (ps.pkg == null) {
18358                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18359                // TODO: might be due to legacy ASEC apps; we should circle back
18360                // and reconcile again once they're scanned
18361                continue;
18362            }
18363
18364            if (ps.getInstalled(userId)) {
18365                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18366
18367                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18368                    // We may have just shuffled around app data directories, so
18369                    // prepare them one more time
18370                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18371                }
18372
18373                preparedCount++;
18374            }
18375        }
18376
18377        if (restoreconNeeded) {
18378            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18379                SELinuxMMAC.setRestoreconDone(ceDir);
18380            }
18381            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18382                SELinuxMMAC.setRestoreconDone(deDir);
18383            }
18384        }
18385
18386        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18387                + " packages; restoreconNeeded was " + restoreconNeeded);
18388    }
18389
18390    /**
18391     * Prepare app data for the given app just after it was installed or
18392     * upgraded. This method carefully only touches users that it's installed
18393     * for, and it forces a restorecon to handle any seinfo changes.
18394     * <p>
18395     * Verifies that directories exist and that ownership and labeling is
18396     * correct for all installed apps. If there is an ownership mismatch, it
18397     * will try recovering system apps by wiping data; third-party app data is
18398     * left intact.
18399     * <p>
18400     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18401     */
18402    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18403        prepareAppDataAfterInstallInternal(pkg);
18404        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18405        for (int i = 0; i < childCount; i++) {
18406            PackageParser.Package childPackage = pkg.childPackages.get(i);
18407            prepareAppDataAfterInstallInternal(childPackage);
18408        }
18409    }
18410
18411    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18412        final PackageSetting ps;
18413        synchronized (mPackages) {
18414            ps = mSettings.mPackages.get(pkg.packageName);
18415            mSettings.writeKernelMappingLPr(ps);
18416        }
18417
18418        final UserManager um = mContext.getSystemService(UserManager.class);
18419        for (UserInfo user : um.getUsers()) {
18420            final int flags;
18421            if (um.isUserUnlocked(user.id)) {
18422                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18423            } else if (um.isUserRunning(user.id)) {
18424                flags = StorageManager.FLAG_STORAGE_DE;
18425            } else {
18426                continue;
18427            }
18428
18429            if (ps.getInstalled(user.id)) {
18430                // Whenever an app changes, force a restorecon of its data
18431                // TODO: when user data is locked, mark that we're still dirty
18432                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18433            }
18434        }
18435    }
18436
18437    /**
18438     * Prepare app data for the given app.
18439     * <p>
18440     * Verifies that directories exist and that ownership and labeling is
18441     * correct for all installed apps. If there is an ownership mismatch, this
18442     * will try recovering system apps by wiping data; third-party app data is
18443     * left intact.
18444     */
18445    private void prepareAppData(String volumeUuid, int userId, int flags,
18446            PackageParser.Package pkg, boolean restoreconNeeded) {
18447        if (DEBUG_APP_DATA) {
18448            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18449                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18450        }
18451
18452        final String packageName = pkg.packageName;
18453        final ApplicationInfo app = pkg.applicationInfo;
18454        final int appId = UserHandle.getAppId(app.uid);
18455
18456        Preconditions.checkNotNull(app.seinfo);
18457
18458        synchronized (mInstallLock) {
18459            try {
18460                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18461                        appId, app.seinfo, app.targetSdkVersion);
18462            } catch (InstallerException e) {
18463                if (app.isSystemApp()) {
18464                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18465                            + ", but trying to recover: " + e);
18466                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18467                    try {
18468                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18469                                appId, app.seinfo, app.targetSdkVersion);
18470                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18471                    } catch (InstallerException e2) {
18472                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18473                    }
18474                } else {
18475                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18476                }
18477            }
18478
18479            if (restoreconNeeded) {
18480                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18481            }
18482
18483            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18484                // Create a native library symlink only if we have native libraries
18485                // and if the native libraries are 32 bit libraries. We do not provide
18486                // this symlink for 64 bit libraries.
18487                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18488                    final String nativeLibPath = app.nativeLibraryDir;
18489                    try {
18490                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18491                                nativeLibPath, userId);
18492                    } catch (InstallerException e) {
18493                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18494                    }
18495                }
18496            }
18497        }
18498    }
18499
18500    /**
18501     * For system apps on non-FBE devices, this method migrates any existing
18502     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18503     * requested by the app.
18504     */
18505    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18506        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18507                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18508            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18509                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18510            synchronized (mInstallLock) {
18511                try {
18512                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18513                } catch (InstallerException e) {
18514                    logCriticalInfo(Log.WARN,
18515                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18516                }
18517            }
18518            return true;
18519        } else {
18520            return false;
18521        }
18522    }
18523
18524    private void unfreezePackage(String packageName) {
18525        synchronized (mPackages) {
18526            final PackageSetting ps = mSettings.mPackages.get(packageName);
18527            if (ps != null) {
18528                ps.frozen = false;
18529            }
18530        }
18531    }
18532
18533    @Override
18534    public int movePackage(final String packageName, final String volumeUuid) {
18535        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18536
18537        final int moveId = mNextMoveId.getAndIncrement();
18538        mHandler.post(new Runnable() {
18539            @Override
18540            public void run() {
18541                try {
18542                    movePackageInternal(packageName, volumeUuid, moveId);
18543                } catch (PackageManagerException e) {
18544                    Slog.w(TAG, "Failed to move " + packageName, e);
18545                    mMoveCallbacks.notifyStatusChanged(moveId,
18546                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18547                }
18548            }
18549        });
18550        return moveId;
18551    }
18552
18553    private void movePackageInternal(final String packageName, final String volumeUuid,
18554            final int moveId) throws PackageManagerException {
18555        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18556        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18557        final PackageManager pm = mContext.getPackageManager();
18558
18559        final boolean currentAsec;
18560        final String currentVolumeUuid;
18561        final File codeFile;
18562        final String installerPackageName;
18563        final String packageAbiOverride;
18564        final int appId;
18565        final String seinfo;
18566        final String label;
18567        final int targetSdkVersion;
18568
18569        // reader
18570        synchronized (mPackages) {
18571            final PackageParser.Package pkg = mPackages.get(packageName);
18572            final PackageSetting ps = mSettings.mPackages.get(packageName);
18573            if (pkg == null || ps == null) {
18574                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18575            }
18576
18577            if (pkg.applicationInfo.isSystemApp()) {
18578                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18579                        "Cannot move system application");
18580            }
18581
18582            if (pkg.applicationInfo.isExternalAsec()) {
18583                currentAsec = true;
18584                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18585            } else if (pkg.applicationInfo.isForwardLocked()) {
18586                currentAsec = true;
18587                currentVolumeUuid = "forward_locked";
18588            } else {
18589                currentAsec = false;
18590                currentVolumeUuid = ps.volumeUuid;
18591
18592                final File probe = new File(pkg.codePath);
18593                final File probeOat = new File(probe, "oat");
18594                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18595                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18596                            "Move only supported for modern cluster style installs");
18597                }
18598            }
18599
18600            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18601                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18602                        "Package already moved to " + volumeUuid);
18603            }
18604            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18605                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18606                        "Device admin cannot be moved");
18607            }
18608
18609            if (ps.frozen) {
18610                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18611                        "Failed to move already frozen package");
18612            }
18613            ps.frozen = true;
18614
18615            codeFile = new File(pkg.codePath);
18616            installerPackageName = ps.installerPackageName;
18617            packageAbiOverride = ps.cpuAbiOverrideString;
18618            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18619            seinfo = pkg.applicationInfo.seinfo;
18620            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18621            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18622        }
18623
18624        // Now that we're guarded by frozen state, kill app during move
18625        final long token = Binder.clearCallingIdentity();
18626        try {
18627            killApplication(packageName, appId, "move pkg");
18628        } finally {
18629            Binder.restoreCallingIdentity(token);
18630        }
18631
18632        final Bundle extras = new Bundle();
18633        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18634        extras.putString(Intent.EXTRA_TITLE, label);
18635        mMoveCallbacks.notifyCreated(moveId, extras);
18636
18637        int installFlags;
18638        final boolean moveCompleteApp;
18639        final File measurePath;
18640
18641        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18642            installFlags = INSTALL_INTERNAL;
18643            moveCompleteApp = !currentAsec;
18644            measurePath = Environment.getDataAppDirectory(volumeUuid);
18645        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18646            installFlags = INSTALL_EXTERNAL;
18647            moveCompleteApp = false;
18648            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18649        } else {
18650            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18651            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18652                    || !volume.isMountedWritable()) {
18653                unfreezePackage(packageName);
18654                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18655                        "Move location not mounted private volume");
18656            }
18657
18658            Preconditions.checkState(!currentAsec);
18659
18660            installFlags = INSTALL_INTERNAL;
18661            moveCompleteApp = true;
18662            measurePath = Environment.getDataAppDirectory(volumeUuid);
18663        }
18664
18665        final PackageStats stats = new PackageStats(null, -1);
18666        synchronized (mInstaller) {
18667            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18668                unfreezePackage(packageName);
18669                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18670                        "Failed to measure package size");
18671            }
18672        }
18673
18674        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18675                + stats.dataSize);
18676
18677        final long startFreeBytes = measurePath.getFreeSpace();
18678        final long sizeBytes;
18679        if (moveCompleteApp) {
18680            sizeBytes = stats.codeSize + stats.dataSize;
18681        } else {
18682            sizeBytes = stats.codeSize;
18683        }
18684
18685        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18686            unfreezePackage(packageName);
18687            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18688                    "Not enough free space to move");
18689        }
18690
18691        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18692
18693        final CountDownLatch installedLatch = new CountDownLatch(1);
18694        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18695            @Override
18696            public void onUserActionRequired(Intent intent) throws RemoteException {
18697                throw new IllegalStateException();
18698            }
18699
18700            @Override
18701            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18702                    Bundle extras) throws RemoteException {
18703                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18704                        + PackageManager.installStatusToString(returnCode, msg));
18705
18706                installedLatch.countDown();
18707
18708                // Regardless of success or failure of the move operation,
18709                // always unfreeze the package
18710                unfreezePackage(packageName);
18711
18712                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18713                switch (status) {
18714                    case PackageInstaller.STATUS_SUCCESS:
18715                        mMoveCallbacks.notifyStatusChanged(moveId,
18716                                PackageManager.MOVE_SUCCEEDED);
18717                        break;
18718                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18719                        mMoveCallbacks.notifyStatusChanged(moveId,
18720                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18721                        break;
18722                    default:
18723                        mMoveCallbacks.notifyStatusChanged(moveId,
18724                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18725                        break;
18726                }
18727            }
18728        };
18729
18730        final MoveInfo move;
18731        if (moveCompleteApp) {
18732            // Kick off a thread to report progress estimates
18733            new Thread() {
18734                @Override
18735                public void run() {
18736                    while (true) {
18737                        try {
18738                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18739                                break;
18740                            }
18741                        } catch (InterruptedException ignored) {
18742                        }
18743
18744                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18745                        final int progress = 10 + (int) MathUtils.constrain(
18746                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18747                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18748                    }
18749                }
18750            }.start();
18751
18752            final String dataAppName = codeFile.getName();
18753            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18754                    dataAppName, appId, seinfo, targetSdkVersion);
18755        } else {
18756            move = null;
18757        }
18758
18759        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18760
18761        final Message msg = mHandler.obtainMessage(INIT_COPY);
18762        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18763        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18764                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18765                packageAbiOverride, null);
18766        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18767        msg.obj = params;
18768
18769        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18770                System.identityHashCode(msg.obj));
18771        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18772                System.identityHashCode(msg.obj));
18773
18774        mHandler.sendMessage(msg);
18775    }
18776
18777    @Override
18778    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18779        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18780
18781        final int realMoveId = mNextMoveId.getAndIncrement();
18782        final Bundle extras = new Bundle();
18783        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18784        mMoveCallbacks.notifyCreated(realMoveId, extras);
18785
18786        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18787            @Override
18788            public void onCreated(int moveId, Bundle extras) {
18789                // Ignored
18790            }
18791
18792            @Override
18793            public void onStatusChanged(int moveId, int status, long estMillis) {
18794                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18795            }
18796        };
18797
18798        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18799        storage.setPrimaryStorageUuid(volumeUuid, callback);
18800        return realMoveId;
18801    }
18802
18803    @Override
18804    public int getMoveStatus(int moveId) {
18805        mContext.enforceCallingOrSelfPermission(
18806                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18807        return mMoveCallbacks.mLastStatus.get(moveId);
18808    }
18809
18810    @Override
18811    public void registerMoveCallback(IPackageMoveObserver callback) {
18812        mContext.enforceCallingOrSelfPermission(
18813                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18814        mMoveCallbacks.register(callback);
18815    }
18816
18817    @Override
18818    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18819        mContext.enforceCallingOrSelfPermission(
18820                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18821        mMoveCallbacks.unregister(callback);
18822    }
18823
18824    @Override
18825    public boolean setInstallLocation(int loc) {
18826        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18827                null);
18828        if (getInstallLocation() == loc) {
18829            return true;
18830        }
18831        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18832                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18833            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18834                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18835            return true;
18836        }
18837        return false;
18838   }
18839
18840    @Override
18841    public int getInstallLocation() {
18842        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18843                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18844                PackageHelper.APP_INSTALL_AUTO);
18845    }
18846
18847    /** Called by UserManagerService */
18848    void cleanUpUser(UserManagerService userManager, int userHandle) {
18849        synchronized (mPackages) {
18850            mDirtyUsers.remove(userHandle);
18851            mUserNeedsBadging.delete(userHandle);
18852            mSettings.removeUserLPw(userHandle);
18853            mPendingBroadcasts.remove(userHandle);
18854            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18855        }
18856        synchronized (mInstallLock) {
18857            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18858            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18859                final String volumeUuid = vol.getFsUuid();
18860                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18861                try {
18862                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18863                } catch (InstallerException e) {
18864                    Slog.w(TAG, "Failed to remove user data", e);
18865                }
18866            }
18867            synchronized (mPackages) {
18868                removeUnusedPackagesLILPw(userManager, userHandle);
18869            }
18870        }
18871    }
18872
18873    /**
18874     * We're removing userHandle and would like to remove any downloaded packages
18875     * that are no longer in use by any other user.
18876     * @param userHandle the user being removed
18877     */
18878    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18879        final boolean DEBUG_CLEAN_APKS = false;
18880        int [] users = userManager.getUserIds();
18881        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18882        while (psit.hasNext()) {
18883            PackageSetting ps = psit.next();
18884            if (ps.pkg == null) {
18885                continue;
18886            }
18887            final String packageName = ps.pkg.packageName;
18888            // Skip over if system app
18889            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18890                continue;
18891            }
18892            if (DEBUG_CLEAN_APKS) {
18893                Slog.i(TAG, "Checking package " + packageName);
18894            }
18895            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18896            if (keep) {
18897                if (DEBUG_CLEAN_APKS) {
18898                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18899                }
18900            } else {
18901                for (int i = 0; i < users.length; i++) {
18902                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18903                        keep = true;
18904                        if (DEBUG_CLEAN_APKS) {
18905                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18906                                    + users[i]);
18907                        }
18908                        break;
18909                    }
18910                }
18911            }
18912            if (!keep) {
18913                if (DEBUG_CLEAN_APKS) {
18914                    Slog.i(TAG, "  Removing package " + packageName);
18915                }
18916                mHandler.post(new Runnable() {
18917                    public void run() {
18918                        deletePackageX(packageName, userHandle, 0);
18919                    } //end run
18920                });
18921            }
18922        }
18923    }
18924
18925    /** Called by UserManagerService */
18926    void createNewUser(int userHandle) {
18927        synchronized (mInstallLock) {
18928            try {
18929                mInstaller.createUserConfig(userHandle);
18930            } catch (InstallerException e) {
18931                Slog.w(TAG, "Failed to create user config", e);
18932            }
18933            mSettings.createNewUserLI(this, mInstaller, userHandle);
18934        }
18935        synchronized (mPackages) {
18936            applyFactoryDefaultBrowserLPw(userHandle);
18937            primeDomainVerificationsLPw(userHandle);
18938        }
18939    }
18940
18941    void newUserCreated(final int userHandle) {
18942        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18943        // If permission review for legacy apps is required, we represent
18944        // dagerous permissions for such apps as always granted runtime
18945        // permissions to keep per user flag state whether review is needed.
18946        // Hence, if a new user is added we have to propagate dangerous
18947        // permission grants for these legacy apps.
18948        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18949            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18950                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18951        }
18952    }
18953
18954    @Override
18955    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18956        mContext.enforceCallingOrSelfPermission(
18957                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18958                "Only package verification agents can read the verifier device identity");
18959
18960        synchronized (mPackages) {
18961            return mSettings.getVerifierDeviceIdentityLPw();
18962        }
18963    }
18964
18965    @Override
18966    public void setPermissionEnforced(String permission, boolean enforced) {
18967        // TODO: Now that we no longer change GID for storage, this should to away.
18968        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18969                "setPermissionEnforced");
18970        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18971            synchronized (mPackages) {
18972                if (mSettings.mReadExternalStorageEnforced == null
18973                        || mSettings.mReadExternalStorageEnforced != enforced) {
18974                    mSettings.mReadExternalStorageEnforced = enforced;
18975                    mSettings.writeLPr();
18976                }
18977            }
18978            // kill any non-foreground processes so we restart them and
18979            // grant/revoke the GID.
18980            final IActivityManager am = ActivityManagerNative.getDefault();
18981            if (am != null) {
18982                final long token = Binder.clearCallingIdentity();
18983                try {
18984                    am.killProcessesBelowForeground("setPermissionEnforcement");
18985                } catch (RemoteException e) {
18986                } finally {
18987                    Binder.restoreCallingIdentity(token);
18988                }
18989            }
18990        } else {
18991            throw new IllegalArgumentException("No selective enforcement for " + permission);
18992        }
18993    }
18994
18995    @Override
18996    @Deprecated
18997    public boolean isPermissionEnforced(String permission) {
18998        return true;
18999    }
19000
19001    @Override
19002    public boolean isStorageLow() {
19003        final long token = Binder.clearCallingIdentity();
19004        try {
19005            final DeviceStorageMonitorInternal
19006                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19007            if (dsm != null) {
19008                return dsm.isMemoryLow();
19009            } else {
19010                return false;
19011            }
19012        } finally {
19013            Binder.restoreCallingIdentity(token);
19014        }
19015    }
19016
19017    @Override
19018    public IPackageInstaller getPackageInstaller() {
19019        return mInstallerService;
19020    }
19021
19022    private boolean userNeedsBadging(int userId) {
19023        int index = mUserNeedsBadging.indexOfKey(userId);
19024        if (index < 0) {
19025            final UserInfo userInfo;
19026            final long token = Binder.clearCallingIdentity();
19027            try {
19028                userInfo = sUserManager.getUserInfo(userId);
19029            } finally {
19030                Binder.restoreCallingIdentity(token);
19031            }
19032            final boolean b;
19033            if (userInfo != null && userInfo.isManagedProfile()) {
19034                b = true;
19035            } else {
19036                b = false;
19037            }
19038            mUserNeedsBadging.put(userId, b);
19039            return b;
19040        }
19041        return mUserNeedsBadging.valueAt(index);
19042    }
19043
19044    @Override
19045    public KeySet getKeySetByAlias(String packageName, String alias) {
19046        if (packageName == null || alias == null) {
19047            return null;
19048        }
19049        synchronized(mPackages) {
19050            final PackageParser.Package pkg = mPackages.get(packageName);
19051            if (pkg == null) {
19052                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19053                throw new IllegalArgumentException("Unknown package: " + packageName);
19054            }
19055            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19056            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19057        }
19058    }
19059
19060    @Override
19061    public KeySet getSigningKeySet(String packageName) {
19062        if (packageName == null) {
19063            return null;
19064        }
19065        synchronized(mPackages) {
19066            final PackageParser.Package pkg = mPackages.get(packageName);
19067            if (pkg == null) {
19068                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19069                throw new IllegalArgumentException("Unknown package: " + packageName);
19070            }
19071            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19072                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19073                throw new SecurityException("May not access signing KeySet of other apps.");
19074            }
19075            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19076            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19077        }
19078    }
19079
19080    @Override
19081    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19082        if (packageName == null || ks == null) {
19083            return false;
19084        }
19085        synchronized(mPackages) {
19086            final PackageParser.Package pkg = mPackages.get(packageName);
19087            if (pkg == null) {
19088                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19089                throw new IllegalArgumentException("Unknown package: " + packageName);
19090            }
19091            IBinder ksh = ks.getToken();
19092            if (ksh instanceof KeySetHandle) {
19093                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19094                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19095            }
19096            return false;
19097        }
19098    }
19099
19100    @Override
19101    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19102        if (packageName == null || ks == null) {
19103            return false;
19104        }
19105        synchronized(mPackages) {
19106            final PackageParser.Package pkg = mPackages.get(packageName);
19107            if (pkg == null) {
19108                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19109                throw new IllegalArgumentException("Unknown package: " + packageName);
19110            }
19111            IBinder ksh = ks.getToken();
19112            if (ksh instanceof KeySetHandle) {
19113                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19114                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19115            }
19116            return false;
19117        }
19118    }
19119
19120    private void deletePackageIfUnusedLPr(final String packageName) {
19121        PackageSetting ps = mSettings.mPackages.get(packageName);
19122        if (ps == null) {
19123            return;
19124        }
19125        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19126            // TODO Implement atomic delete if package is unused
19127            // It is currently possible that the package will be deleted even if it is installed
19128            // after this method returns.
19129            mHandler.post(new Runnable() {
19130                public void run() {
19131                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19132                }
19133            });
19134        }
19135    }
19136
19137    /**
19138     * Check and throw if the given before/after packages would be considered a
19139     * downgrade.
19140     */
19141    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19142            throws PackageManagerException {
19143        if (after.versionCode < before.mVersionCode) {
19144            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19145                    "Update version code " + after.versionCode + " is older than current "
19146                    + before.mVersionCode);
19147        } else if (after.versionCode == before.mVersionCode) {
19148            if (after.baseRevisionCode < before.baseRevisionCode) {
19149                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19150                        "Update base revision code " + after.baseRevisionCode
19151                        + " is older than current " + before.baseRevisionCode);
19152            }
19153
19154            if (!ArrayUtils.isEmpty(after.splitNames)) {
19155                for (int i = 0; i < after.splitNames.length; i++) {
19156                    final String splitName = after.splitNames[i];
19157                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19158                    if (j != -1) {
19159                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19160                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19161                                    "Update split " + splitName + " revision code "
19162                                    + after.splitRevisionCodes[i] + " is older than current "
19163                                    + before.splitRevisionCodes[j]);
19164                        }
19165                    }
19166                }
19167            }
19168        }
19169    }
19170
19171    private static class MoveCallbacks extends Handler {
19172        private static final int MSG_CREATED = 1;
19173        private static final int MSG_STATUS_CHANGED = 2;
19174
19175        private final RemoteCallbackList<IPackageMoveObserver>
19176                mCallbacks = new RemoteCallbackList<>();
19177
19178        private final SparseIntArray mLastStatus = new SparseIntArray();
19179
19180        public MoveCallbacks(Looper looper) {
19181            super(looper);
19182        }
19183
19184        public void register(IPackageMoveObserver callback) {
19185            mCallbacks.register(callback);
19186        }
19187
19188        public void unregister(IPackageMoveObserver callback) {
19189            mCallbacks.unregister(callback);
19190        }
19191
19192        @Override
19193        public void handleMessage(Message msg) {
19194            final SomeArgs args = (SomeArgs) msg.obj;
19195            final int n = mCallbacks.beginBroadcast();
19196            for (int i = 0; i < n; i++) {
19197                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19198                try {
19199                    invokeCallback(callback, msg.what, args);
19200                } catch (RemoteException ignored) {
19201                }
19202            }
19203            mCallbacks.finishBroadcast();
19204            args.recycle();
19205        }
19206
19207        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19208                throws RemoteException {
19209            switch (what) {
19210                case MSG_CREATED: {
19211                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19212                    break;
19213                }
19214                case MSG_STATUS_CHANGED: {
19215                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19216                    break;
19217                }
19218            }
19219        }
19220
19221        private void notifyCreated(int moveId, Bundle extras) {
19222            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19223
19224            final SomeArgs args = SomeArgs.obtain();
19225            args.argi1 = moveId;
19226            args.arg2 = extras;
19227            obtainMessage(MSG_CREATED, args).sendToTarget();
19228        }
19229
19230        private void notifyStatusChanged(int moveId, int status) {
19231            notifyStatusChanged(moveId, status, -1);
19232        }
19233
19234        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19235            Slog.v(TAG, "Move " + moveId + " status " + status);
19236
19237            final SomeArgs args = SomeArgs.obtain();
19238            args.argi1 = moveId;
19239            args.argi2 = status;
19240            args.arg3 = estMillis;
19241            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19242
19243            synchronized (mLastStatus) {
19244                mLastStatus.put(moveId, status);
19245            }
19246        }
19247    }
19248
19249    private final static class OnPermissionChangeListeners extends Handler {
19250        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19251
19252        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19253                new RemoteCallbackList<>();
19254
19255        public OnPermissionChangeListeners(Looper looper) {
19256            super(looper);
19257        }
19258
19259        @Override
19260        public void handleMessage(Message msg) {
19261            switch (msg.what) {
19262                case MSG_ON_PERMISSIONS_CHANGED: {
19263                    final int uid = msg.arg1;
19264                    handleOnPermissionsChanged(uid);
19265                } break;
19266            }
19267        }
19268
19269        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19270            mPermissionListeners.register(listener);
19271
19272        }
19273
19274        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19275            mPermissionListeners.unregister(listener);
19276        }
19277
19278        public void onPermissionsChanged(int uid) {
19279            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19280                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19281            }
19282        }
19283
19284        private void handleOnPermissionsChanged(int uid) {
19285            final int count = mPermissionListeners.beginBroadcast();
19286            try {
19287                for (int i = 0; i < count; i++) {
19288                    IOnPermissionsChangeListener callback = mPermissionListeners
19289                            .getBroadcastItem(i);
19290                    try {
19291                        callback.onPermissionsChanged(uid);
19292                    } catch (RemoteException e) {
19293                        Log.e(TAG, "Permission listener is dead", e);
19294                    }
19295                }
19296            } finally {
19297                mPermissionListeners.finishBroadcast();
19298            }
19299        }
19300    }
19301
19302    private class PackageManagerInternalImpl extends PackageManagerInternal {
19303        @Override
19304        public void setLocationPackagesProvider(PackagesProvider provider) {
19305            synchronized (mPackages) {
19306                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19307            }
19308        }
19309
19310        @Override
19311        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19312            synchronized (mPackages) {
19313                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19314            }
19315        }
19316
19317        @Override
19318        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19319            synchronized (mPackages) {
19320                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19321            }
19322        }
19323
19324        @Override
19325        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19326            synchronized (mPackages) {
19327                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19328            }
19329        }
19330
19331        @Override
19332        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19333            synchronized (mPackages) {
19334                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19335            }
19336        }
19337
19338        @Override
19339        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19340            synchronized (mPackages) {
19341                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19342            }
19343        }
19344
19345        @Override
19346        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19347            synchronized (mPackages) {
19348                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19349                        packageName, userId);
19350            }
19351        }
19352
19353        @Override
19354        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19355            synchronized (mPackages) {
19356                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19357                        packageName, userId);
19358            }
19359        }
19360
19361        @Override
19362        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19363            synchronized (mPackages) {
19364                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19365                        packageName, userId);
19366            }
19367        }
19368
19369        @Override
19370        public void setKeepUninstalledPackages(final List<String> packageList) {
19371            Preconditions.checkNotNull(packageList);
19372            List<String> removedFromList = null;
19373            synchronized (mPackages) {
19374                if (mKeepUninstalledPackages != null) {
19375                    final int packagesCount = mKeepUninstalledPackages.size();
19376                    for (int i = 0; i < packagesCount; i++) {
19377                        String oldPackage = mKeepUninstalledPackages.get(i);
19378                        if (packageList != null && packageList.contains(oldPackage)) {
19379                            continue;
19380                        }
19381                        if (removedFromList == null) {
19382                            removedFromList = new ArrayList<>();
19383                        }
19384                        removedFromList.add(oldPackage);
19385                    }
19386                }
19387                mKeepUninstalledPackages = new ArrayList<>(packageList);
19388                if (removedFromList != null) {
19389                    final int removedCount = removedFromList.size();
19390                    for (int i = 0; i < removedCount; i++) {
19391                        deletePackageIfUnusedLPr(removedFromList.get(i));
19392                    }
19393                }
19394            }
19395        }
19396
19397        @Override
19398        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19399            synchronized (mPackages) {
19400                // If we do not support permission review, done.
19401                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19402                    return false;
19403                }
19404
19405                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19406                if (packageSetting == null) {
19407                    return false;
19408                }
19409
19410                // Permission review applies only to apps not supporting the new permission model.
19411                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19412                    return false;
19413                }
19414
19415                // Legacy apps have the permission and get user consent on launch.
19416                PermissionsState permissionsState = packageSetting.getPermissionsState();
19417                return permissionsState.isPermissionReviewRequired(userId);
19418            }
19419        }
19420
19421        @Override
19422        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19423            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19424        }
19425
19426        @Override
19427        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19428                int userId) {
19429            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19430        }
19431    }
19432
19433    @Override
19434    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19435        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19436        synchronized (mPackages) {
19437            final long identity = Binder.clearCallingIdentity();
19438            try {
19439                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19440                        packageNames, userId);
19441            } finally {
19442                Binder.restoreCallingIdentity(identity);
19443            }
19444        }
19445    }
19446
19447    private static void enforceSystemOrPhoneCaller(String tag) {
19448        int callingUid = Binder.getCallingUid();
19449        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19450            throw new SecurityException(
19451                    "Cannot call " + tag + " from UID " + callingUid);
19452        }
19453    }
19454
19455    boolean isHistoricalPackageUsageAvailable() {
19456        return mPackageUsage.isHistoricalPackageUsageAvailable();
19457    }
19458
19459    /**
19460     * Return a <b>copy</b> of the collection of packages known to the package manager.
19461     * @return A copy of the values of mPackages.
19462     */
19463    Collection<PackageParser.Package> getPackages() {
19464        synchronized (mPackages) {
19465            return new ArrayList<>(mPackages.values());
19466        }
19467    }
19468
19469    /**
19470     * Logs process start information (including base APK hash) to the security log.
19471     * @hide
19472     */
19473    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
19474            String apkFile, int pid) {
19475        if (!SecurityLog.isLoggingEnabled()) {
19476            return;
19477        }
19478        Bundle data = new Bundle();
19479        data.putLong("startTimestamp", System.currentTimeMillis());
19480        data.putString("processName", processName);
19481        data.putInt("uid", uid);
19482        data.putString("seinfo", seinfo);
19483        data.putString("apkFile", apkFile);
19484        data.putInt("pid", pid);
19485        Message msg = mProcessLoggingHandler.obtainMessage(
19486                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
19487        msg.setData(data);
19488        mProcessLoggingHandler.sendMessage(msg);
19489    }
19490}
19491