PackageManagerService.java revision 7bdf3cff92d26f9a4a8b88f816f5313fe02d6a33
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
62import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
63import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
64import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
65import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
66import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
67import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
68import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
69import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
70import static android.content.pm.PackageManager.PERMISSION_DENIED;
71import static android.content.pm.PackageManager.PERMISSION_GRANTED;
72import static android.content.pm.PackageParser.isApkFile;
73import static android.os.Process.PACKAGE_INFO_GID;
74import static android.os.Process.SYSTEM_UID;
75import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
76import static android.system.OsConstants.O_CREAT;
77import static android.system.OsConstants.O_RDWR;
78import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
80import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
81import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
82import static com.android.internal.util.ArrayUtils.appendInt;
83import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
84import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
85import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
87import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
88import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
89import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
92
93import android.Manifest;
94import android.annotation.NonNull;
95import android.annotation.Nullable;
96import android.app.ActivityManager;
97import android.app.ActivityManagerNative;
98import android.app.AppGlobals;
99import android.app.IActivityManager;
100import android.app.admin.IDevicePolicyManager;
101import android.app.backup.IBackupManager;
102import android.content.BroadcastReceiver;
103import android.content.ComponentName;
104import android.content.Context;
105import android.content.IIntentReceiver;
106import android.content.Intent;
107import android.content.IntentFilter;
108import android.content.IntentSender;
109import android.content.IntentSender.SendIntentException;
110import android.content.ServiceConnection;
111import android.content.pm.ActivityInfo;
112import android.content.pm.ApplicationInfo;
113import android.content.pm.AppsQueryHelper;
114import android.content.pm.ComponentInfo;
115import android.content.pm.EphemeralApplicationInfo;
116import android.content.pm.EphemeralResolveInfo;
117import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
118import android.content.pm.FeatureInfo;
119import android.content.pm.IOnPermissionsChangeListener;
120import android.content.pm.IPackageDataObserver;
121import android.content.pm.IPackageDeleteObserver;
122import android.content.pm.IPackageDeleteObserver2;
123import android.content.pm.IPackageInstallObserver2;
124import android.content.pm.IPackageInstaller;
125import android.content.pm.IPackageManager;
126import android.content.pm.IPackageMoveObserver;
127import android.content.pm.IPackageStatsObserver;
128import android.content.pm.InstrumentationInfo;
129import android.content.pm.IntentFilterVerificationInfo;
130import android.content.pm.KeySet;
131import android.content.pm.PackageCleanItem;
132import android.content.pm.PackageInfo;
133import android.content.pm.PackageInfoLite;
134import android.content.pm.PackageInstaller;
135import android.content.pm.PackageManager;
136import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
137import android.content.pm.PackageManagerInternal;
138import android.content.pm.PackageParser;
139import android.content.pm.PackageParser.ActivityIntentInfo;
140import android.content.pm.PackageParser.PackageLite;
141import android.content.pm.PackageParser.PackageParserException;
142import android.content.pm.PackageStats;
143import android.content.pm.PackageUserState;
144import android.content.pm.ParceledListSlice;
145import android.content.pm.PermissionGroupInfo;
146import android.content.pm.PermissionInfo;
147import android.content.pm.ProviderInfo;
148import android.content.pm.ResolveInfo;
149import android.content.pm.ServiceInfo;
150import android.content.pm.Signature;
151import android.content.pm.UserInfo;
152import android.content.pm.VerificationParams;
153import android.content.pm.VerifierDeviceIdentity;
154import android.content.pm.VerifierInfo;
155import android.content.res.Resources;
156import android.graphics.Bitmap;
157import android.hardware.display.DisplayManager;
158import android.net.Uri;
159import android.os.Binder;
160import android.os.Build;
161import android.os.Bundle;
162import android.os.Debug;
163import android.os.Environment;
164import android.os.Environment.UserEnvironment;
165import android.os.FileUtils;
166import android.os.Handler;
167import android.os.IBinder;
168import android.os.Looper;
169import android.os.Message;
170import android.os.Parcel;
171import android.os.ParcelFileDescriptor;
172import android.os.Process;
173import android.os.RemoteCallbackList;
174import android.os.RemoteException;
175import android.os.ResultReceiver;
176import android.os.SELinux;
177import android.os.ServiceManager;
178import android.os.SystemClock;
179import android.os.SystemProperties;
180import android.os.Trace;
181import android.os.UserHandle;
182import android.os.UserManager;
183import android.os.storage.IMountService;
184import android.os.storage.MountServiceInternal;
185import android.os.storage.StorageEventListener;
186import android.os.storage.StorageManager;
187import android.os.storage.VolumeInfo;
188import android.os.storage.VolumeRecord;
189import android.security.KeyStore;
190import android.security.SystemKeyStore;
191import android.system.ErrnoException;
192import android.system.Os;
193import android.text.TextUtils;
194import android.text.format.DateUtils;
195import android.util.ArrayMap;
196import android.util.ArraySet;
197import android.util.AtomicFile;
198import android.util.DisplayMetrics;
199import android.util.EventLog;
200import android.util.ExceptionUtils;
201import android.util.Log;
202import android.util.LogPrinter;
203import android.util.MathUtils;
204import android.util.PrintStreamPrinter;
205import android.util.Slog;
206import android.util.SparseArray;
207import android.util.SparseBooleanArray;
208import android.util.SparseIntArray;
209import android.util.Xml;
210import android.view.Display;
211
212import com.android.internal.R;
213import com.android.internal.annotations.GuardedBy;
214import com.android.internal.app.IMediaContainerService;
215import com.android.internal.app.ResolverActivity;
216import com.android.internal.content.NativeLibraryHelper;
217import com.android.internal.content.PackageHelper;
218import com.android.internal.os.IParcelFileDescriptorFactory;
219import com.android.internal.os.InstallerConnection.InstallerException;
220import com.android.internal.os.SomeArgs;
221import com.android.internal.os.Zygote;
222import com.android.internal.util.ArrayUtils;
223import com.android.internal.util.FastPrintWriter;
224import com.android.internal.util.FastXmlSerializer;
225import com.android.internal.util.IndentingPrintWriter;
226import com.android.internal.util.Preconditions;
227import com.android.internal.util.XmlUtils;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.Installer.StorageFlags;
236import com.android.server.pm.PermissionsState.PermissionState;
237import com.android.server.pm.Settings.DatabaseVersion;
238import com.android.server.pm.Settings.VersionInfo;
239import com.android.server.storage.DeviceStorageMonitorInternal;
240
241import dalvik.system.DexFile;
242import dalvik.system.VMRuntime;
243
244import libcore.io.IoUtils;
245import libcore.util.EmptyArray;
246
247import org.xmlpull.v1.XmlPullParser;
248import org.xmlpull.v1.XmlPullParserException;
249import org.xmlpull.v1.XmlSerializer;
250
251import java.io.BufferedInputStream;
252import java.io.BufferedOutputStream;
253import java.io.BufferedReader;
254import java.io.ByteArrayInputStream;
255import java.io.ByteArrayOutputStream;
256import java.io.File;
257import java.io.FileDescriptor;
258import java.io.FileNotFoundException;
259import java.io.FileOutputStream;
260import java.io.FileReader;
261import java.io.FilenameFilter;
262import java.io.IOException;
263import java.io.InputStream;
264import java.io.PrintWriter;
265import java.nio.charset.StandardCharsets;
266import java.security.MessageDigest;
267import java.security.NoSuchAlgorithmException;
268import java.security.PublicKey;
269import java.security.cert.CertificateEncodingException;
270import java.security.cert.CertificateException;
271import java.text.SimpleDateFormat;
272import java.util.ArrayList;
273import java.util.Arrays;
274import java.util.Collection;
275import java.util.Collections;
276import java.util.Comparator;
277import java.util.Date;
278import java.util.Iterator;
279import java.util.List;
280import java.util.Map;
281import java.util.Objects;
282import java.util.Set;
283import java.util.concurrent.CountDownLatch;
284import java.util.concurrent.TimeUnit;
285import java.util.concurrent.atomic.AtomicBoolean;
286import java.util.concurrent.atomic.AtomicInteger;
287import java.util.concurrent.atomic.AtomicLong;
288
289/**
290 * Keep track of all those .apks everywhere.
291 *
292 * This is very central to the platform's security; please run the unit
293 * tests whenever making modifications here:
294 *
295runtest -c android.content.pm.PackageManagerTests frameworks-core
296 *
297 * {@hide}
298 */
299public class PackageManagerService extends IPackageManager.Stub {
300    static final String TAG = "PackageManager";
301    static final boolean DEBUG_SETTINGS = false;
302    static final boolean DEBUG_PREFERRED = false;
303    static final boolean DEBUG_UPGRADE = false;
304    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
305    private static final boolean DEBUG_BACKUP = false;
306    private static final boolean DEBUG_INSTALL = false;
307    private static final boolean DEBUG_REMOVE = false;
308    private static final boolean DEBUG_BROADCASTS = false;
309    private static final boolean DEBUG_SHOW_INFO = false;
310    private static final boolean DEBUG_PACKAGE_INFO = false;
311    private static final boolean DEBUG_INTENT_MATCHING = false;
312    private static final boolean DEBUG_PACKAGE_SCANNING = false;
313    private static final boolean DEBUG_VERIFY = false;
314    private static final boolean DEBUG_DEXOPT = false;
315    private static final boolean DEBUG_ABI_SELECTION = false;
316    private static final boolean DEBUG_EPHEMERAL = false;
317    private static final boolean DEBUG_TRIAGED_MISSING = false;
318    private static final boolean DEBUG_APP_DATA = false;
319
320    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
321
322    private static final boolean DISABLE_EPHEMERAL_APPS = true;
323
324    private static final int RADIO_UID = Process.PHONE_UID;
325    private static final int LOG_UID = Process.LOG_UID;
326    private static final int NFC_UID = Process.NFC_UID;
327    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
328    private static final int SHELL_UID = Process.SHELL_UID;
329
330    // Cap the size of permission trees that 3rd party apps can define
331    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
332
333    // Suffix used during package installation when copying/moving
334    // package apks to install directory.
335    private static final String INSTALL_PACKAGE_SUFFIX = "-";
336
337    static final int SCAN_NO_DEX = 1<<1;
338    static final int SCAN_FORCE_DEX = 1<<2;
339    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
340    static final int SCAN_NEW_INSTALL = 1<<4;
341    static final int SCAN_NO_PATHS = 1<<5;
342    static final int SCAN_UPDATE_TIME = 1<<6;
343    static final int SCAN_DEFER_DEX = 1<<7;
344    static final int SCAN_BOOTING = 1<<8;
345    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
346    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
347    static final int SCAN_REPLACING = 1<<11;
348    static final int SCAN_REQUIRE_KNOWN = 1<<12;
349    static final int SCAN_MOVE = 1<<13;
350    static final int SCAN_INITIAL = 1<<14;
351
352    static final int REMOVE_CHATTY = 1<<16;
353
354    private static final int[] EMPTY_INT_ARRAY = new int[0];
355
356    /**
357     * Timeout (in milliseconds) after which the watchdog should declare that
358     * our handler thread is wedged.  The usual default for such things is one
359     * minute but we sometimes do very lengthy I/O operations on this thread,
360     * such as installing multi-gigabyte applications, so ours needs to be longer.
361     */
362    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
363
364    /**
365     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
366     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
367     * settings entry if available, otherwise we use the hardcoded default.  If it's been
368     * more than this long since the last fstrim, we force one during the boot sequence.
369     *
370     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
371     * one gets run at the next available charging+idle time.  This final mandatory
372     * no-fstrim check kicks in only of the other scheduling criteria is never met.
373     */
374    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
375
376    /**
377     * Whether verification is enabled by default.
378     */
379    private static final boolean DEFAULT_VERIFY_ENABLE = true;
380
381    /**
382     * The default maximum time to wait for the verification agent to return in
383     * milliseconds.
384     */
385    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
386
387    /**
388     * The default response for package verification timeout.
389     *
390     * This can be either PackageManager.VERIFICATION_ALLOW or
391     * PackageManager.VERIFICATION_REJECT.
392     */
393    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
394
395    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
396
397    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
398            DEFAULT_CONTAINER_PACKAGE,
399            "com.android.defcontainer.DefaultContainerService");
400
401    private static final String KILL_APP_REASON_GIDS_CHANGED =
402            "permission grant or revoke changed gids";
403
404    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
405            "permissions revoked";
406
407    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
408
409    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
410
411    /** Permission grant: not grant the permission. */
412    private static final int GRANT_DENIED = 1;
413
414    /** Permission grant: grant the permission as an install permission. */
415    private static final int GRANT_INSTALL = 2;
416
417    /** Permission grant: grant the permission as a runtime one. */
418    private static final int GRANT_RUNTIME = 3;
419
420    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
421    private static final int GRANT_UPGRADE = 4;
422
423    /** Canonical intent used to identify what counts as a "web browser" app */
424    private static final Intent sBrowserIntent;
425    static {
426        sBrowserIntent = new Intent();
427        sBrowserIntent.setAction(Intent.ACTION_VIEW);
428        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
429        sBrowserIntent.setData(Uri.parse("http:"));
430    }
431
432    final ServiceThread mHandlerThread;
433
434    final PackageHandler mHandler;
435
436    /**
437     * Messages for {@link #mHandler} that need to wait for system ready before
438     * being dispatched.
439     */
440    private ArrayList<Message> mPostSystemReadyMessages;
441
442    final int mSdkVersion = Build.VERSION.SDK_INT;
443
444    final Context mContext;
445    final boolean mFactoryTest;
446    final boolean mOnlyCore;
447    final DisplayMetrics mMetrics;
448    final int mDefParseFlags;
449    final String[] mSeparateProcesses;
450    final boolean mIsUpgrade;
451
452    /** The location for ASEC container files on internal storage. */
453    final String mAsecInternalPath;
454
455    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
456    // LOCK HELD.  Can be called with mInstallLock held.
457    @GuardedBy("mInstallLock")
458    final Installer mInstaller;
459
460    /** Directory where installed third-party apps stored */
461    final File mAppInstallDir;
462    final File mEphemeralInstallDir;
463
464    /**
465     * Directory to which applications installed internally have their
466     * 32 bit native libraries copied.
467     */
468    private File mAppLib32InstallDir;
469
470    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
471    // apps.
472    final File mDrmAppPrivateInstallDir;
473
474    // ----------------------------------------------------------------
475
476    // Lock for state used when installing and doing other long running
477    // operations.  Methods that must be called with this lock held have
478    // the suffix "LI".
479    final Object mInstallLock = new Object();
480
481    // ----------------------------------------------------------------
482
483    // Keys are String (package name), values are Package.  This also serves
484    // as the lock for the global state.  Methods that must be called with
485    // this lock held have the prefix "LP".
486    @GuardedBy("mPackages")
487    final ArrayMap<String, PackageParser.Package> mPackages =
488            new ArrayMap<String, PackageParser.Package>();
489
490    // Tracks available target package names -> overlay package paths.
491    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
492        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
493
494    /**
495     * Tracks new system packages [received in an OTA] that we expect to
496     * find updated user-installed versions. Keys are package name, values
497     * are package location.
498     */
499    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
500
501    /**
502     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
503     */
504    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
505    /**
506     * Whether or not system app permissions should be promoted from install to runtime.
507     */
508    boolean mPromoteSystemApps;
509
510    final Settings mSettings;
511    boolean mRestoredSettings;
512
513    // System configuration read by SystemConfig.
514    final int[] mGlobalGids;
515    final SparseArray<ArraySet<String>> mSystemPermissions;
516    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
517
518    // If mac_permissions.xml was found for seinfo labeling.
519    boolean mFoundPolicyFile;
520
521    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
522
523    public static final class SharedLibraryEntry {
524        public final String path;
525        public final String apk;
526
527        SharedLibraryEntry(String _path, String _apk) {
528            path = _path;
529            apk = _apk;
530        }
531    }
532
533    // Currently known shared libraries.
534    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
535            new ArrayMap<String, SharedLibraryEntry>();
536
537    // All available activities, for your resolving pleasure.
538    final ActivityIntentResolver mActivities =
539            new ActivityIntentResolver();
540
541    // All available receivers, for your resolving pleasure.
542    final ActivityIntentResolver mReceivers =
543            new ActivityIntentResolver();
544
545    // All available services, for your resolving pleasure.
546    final ServiceIntentResolver mServices = new ServiceIntentResolver();
547
548    // All available providers, for your resolving pleasure.
549    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
550
551    // Mapping from provider base names (first directory in content URI codePath)
552    // to the provider information.
553    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
554            new ArrayMap<String, PackageParser.Provider>();
555
556    // Mapping from instrumentation class names to info about them.
557    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
558            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
559
560    // Mapping from permission names to info about them.
561    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
562            new ArrayMap<String, PackageParser.PermissionGroup>();
563
564    // Packages whose data we have transfered into another package, thus
565    // should no longer exist.
566    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
567
568    // Broadcast actions that are only available to the system.
569    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
570
571    /** List of packages waiting for verification. */
572    final SparseArray<PackageVerificationState> mPendingVerification
573            = new SparseArray<PackageVerificationState>();
574
575    /** Set of packages associated with each app op permission. */
576    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
577
578    final PackageInstallerService mInstallerService;
579
580    private final PackageDexOptimizer mPackageDexOptimizer;
581
582    private AtomicInteger mNextMoveId = new AtomicInteger();
583    private final MoveCallbacks mMoveCallbacks;
584
585    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
586
587    // Cache of users who need badging.
588    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
589
590    /** Token for keys in mPendingVerification. */
591    private int mPendingVerificationToken = 0;
592
593    volatile boolean mSystemReady;
594    volatile boolean mSafeMode;
595    volatile boolean mHasSystemUidErrors;
596
597    ApplicationInfo mAndroidApplication;
598    final ActivityInfo mResolveActivity = new ActivityInfo();
599    final ResolveInfo mResolveInfo = new ResolveInfo();
600    ComponentName mResolveComponentName;
601    PackageParser.Package mPlatformPackage;
602    ComponentName mCustomResolverComponentName;
603
604    boolean mResolverReplaced = false;
605
606    private final @Nullable ComponentName mIntentFilterVerifierComponent;
607    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
608
609    private int mIntentFilterVerificationToken = 0;
610
611    /** Component that knows whether or not an ephemeral application exists */
612    final ComponentName mEphemeralResolverComponent;
613    /** The service connection to the ephemeral resolver */
614    final EphemeralResolverConnection mEphemeralResolverConnection;
615
616    /** Component used to install ephemeral applications */
617    final ComponentName mEphemeralInstallerComponent;
618    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
619    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
620
621    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
622            = new SparseArray<IntentFilterVerificationState>();
623
624    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
625            new DefaultPermissionGrantPolicy(this);
626
627    // List of packages names to keep cached, even if they are uninstalled for all users
628    private List<String> mKeepUninstalledPackages;
629
630    private static class IFVerificationParams {
631        PackageParser.Package pkg;
632        boolean replacing;
633        int userId;
634        int verifierUid;
635
636        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
637                int _userId, int _verifierUid) {
638            pkg = _pkg;
639            replacing = _replacing;
640            userId = _userId;
641            replacing = _replacing;
642            verifierUid = _verifierUid;
643        }
644    }
645
646    private interface IntentFilterVerifier<T extends IntentFilter> {
647        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
648                                               T filter, String packageName);
649        void startVerifications(int userId);
650        void receiveVerificationResponse(int verificationId);
651    }
652
653    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
654        private Context mContext;
655        private ComponentName mIntentFilterVerifierComponent;
656        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
657
658        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
659            mContext = context;
660            mIntentFilterVerifierComponent = verifierComponent;
661        }
662
663        private String getDefaultScheme() {
664            return IntentFilter.SCHEME_HTTPS;
665        }
666
667        @Override
668        public void startVerifications(int userId) {
669            // Launch verifications requests
670            int count = mCurrentIntentFilterVerifications.size();
671            for (int n=0; n<count; n++) {
672                int verificationId = mCurrentIntentFilterVerifications.get(n);
673                final IntentFilterVerificationState ivs =
674                        mIntentFilterVerificationStates.get(verificationId);
675
676                String packageName = ivs.getPackageName();
677
678                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
679                final int filterCount = filters.size();
680                ArraySet<String> domainsSet = new ArraySet<>();
681                for (int m=0; m<filterCount; m++) {
682                    PackageParser.ActivityIntentInfo filter = filters.get(m);
683                    domainsSet.addAll(filter.getHostsList());
684                }
685                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
686                synchronized (mPackages) {
687                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
688                            packageName, domainsList) != null) {
689                        scheduleWriteSettingsLocked();
690                    }
691                }
692                sendVerificationRequest(userId, verificationId, ivs);
693            }
694            mCurrentIntentFilterVerifications.clear();
695        }
696
697        private void sendVerificationRequest(int userId, int verificationId,
698                IntentFilterVerificationState ivs) {
699
700            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
703                    verificationId);
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
706                    getDefaultScheme());
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
709                    ivs.getHostsString());
710            verificationIntent.putExtra(
711                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
712                    ivs.getPackageName());
713            verificationIntent.setComponent(mIntentFilterVerifierComponent);
714            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
715
716            UserHandle user = new UserHandle(userId);
717            mContext.sendBroadcastAsUser(verificationIntent, user);
718            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                    "Sending IntentFilter verification broadcast");
720        }
721
722        public void receiveVerificationResponse(int verificationId) {
723            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
724
725            final boolean verified = ivs.isVerified();
726
727            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
728            final int count = filters.size();
729            if (DEBUG_DOMAIN_VERIFICATION) {
730                Slog.i(TAG, "Received verification response " + verificationId
731                        + " for " + count + " filters, verified=" + verified);
732            }
733            for (int n=0; n<count; n++) {
734                PackageParser.ActivityIntentInfo filter = filters.get(n);
735                filter.setVerified(verified);
736
737                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
738                        + " verified with result:" + verified + " and hosts:"
739                        + ivs.getHostsString());
740            }
741
742            mIntentFilterVerificationStates.remove(verificationId);
743
744            final String packageName = ivs.getPackageName();
745            IntentFilterVerificationInfo ivi = null;
746
747            synchronized (mPackages) {
748                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
749            }
750            if (ivi == null) {
751                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
752                        + verificationId + " packageName:" + packageName);
753                return;
754            }
755            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
756                    "Updating IntentFilterVerificationInfo for package " + packageName
757                            +" verificationId:" + verificationId);
758
759            synchronized (mPackages) {
760                if (verified) {
761                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
762                } else {
763                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
764                }
765                scheduleWriteSettingsLocked();
766
767                final int userId = ivs.getUserId();
768                if (userId != UserHandle.USER_ALL) {
769                    final int userStatus =
770                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
771
772                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
773                    boolean needUpdate = false;
774
775                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
776                    // already been set by the User thru the Disambiguation dialog
777                    switch (userStatus) {
778                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
779                            if (verified) {
780                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
781                            } else {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
783                            }
784                            needUpdate = true;
785                            break;
786
787                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
788                            if (verified) {
789                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
790                                needUpdate = true;
791                            }
792                            break;
793
794                        default:
795                            // Nothing to do
796                    }
797
798                    if (needUpdate) {
799                        mSettings.updateIntentFilterVerificationStatusLPw(
800                                packageName, updatedStatus, userId);
801                        scheduleWritePackageRestrictionsLocked(userId);
802                    }
803                }
804            }
805        }
806
807        @Override
808        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
809                    ActivityIntentInfo filter, String packageName) {
810            if (!hasValidDomains(filter)) {
811                return false;
812            }
813            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
814            if (ivs == null) {
815                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
816                        packageName);
817            }
818            if (DEBUG_DOMAIN_VERIFICATION) {
819                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
820            }
821            ivs.addFilter(filter);
822            return true;
823        }
824
825        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
826                int userId, int verificationId, String packageName) {
827            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
828                    verifierUid, userId, packageName);
829            ivs.setPendingState();
830            synchronized (mPackages) {
831                mIntentFilterVerificationStates.append(verificationId, ivs);
832                mCurrentIntentFilterVerifications.add(verificationId);
833            }
834            return ivs;
835        }
836    }
837
838    private static boolean hasValidDomains(ActivityIntentInfo filter) {
839        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
840                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
841                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
842    }
843
844    // Set of pending broadcasts for aggregating enable/disable of components.
845    static class PendingPackageBroadcasts {
846        // for each user id, a map of <package name -> components within that package>
847        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
848
849        public PendingPackageBroadcasts() {
850            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
851        }
852
853        public ArrayList<String> get(int userId, String packageName) {
854            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
855            return packages.get(packageName);
856        }
857
858        public void put(int userId, String packageName, ArrayList<String> components) {
859            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
860            packages.put(packageName, components);
861        }
862
863        public void remove(int userId, String packageName) {
864            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
865            if (packages != null) {
866                packages.remove(packageName);
867            }
868        }
869
870        public void remove(int userId) {
871            mUidMap.remove(userId);
872        }
873
874        public int userIdCount() {
875            return mUidMap.size();
876        }
877
878        public int userIdAt(int n) {
879            return mUidMap.keyAt(n);
880        }
881
882        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
883            return mUidMap.get(userId);
884        }
885
886        public int size() {
887            // total number of pending broadcast entries across all userIds
888            int num = 0;
889            for (int i = 0; i< mUidMap.size(); i++) {
890                num += mUidMap.valueAt(i).size();
891            }
892            return num;
893        }
894
895        public void clear() {
896            mUidMap.clear();
897        }
898
899        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
900            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
901            if (map == null) {
902                map = new ArrayMap<String, ArrayList<String>>();
903                mUidMap.put(userId, map);
904            }
905            return map;
906        }
907    }
908    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
909
910    // Service Connection to remote media container service to copy
911    // package uri's from external media onto secure containers
912    // or internal storage.
913    private IMediaContainerService mContainerService = null;
914
915    static final int SEND_PENDING_BROADCAST = 1;
916    static final int MCS_BOUND = 3;
917    static final int END_COPY = 4;
918    static final int INIT_COPY = 5;
919    static final int MCS_UNBIND = 6;
920    static final int START_CLEANING_PACKAGE = 7;
921    static final int FIND_INSTALL_LOC = 8;
922    static final int POST_INSTALL = 9;
923    static final int MCS_RECONNECT = 10;
924    static final int MCS_GIVE_UP = 11;
925    static final int UPDATED_MEDIA_STATUS = 12;
926    static final int WRITE_SETTINGS = 13;
927    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
928    static final int PACKAGE_VERIFIED = 15;
929    static final int CHECK_PENDING_VERIFICATION = 16;
930    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
931    static final int INTENT_FILTER_VERIFIED = 18;
932
933    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
934
935    // Delay time in millisecs
936    static final int BROADCAST_DELAY = 10 * 1000;
937
938    static UserManagerService sUserManager;
939
940    // Stores a list of users whose package restrictions file needs to be updated
941    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
942
943    final private DefaultContainerConnection mDefContainerConn =
944            new DefaultContainerConnection();
945    class DefaultContainerConnection implements ServiceConnection {
946        public void onServiceConnected(ComponentName name, IBinder service) {
947            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
948            IMediaContainerService imcs =
949                IMediaContainerService.Stub.asInterface(service);
950            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
951        }
952
953        public void onServiceDisconnected(ComponentName name) {
954            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
955        }
956    }
957
958    // Recordkeeping of restore-after-install operations that are currently in flight
959    // between the Package Manager and the Backup Manager
960    static class PostInstallData {
961        public InstallArgs args;
962        public PackageInstalledInfo res;
963
964        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
965            args = _a;
966            res = _r;
967        }
968    }
969
970    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
971    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
972
973    // XML tags for backup/restore of various bits of state
974    private static final String TAG_PREFERRED_BACKUP = "pa";
975    private static final String TAG_DEFAULT_APPS = "da";
976    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
977
978    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
979    private static final String TAG_ALL_GRANTS = "rt-grants";
980    private static final String TAG_GRANT = "grant";
981    private static final String ATTR_PACKAGE_NAME = "pkg";
982
983    private static final String TAG_PERMISSION = "perm";
984    private static final String ATTR_PERMISSION_NAME = "name";
985    private static final String ATTR_IS_GRANTED = "g";
986    private static final String ATTR_USER_SET = "set";
987    private static final String ATTR_USER_FIXED = "fixed";
988    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
989
990    // System/policy permission grants are not backed up
991    private static final int SYSTEM_RUNTIME_GRANT_MASK =
992            FLAG_PERMISSION_POLICY_FIXED
993            | FLAG_PERMISSION_SYSTEM_FIXED
994            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
995
996    // And we back up these user-adjusted states
997    private static final int USER_RUNTIME_GRANT_MASK =
998            FLAG_PERMISSION_USER_SET
999            | FLAG_PERMISSION_USER_FIXED
1000            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1001
1002    final @Nullable String mRequiredVerifierPackage;
1003    final @Nullable String mRequiredInstallerPackage;
1004
1005    private final PackageUsage mPackageUsage = new PackageUsage();
1006
1007    private class PackageUsage {
1008        private static final int WRITE_INTERVAL
1009            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1010
1011        private final Object mFileLock = new Object();
1012        private final AtomicLong mLastWritten = new AtomicLong(0);
1013        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1014
1015        private boolean mIsHistoricalPackageUsageAvailable = true;
1016
1017        boolean isHistoricalPackageUsageAvailable() {
1018            return mIsHistoricalPackageUsageAvailable;
1019        }
1020
1021        void write(boolean force) {
1022            if (force) {
1023                writeInternal();
1024                return;
1025            }
1026            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1027                && !DEBUG_DEXOPT) {
1028                return;
1029            }
1030            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1031                new Thread("PackageUsage_DiskWriter") {
1032                    @Override
1033                    public void run() {
1034                        try {
1035                            writeInternal();
1036                        } finally {
1037                            mBackgroundWriteRunning.set(false);
1038                        }
1039                    }
1040                }.start();
1041            }
1042        }
1043
1044        private void writeInternal() {
1045            synchronized (mPackages) {
1046                synchronized (mFileLock) {
1047                    AtomicFile file = getFile();
1048                    FileOutputStream f = null;
1049                    try {
1050                        f = file.startWrite();
1051                        BufferedOutputStream out = new BufferedOutputStream(f);
1052                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1053                        StringBuilder sb = new StringBuilder();
1054                        for (PackageParser.Package pkg : mPackages.values()) {
1055                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1056                                continue;
1057                            }
1058                            sb.setLength(0);
1059                            sb.append(pkg.packageName);
1060                            sb.append(' ');
1061                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1062                            sb.append('\n');
1063                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1064                        }
1065                        out.flush();
1066                        file.finishWrite(f);
1067                    } catch (IOException e) {
1068                        if (f != null) {
1069                            file.failWrite(f);
1070                        }
1071                        Log.e(TAG, "Failed to write package usage times", e);
1072                    }
1073                }
1074            }
1075            mLastWritten.set(SystemClock.elapsedRealtime());
1076        }
1077
1078        void readLP() {
1079            synchronized (mFileLock) {
1080                AtomicFile file = getFile();
1081                BufferedInputStream in = null;
1082                try {
1083                    in = new BufferedInputStream(file.openRead());
1084                    StringBuffer sb = new StringBuffer();
1085                    while (true) {
1086                        String packageName = readToken(in, sb, ' ');
1087                        if (packageName == null) {
1088                            break;
1089                        }
1090                        String timeInMillisString = readToken(in, sb, '\n');
1091                        if (timeInMillisString == null) {
1092                            throw new IOException("Failed to find last usage time for package "
1093                                                  + packageName);
1094                        }
1095                        PackageParser.Package pkg = mPackages.get(packageName);
1096                        if (pkg == null) {
1097                            continue;
1098                        }
1099                        long timeInMillis;
1100                        try {
1101                            timeInMillis = Long.parseLong(timeInMillisString);
1102                        } catch (NumberFormatException e) {
1103                            throw new IOException("Failed to parse " + timeInMillisString
1104                                                  + " as a long.", e);
1105                        }
1106                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1107                    }
1108                } catch (FileNotFoundException expected) {
1109                    mIsHistoricalPackageUsageAvailable = false;
1110                } catch (IOException e) {
1111                    Log.w(TAG, "Failed to read package usage times", e);
1112                } finally {
1113                    IoUtils.closeQuietly(in);
1114                }
1115            }
1116            mLastWritten.set(SystemClock.elapsedRealtime());
1117        }
1118
1119        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1120                throws IOException {
1121            sb.setLength(0);
1122            while (true) {
1123                int ch = in.read();
1124                if (ch == -1) {
1125                    if (sb.length() == 0) {
1126                        return null;
1127                    }
1128                    throw new IOException("Unexpected EOF");
1129                }
1130                if (ch == endOfToken) {
1131                    return sb.toString();
1132                }
1133                sb.append((char)ch);
1134            }
1135        }
1136
1137        private AtomicFile getFile() {
1138            File dataDir = Environment.getDataDirectory();
1139            File systemDir = new File(dataDir, "system");
1140            File fname = new File(systemDir, "package-usage.list");
1141            return new AtomicFile(fname);
1142        }
1143    }
1144
1145    class PackageHandler extends Handler {
1146        private boolean mBound = false;
1147        final ArrayList<HandlerParams> mPendingInstalls =
1148            new ArrayList<HandlerParams>();
1149
1150        private boolean connectToService() {
1151            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1152                    " DefaultContainerService");
1153            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1154            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1155            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1156                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1157                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1158                mBound = true;
1159                return true;
1160            }
1161            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162            return false;
1163        }
1164
1165        private void disconnectService() {
1166            mContainerService = null;
1167            mBound = false;
1168            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1169            mContext.unbindService(mDefContainerConn);
1170            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1171        }
1172
1173        PackageHandler(Looper looper) {
1174            super(looper);
1175        }
1176
1177        public void handleMessage(Message msg) {
1178            try {
1179                doHandleMessage(msg);
1180            } finally {
1181                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1182            }
1183        }
1184
1185        void doHandleMessage(Message msg) {
1186            switch (msg.what) {
1187                case INIT_COPY: {
1188                    HandlerParams params = (HandlerParams) msg.obj;
1189                    int idx = mPendingInstalls.size();
1190                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1191                    // If a bind was already initiated we dont really
1192                    // need to do anything. The pending install
1193                    // will be processed later on.
1194                    if (!mBound) {
1195                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1196                                System.identityHashCode(mHandler));
1197                        // If this is the only one pending we might
1198                        // have to bind to the service again.
1199                        if (!connectToService()) {
1200                            Slog.e(TAG, "Failed to bind to media container service");
1201                            params.serviceError();
1202                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1203                                    System.identityHashCode(mHandler));
1204                            if (params.traceMethod != null) {
1205                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1206                                        params.traceCookie);
1207                            }
1208                            return;
1209                        } else {
1210                            // Once we bind to the service, the first
1211                            // pending request will be processed.
1212                            mPendingInstalls.add(idx, params);
1213                        }
1214                    } else {
1215                        mPendingInstalls.add(idx, params);
1216                        // Already bound to the service. Just make
1217                        // sure we trigger off processing the first request.
1218                        if (idx == 0) {
1219                            mHandler.sendEmptyMessage(MCS_BOUND);
1220                        }
1221                    }
1222                    break;
1223                }
1224                case MCS_BOUND: {
1225                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1226                    if (msg.obj != null) {
1227                        mContainerService = (IMediaContainerService) msg.obj;
1228                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1229                                System.identityHashCode(mHandler));
1230                    }
1231                    if (mContainerService == null) {
1232                        if (!mBound) {
1233                            // Something seriously wrong since we are not bound and we are not
1234                            // waiting for connection. Bail out.
1235                            Slog.e(TAG, "Cannot bind to media container service");
1236                            for (HandlerParams params : mPendingInstalls) {
1237                                // Indicate service bind error
1238                                params.serviceError();
1239                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1240                                        System.identityHashCode(params));
1241                                if (params.traceMethod != null) {
1242                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1243                                            params.traceMethod, params.traceCookie);
1244                                }
1245                                return;
1246                            }
1247                            mPendingInstalls.clear();
1248                        } else {
1249                            Slog.w(TAG, "Waiting to connect to media container service");
1250                        }
1251                    } else if (mPendingInstalls.size() > 0) {
1252                        HandlerParams params = mPendingInstalls.get(0);
1253                        if (params != null) {
1254                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1255                                    System.identityHashCode(params));
1256                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1257                            if (params.startCopy()) {
1258                                // We are done...  look for more work or to
1259                                // go idle.
1260                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1261                                        "Checking for more work or unbind...");
1262                                // Delete pending install
1263                                if (mPendingInstalls.size() > 0) {
1264                                    mPendingInstalls.remove(0);
1265                                }
1266                                if (mPendingInstalls.size() == 0) {
1267                                    if (mBound) {
1268                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1269                                                "Posting delayed MCS_UNBIND");
1270                                        removeMessages(MCS_UNBIND);
1271                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1272                                        // Unbind after a little delay, to avoid
1273                                        // continual thrashing.
1274                                        sendMessageDelayed(ubmsg, 10000);
1275                                    }
1276                                } else {
1277                                    // There are more pending requests in queue.
1278                                    // Just post MCS_BOUND message to trigger processing
1279                                    // of next pending install.
1280                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1281                                            "Posting MCS_BOUND for next work");
1282                                    mHandler.sendEmptyMessage(MCS_BOUND);
1283                                }
1284                            }
1285                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1286                        }
1287                    } else {
1288                        // Should never happen ideally.
1289                        Slog.w(TAG, "Empty queue");
1290                    }
1291                    break;
1292                }
1293                case MCS_RECONNECT: {
1294                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1295                    if (mPendingInstalls.size() > 0) {
1296                        if (mBound) {
1297                            disconnectService();
1298                        }
1299                        if (!connectToService()) {
1300                            Slog.e(TAG, "Failed to bind to media container service");
1301                            for (HandlerParams params : mPendingInstalls) {
1302                                // Indicate service bind error
1303                                params.serviceError();
1304                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1305                                        System.identityHashCode(params));
1306                            }
1307                            mPendingInstalls.clear();
1308                        }
1309                    }
1310                    break;
1311                }
1312                case MCS_UNBIND: {
1313                    // If there is no actual work left, then time to unbind.
1314                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1315
1316                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1317                        if (mBound) {
1318                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1319
1320                            disconnectService();
1321                        }
1322                    } else if (mPendingInstalls.size() > 0) {
1323                        // There are more pending requests in queue.
1324                        // Just post MCS_BOUND message to trigger processing
1325                        // of next pending install.
1326                        mHandler.sendEmptyMessage(MCS_BOUND);
1327                    }
1328
1329                    break;
1330                }
1331                case MCS_GIVE_UP: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1333                    HandlerParams params = mPendingInstalls.remove(0);
1334                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1335                            System.identityHashCode(params));
1336                    break;
1337                }
1338                case SEND_PENDING_BROADCAST: {
1339                    String packages[];
1340                    ArrayList<String> components[];
1341                    int size = 0;
1342                    int uids[];
1343                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1344                    synchronized (mPackages) {
1345                        if (mPendingBroadcasts == null) {
1346                            return;
1347                        }
1348                        size = mPendingBroadcasts.size();
1349                        if (size <= 0) {
1350                            // Nothing to be done. Just return
1351                            return;
1352                        }
1353                        packages = new String[size];
1354                        components = new ArrayList[size];
1355                        uids = new int[size];
1356                        int i = 0;  // filling out the above arrays
1357
1358                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1359                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1360                            Iterator<Map.Entry<String, ArrayList<String>>> it
1361                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1362                                            .entrySet().iterator();
1363                            while (it.hasNext() && i < size) {
1364                                Map.Entry<String, ArrayList<String>> ent = it.next();
1365                                packages[i] = ent.getKey();
1366                                components[i] = ent.getValue();
1367                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1368                                uids[i] = (ps != null)
1369                                        ? UserHandle.getUid(packageUserId, ps.appId)
1370                                        : -1;
1371                                i++;
1372                            }
1373                        }
1374                        size = i;
1375                        mPendingBroadcasts.clear();
1376                    }
1377                    // Send broadcasts
1378                    for (int i = 0; i < size; i++) {
1379                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1380                    }
1381                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1382                    break;
1383                }
1384                case START_CLEANING_PACKAGE: {
1385                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1386                    final String packageName = (String)msg.obj;
1387                    final int userId = msg.arg1;
1388                    final boolean andCode = msg.arg2 != 0;
1389                    synchronized (mPackages) {
1390                        if (userId == UserHandle.USER_ALL) {
1391                            int[] users = sUserManager.getUserIds();
1392                            for (int user : users) {
1393                                mSettings.addPackageToCleanLPw(
1394                                        new PackageCleanItem(user, packageName, andCode));
1395                            }
1396                        } else {
1397                            mSettings.addPackageToCleanLPw(
1398                                    new PackageCleanItem(userId, packageName, andCode));
1399                        }
1400                    }
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1402                    startCleaningPackages();
1403                } break;
1404                case POST_INSTALL: {
1405                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1406
1407                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1408                    mRunningInstalls.delete(msg.arg1);
1409                    boolean deleteOld = false;
1410
1411                    if (data != null) {
1412                        InstallArgs args = data.args;
1413                        PackageInstalledInfo res = data.res;
1414
1415                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1416                            final String packageName = res.pkg.applicationInfo.packageName;
1417                            res.removedInfo.sendBroadcast(false, true, false);
1418                            Bundle extras = new Bundle(1);
1419                            extras.putInt(Intent.EXTRA_UID, res.uid);
1420
1421                            // Now that we successfully installed the package, grant runtime
1422                            // permissions if requested before broadcasting the install.
1423                            if ((args.installFlags
1424                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1425                                    && res.pkg.applicationInfo.targetSdkVersion
1426                                            >= Build.VERSION_CODES.M) {
1427                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1428                                        args.installGrantPermissions);
1429                            }
1430
1431                            synchronized (mPackages) {
1432                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1433                            }
1434
1435                            // Determine the set of users who are adding this
1436                            // package for the first time vs. those who are seeing
1437                            // an update.
1438                            int[] firstUsers;
1439                            int[] updateUsers = new int[0];
1440                            if (res.origUsers == null || res.origUsers.length == 0) {
1441                                firstUsers = res.newUsers;
1442                            } else {
1443                                firstUsers = new int[0];
1444                                for (int i=0; i<res.newUsers.length; i++) {
1445                                    int user = res.newUsers[i];
1446                                    boolean isNew = true;
1447                                    for (int j=0; j<res.origUsers.length; j++) {
1448                                        if (res.origUsers[j] == user) {
1449                                            isNew = false;
1450                                            break;
1451                                        }
1452                                    }
1453                                    if (isNew) {
1454                                        int[] newFirst = new int[firstUsers.length+1];
1455                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1456                                                firstUsers.length);
1457                                        newFirst[firstUsers.length] = user;
1458                                        firstUsers = newFirst;
1459                                    } else {
1460                                        int[] newUpdate = new int[updateUsers.length+1];
1461                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1462                                                updateUsers.length);
1463                                        newUpdate[updateUsers.length] = user;
1464                                        updateUsers = newUpdate;
1465                                    }
1466                                }
1467                            }
1468                            // don't broadcast for ephemeral installs/updates
1469                            final boolean isEphemeral = isEphemeral(res.pkg);
1470                            if (!isEphemeral) {
1471                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1472                                        extras, 0 /*flags*/, null /*targetPackage*/,
1473                                        null /*finishedReceiver*/, firstUsers);
1474                            }
1475                            final boolean update = res.removedInfo.removedPackage != null;
1476                            if (update) {
1477                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1478                            }
1479                            if (!isEphemeral) {
1480                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1481                                        extras, 0 /*flags*/, null /*targetPackage*/,
1482                                        null /*finishedReceiver*/, updateUsers);
1483                            }
1484                            if (update) {
1485                                if (!isEphemeral) {
1486                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1487                                            packageName, extras, 0 /*flags*/,
1488                                            null /*targetPackage*/, null /*finishedReceiver*/,
1489                                            updateUsers);
1490                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1491                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1492                                            packageName /*targetPackage*/,
1493                                            null /*finishedReceiver*/, updateUsers);
1494                                }
1495
1496                                // treat asec-hosted packages like removable media on upgrade
1497                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1498                                    if (DEBUG_INSTALL) {
1499                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1500                                                + " is ASEC-hosted -> AVAILABLE");
1501                                    }
1502                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1503                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1504                                    pkgList.add(packageName);
1505                                    sendResourcesChangedBroadcast(true, true,
1506                                            pkgList,uidArray, null);
1507                                }
1508                            }
1509                            if (res.removedInfo.args != null) {
1510                                // Remove the replaced package's older resources safely now
1511                                deleteOld = true;
1512                            }
1513
1514
1515                            // Work that needs to happen on first install within each user
1516                            if (firstUsers.length > 0) {
1517                                for (int userId : firstUsers) {
1518                                    synchronized (mPackages) {
1519                                        // If this app is a browser and it's newly-installed for
1520                                        // some users, clear any default-browser state in those
1521                                        // users.  The app's nature doesn't depend on the user,
1522                                        // so we can just check its browser nature in any user
1523                                        // and generalize.
1524                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1525                                            mSettings.setDefaultBrowserPackageNameLPw(
1526                                                    null, userId);
1527                                        }
1528
1529                                        // We may also need to apply pending (restored) runtime
1530                                        // permission grants within these users.
1531                                        mSettings.applyPendingPermissionGrantsLPw(
1532                                                packageName, userId);
1533                                    }
1534                                }
1535                            }
1536                            // Log current value of "unknown sources" setting
1537                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1538                                getUnknownSourcesSettings());
1539                        }
1540                        // Force a gc to clear up things
1541                        Runtime.getRuntime().gc();
1542                        // We delete after a gc for applications  on sdcard.
1543                        if (deleteOld) {
1544                            synchronized (mInstallLock) {
1545                                res.removedInfo.args.doPostDeleteLI(true);
1546                            }
1547                        }
1548                        if (args.observer != null) {
1549                            try {
1550                                Bundle extras = extrasForInstallResult(res);
1551                                args.observer.onPackageInstalled(res.name, res.returnCode,
1552                                        res.returnMsg, extras);
1553                            } catch (RemoteException e) {
1554                                Slog.i(TAG, "Observer no longer exists.");
1555                            }
1556                        }
1557                        if (args.traceMethod != null) {
1558                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1559                                    args.traceCookie);
1560                        }
1561                        return;
1562                    } else {
1563                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1564                    }
1565
1566                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1567                } break;
1568                case UPDATED_MEDIA_STATUS: {
1569                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1570                    boolean reportStatus = msg.arg1 == 1;
1571                    boolean doGc = msg.arg2 == 1;
1572                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1573                    if (doGc) {
1574                        // Force a gc to clear up stale containers.
1575                        Runtime.getRuntime().gc();
1576                    }
1577                    if (msg.obj != null) {
1578                        @SuppressWarnings("unchecked")
1579                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1580                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1581                        // Unload containers
1582                        unloadAllContainers(args);
1583                    }
1584                    if (reportStatus) {
1585                        try {
1586                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1587                            PackageHelper.getMountService().finishMediaUpdate();
1588                        } catch (RemoteException e) {
1589                            Log.e(TAG, "MountService not running?");
1590                        }
1591                    }
1592                } break;
1593                case WRITE_SETTINGS: {
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        removeMessages(WRITE_SETTINGS);
1597                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1598                        mSettings.writeLPr();
1599                        mDirtyUsers.clear();
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case WRITE_PACKAGE_RESTRICTIONS: {
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1607                        for (int userId : mDirtyUsers) {
1608                            mSettings.writePackageRestrictionsLPr(userId);
1609                        }
1610                        mDirtyUsers.clear();
1611                    }
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1613                } break;
1614                case CHECK_PENDING_VERIFICATION: {
1615                    final int verificationId = msg.arg1;
1616                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1617
1618                    if ((state != null) && !state.timeoutExtended()) {
1619                        final InstallArgs args = state.getInstallArgs();
1620                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1621
1622                        Slog.i(TAG, "Verification timed out for " + originUri);
1623                        mPendingVerification.remove(verificationId);
1624
1625                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1626
1627                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1628                            Slog.i(TAG, "Continuing with installation of " + originUri);
1629                            state.setVerifierResponse(Binder.getCallingUid(),
1630                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1631                            broadcastPackageVerified(verificationId, originUri,
1632                                    PackageManager.VERIFICATION_ALLOW,
1633                                    state.getInstallArgs().getUser());
1634                            try {
1635                                ret = args.copyApk(mContainerService, true);
1636                            } catch (RemoteException e) {
1637                                Slog.e(TAG, "Could not contact the ContainerService");
1638                            }
1639                        } else {
1640                            broadcastPackageVerified(verificationId, originUri,
1641                                    PackageManager.VERIFICATION_REJECT,
1642                                    state.getInstallArgs().getUser());
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651                    break;
1652                }
1653                case PACKAGE_VERIFIED: {
1654                    final int verificationId = msg.arg1;
1655
1656                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1657                    if (state == null) {
1658                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1659                        break;
1660                    }
1661
1662                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1663
1664                    state.setVerifierResponse(response.callerUid, response.code);
1665
1666                    if (state.isVerificationComplete()) {
1667                        mPendingVerification.remove(verificationId);
1668
1669                        final InstallArgs args = state.getInstallArgs();
1670                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1671
1672                        int ret;
1673                        if (state.isInstallAllowed()) {
1674                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1675                            broadcastPackageVerified(verificationId, originUri,
1676                                    response.code, state.getInstallArgs().getUser());
1677                            try {
1678                                ret = args.copyApk(mContainerService, true);
1679                            } catch (RemoteException e) {
1680                                Slog.e(TAG, "Could not contact the ContainerService");
1681                            }
1682                        } else {
1683                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1684                        }
1685
1686                        Trace.asyncTraceEnd(
1687                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1688
1689                        processPendingInstall(args, ret);
1690                        mHandler.sendEmptyMessage(MCS_UNBIND);
1691                    }
1692
1693                    break;
1694                }
1695                case START_INTENT_FILTER_VERIFICATIONS: {
1696                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1697                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1698                            params.replacing, params.pkg);
1699                    break;
1700                }
1701                case INTENT_FILTER_VERIFIED: {
1702                    final int verificationId = msg.arg1;
1703
1704                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1705                            verificationId);
1706                    if (state == null) {
1707                        Slog.w(TAG, "Invalid IntentFilter verification token "
1708                                + verificationId + " received");
1709                        break;
1710                    }
1711
1712                    final int userId = state.getUserId();
1713
1714                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1715                            "Processing IntentFilter verification with token:"
1716                            + verificationId + " and userId:" + userId);
1717
1718                    final IntentFilterVerificationResponse response =
1719                            (IntentFilterVerificationResponse) msg.obj;
1720
1721                    state.setVerifierResponse(response.callerUid, response.code);
1722
1723                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1724                            "IntentFilter verification with token:" + verificationId
1725                            + " and userId:" + userId
1726                            + " is settings verifier response with response code:"
1727                            + response.code);
1728
1729                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1730                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1731                                + response.getFailedDomainsString());
1732                    }
1733
1734                    if (state.isVerificationComplete()) {
1735                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1736                    } else {
1737                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1738                                "IntentFilter verification with token:" + verificationId
1739                                + " was not said to be complete");
1740                    }
1741
1742                    break;
1743                }
1744            }
1745        }
1746    }
1747
1748    private StorageEventListener mStorageListener = new StorageEventListener() {
1749        @Override
1750        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1751            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1752                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1753                    final String volumeUuid = vol.getFsUuid();
1754
1755                    // Clean up any users or apps that were removed or recreated
1756                    // while this volume was missing
1757                    reconcileUsers(volumeUuid);
1758                    reconcileApps(volumeUuid);
1759
1760                    // Clean up any install sessions that expired or were
1761                    // cancelled while this volume was missing
1762                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1763
1764                    loadPrivatePackages(vol);
1765
1766                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1767                    unloadPrivatePackages(vol);
1768                }
1769            }
1770
1771            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1772                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1773                    updateExternalMediaStatus(true, false);
1774                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1775                    updateExternalMediaStatus(false, false);
1776                }
1777            }
1778        }
1779
1780        @Override
1781        public void onVolumeForgotten(String fsUuid) {
1782            if (TextUtils.isEmpty(fsUuid)) {
1783                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1784                return;
1785            }
1786
1787            // Remove any apps installed on the forgotten volume
1788            synchronized (mPackages) {
1789                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1790                for (PackageSetting ps : packages) {
1791                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1792                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1793                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1794                }
1795
1796                mSettings.onVolumeForgotten(fsUuid);
1797                mSettings.writeLPr();
1798            }
1799        }
1800    };
1801
1802    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1803            String[] grantedPermissions) {
1804        if (userId >= UserHandle.USER_SYSTEM) {
1805            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1806        } else if (userId == UserHandle.USER_ALL) {
1807            final int[] userIds;
1808            synchronized (mPackages) {
1809                userIds = UserManagerService.getInstance().getUserIds();
1810            }
1811            for (int someUserId : userIds) {
1812                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1813            }
1814        }
1815
1816        // We could have touched GID membership, so flush out packages.list
1817        synchronized (mPackages) {
1818            mSettings.writePackageListLPr();
1819        }
1820    }
1821
1822    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1823            String[] grantedPermissions) {
1824        SettingBase sb = (SettingBase) pkg.mExtras;
1825        if (sb == null) {
1826            return;
1827        }
1828
1829        PermissionsState permissionsState = sb.getPermissionsState();
1830
1831        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1832                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1833
1834        synchronized (mPackages) {
1835            for (String permission : pkg.requestedPermissions) {
1836                BasePermission bp = mSettings.mPermissions.get(permission);
1837                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1838                        && (grantedPermissions == null
1839                               || ArrayUtils.contains(grantedPermissions, permission))) {
1840                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1841                    // Installer cannot change immutable permissions.
1842                    if ((flags & immutableFlags) == 0) {
1843                        grantRuntimePermission(pkg.packageName, permission, userId);
1844                    }
1845                }
1846            }
1847        }
1848    }
1849
1850    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1851        Bundle extras = null;
1852        switch (res.returnCode) {
1853            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1854                extras = new Bundle();
1855                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1856                        res.origPermission);
1857                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1858                        res.origPackage);
1859                break;
1860            }
1861            case PackageManager.INSTALL_SUCCEEDED: {
1862                extras = new Bundle();
1863                extras.putBoolean(Intent.EXTRA_REPLACING,
1864                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1865                break;
1866            }
1867        }
1868        return extras;
1869    }
1870
1871    void scheduleWriteSettingsLocked() {
1872        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1873            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1874        }
1875    }
1876
1877    void scheduleWritePackageRestrictionsLocked(int userId) {
1878        if (!sUserManager.exists(userId)) return;
1879        mDirtyUsers.add(userId);
1880        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1881            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1882        }
1883    }
1884
1885    public static PackageManagerService main(Context context, Installer installer,
1886            boolean factoryTest, boolean onlyCore) {
1887        PackageManagerService m = new PackageManagerService(context, installer,
1888                factoryTest, onlyCore);
1889        m.enableSystemUserPackages();
1890        ServiceManager.addService("package", m);
1891        return m;
1892    }
1893
1894    private void enableSystemUserPackages() {
1895        if (!UserManager.isSplitSystemUser()) {
1896            return;
1897        }
1898        // For system user, enable apps based on the following conditions:
1899        // - app is whitelisted or belong to one of these groups:
1900        //   -- system app which has no launcher icons
1901        //   -- system app which has INTERACT_ACROSS_USERS permission
1902        //   -- system IME app
1903        // - app is not in the blacklist
1904        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1905        Set<String> enableApps = new ArraySet<>();
1906        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1907                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1908                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1909        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1910        enableApps.addAll(wlApps);
1911        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1912                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1913        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1914        enableApps.removeAll(blApps);
1915        Log.i(TAG, "Applications installed for system user: " + enableApps);
1916        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1917                UserHandle.SYSTEM);
1918        final int allAppsSize = allAps.size();
1919        synchronized (mPackages) {
1920            for (int i = 0; i < allAppsSize; i++) {
1921                String pName = allAps.get(i);
1922                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1923                // Should not happen, but we shouldn't be failing if it does
1924                if (pkgSetting == null) {
1925                    continue;
1926                }
1927                boolean install = enableApps.contains(pName);
1928                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1929                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1930                            + " for system user");
1931                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1932                }
1933            }
1934        }
1935    }
1936
1937    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1938        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1939                Context.DISPLAY_SERVICE);
1940        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1941    }
1942
1943    public PackageManagerService(Context context, Installer installer,
1944            boolean factoryTest, boolean onlyCore) {
1945        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1946                SystemClock.uptimeMillis());
1947
1948        if (mSdkVersion <= 0) {
1949            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1950        }
1951
1952        mContext = context;
1953        mFactoryTest = factoryTest;
1954        mOnlyCore = onlyCore;
1955        mMetrics = new DisplayMetrics();
1956        mSettings = new Settings(mPackages);
1957        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1958                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1959        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1960                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1961        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1962                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1963        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1964                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1965        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1966                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1967        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1968                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1969
1970        String separateProcesses = SystemProperties.get("debug.separate_processes");
1971        if (separateProcesses != null && separateProcesses.length() > 0) {
1972            if ("*".equals(separateProcesses)) {
1973                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1974                mSeparateProcesses = null;
1975                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1976            } else {
1977                mDefParseFlags = 0;
1978                mSeparateProcesses = separateProcesses.split(",");
1979                Slog.w(TAG, "Running with debug.separate_processes: "
1980                        + separateProcesses);
1981            }
1982        } else {
1983            mDefParseFlags = 0;
1984            mSeparateProcesses = null;
1985        }
1986
1987        mInstaller = installer;
1988        mPackageDexOptimizer = new PackageDexOptimizer(this);
1989        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1990
1991        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1992                FgThread.get().getLooper());
1993
1994        getDefaultDisplayMetrics(context, mMetrics);
1995
1996        SystemConfig systemConfig = SystemConfig.getInstance();
1997        mGlobalGids = systemConfig.getGlobalGids();
1998        mSystemPermissions = systemConfig.getSystemPermissions();
1999        mAvailableFeatures = systemConfig.getAvailableFeatures();
2000
2001        synchronized (mInstallLock) {
2002        // writer
2003        synchronized (mPackages) {
2004            mHandlerThread = new ServiceThread(TAG,
2005                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2006            mHandlerThread.start();
2007            mHandler = new PackageHandler(mHandlerThread.getLooper());
2008            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2009
2010            File dataDir = Environment.getDataDirectory();
2011            mAppInstallDir = new File(dataDir, "app");
2012            mAppLib32InstallDir = new File(dataDir, "app-lib");
2013            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2014            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2015            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2016
2017            sUserManager = new UserManagerService(context, this, mPackages);
2018
2019            // Propagate permission configuration in to package manager.
2020            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2021                    = systemConfig.getPermissions();
2022            for (int i=0; i<permConfig.size(); i++) {
2023                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2024                BasePermission bp = mSettings.mPermissions.get(perm.name);
2025                if (bp == null) {
2026                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2027                    mSettings.mPermissions.put(perm.name, bp);
2028                }
2029                if (perm.gids != null) {
2030                    bp.setGids(perm.gids, perm.perUser);
2031                }
2032            }
2033
2034            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2035            for (int i=0; i<libConfig.size(); i++) {
2036                mSharedLibraries.put(libConfig.keyAt(i),
2037                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2038            }
2039
2040            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2041
2042            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2043
2044            String customResolverActivity = Resources.getSystem().getString(
2045                    R.string.config_customResolverActivity);
2046            if (TextUtils.isEmpty(customResolverActivity)) {
2047                customResolverActivity = null;
2048            } else {
2049                mCustomResolverComponentName = ComponentName.unflattenFromString(
2050                        customResolverActivity);
2051            }
2052
2053            long startTime = SystemClock.uptimeMillis();
2054
2055            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2056                    startTime);
2057
2058            // Set flag to monitor and not change apk file paths when
2059            // scanning install directories.
2060            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2061
2062            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2063            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2064
2065            if (bootClassPath == null) {
2066                Slog.w(TAG, "No BOOTCLASSPATH found!");
2067            }
2068
2069            if (systemServerClassPath == null) {
2070                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2071            }
2072
2073            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2074            final String[] dexCodeInstructionSets =
2075                    getDexCodeInstructionSets(
2076                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2077
2078            /**
2079             * Ensure all external libraries have had dexopt run on them.
2080             */
2081            if (mSharedLibraries.size() > 0) {
2082                // NOTE: For now, we're compiling these system "shared libraries"
2083                // (and framework jars) into all available architectures. It's possible
2084                // to compile them only when we come across an app that uses them (there's
2085                // already logic for that in scanPackageLI) but that adds some complexity.
2086                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2087                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2088                        final String lib = libEntry.path;
2089                        if (lib == null) {
2090                            continue;
2091                        }
2092
2093                        try {
2094                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2095                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2096                                // Shared libraries do not have profiles so we perform a full
2097                                // AOT compilation.
2098                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2099                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2100                                        StorageManager.UUID_PRIVATE_INTERNAL,
2101                                        false /*useProfiles*/);
2102                            }
2103                        } catch (FileNotFoundException e) {
2104                            Slog.w(TAG, "Library not found: " + lib);
2105                        } catch (IOException | InstallerException e) {
2106                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2107                                    + e.getMessage());
2108                        }
2109                    }
2110                }
2111            }
2112
2113            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2114
2115            final VersionInfo ver = mSettings.getInternalVersion();
2116            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2117            // when upgrading from pre-M, promote system app permissions from install to runtime
2118            mPromoteSystemApps =
2119                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2120
2121            // save off the names of pre-existing system packages prior to scanning; we don't
2122            // want to automatically grant runtime permissions for new system apps
2123            if (mPromoteSystemApps) {
2124                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2125                while (pkgSettingIter.hasNext()) {
2126                    PackageSetting ps = pkgSettingIter.next();
2127                    if (isSystemApp(ps)) {
2128                        mExistingSystemPackages.add(ps.name);
2129                    }
2130                }
2131            }
2132
2133            // Collect vendor overlay packages.
2134            // (Do this before scanning any apps.)
2135            // For security and version matching reason, only consider
2136            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2137            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2138            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2139                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2140
2141            // Find base frameworks (resource packages without code).
2142            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2143                    | PackageParser.PARSE_IS_SYSTEM_DIR
2144                    | PackageParser.PARSE_IS_PRIVILEGED,
2145                    scanFlags | SCAN_NO_DEX, 0);
2146
2147            // Collected privileged system packages.
2148            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2149            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2150                    | PackageParser.PARSE_IS_SYSTEM_DIR
2151                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2152
2153            // Collect ordinary system packages.
2154            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2155            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2156                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2157
2158            // Collect all vendor packages.
2159            File vendorAppDir = new File("/vendor/app");
2160            try {
2161                vendorAppDir = vendorAppDir.getCanonicalFile();
2162            } catch (IOException e) {
2163                // failed to look up canonical path, continue with original one
2164            }
2165            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2166                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2167
2168            // Collect all OEM packages.
2169            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2170            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2171                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2172
2173            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2174            try {
2175                mInstaller.moveFiles();
2176            } catch (InstallerException e) {
2177                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2178            }
2179
2180            // Prune any system packages that no longer exist.
2181            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2182            if (!mOnlyCore) {
2183                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2184                while (psit.hasNext()) {
2185                    PackageSetting ps = psit.next();
2186
2187                    /*
2188                     * If this is not a system app, it can't be a
2189                     * disable system app.
2190                     */
2191                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2192                        continue;
2193                    }
2194
2195                    /*
2196                     * If the package is scanned, it's not erased.
2197                     */
2198                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2199                    if (scannedPkg != null) {
2200                        /*
2201                         * If the system app is both scanned and in the
2202                         * disabled packages list, then it must have been
2203                         * added via OTA. Remove it from the currently
2204                         * scanned package so the previously user-installed
2205                         * application can be scanned.
2206                         */
2207                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2208                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2209                                    + ps.name + "; removing system app.  Last known codePath="
2210                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2211                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2212                                    + scannedPkg.mVersionCode);
2213                            removePackageLI(ps, true);
2214                            mExpectingBetter.put(ps.name, ps.codePath);
2215                        }
2216
2217                        continue;
2218                    }
2219
2220                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2221                        psit.remove();
2222                        logCriticalInfo(Log.WARN, "System package " + ps.name
2223                                + " no longer exists; wiping its data");
2224                        removeDataDirsLI(null, ps.name);
2225                    } else {
2226                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2227                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2228                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2229                        }
2230                    }
2231                }
2232            }
2233
2234            //look for any incomplete package installations
2235            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2236            //clean up list
2237            for(int i = 0; i < deletePkgsList.size(); i++) {
2238                //clean up here
2239                cleanupInstallFailedPackage(deletePkgsList.get(i));
2240            }
2241            //delete tmp files
2242            deleteTempPackageFiles();
2243
2244            // Remove any shared userIDs that have no associated packages
2245            mSettings.pruneSharedUsersLPw();
2246
2247            if (!mOnlyCore) {
2248                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2249                        SystemClock.uptimeMillis());
2250                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2251
2252                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2253                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2254
2255                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2256                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2257
2258                /**
2259                 * Remove disable package settings for any updated system
2260                 * apps that were removed via an OTA. If they're not a
2261                 * previously-updated app, remove them completely.
2262                 * Otherwise, just revoke their system-level permissions.
2263                 */
2264                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2265                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2266                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2267
2268                    String msg;
2269                    if (deletedPkg == null) {
2270                        msg = "Updated system package " + deletedAppName
2271                                + " no longer exists; wiping its data";
2272                        removeDataDirsLI(null, deletedAppName);
2273                    } else {
2274                        msg = "Updated system app + " + deletedAppName
2275                                + " no longer present; removing system privileges for "
2276                                + deletedAppName;
2277
2278                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2279
2280                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2281                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2282                    }
2283                    logCriticalInfo(Log.WARN, msg);
2284                }
2285
2286                /**
2287                 * Make sure all system apps that we expected to appear on
2288                 * the userdata partition actually showed up. If they never
2289                 * appeared, crawl back and revive the system version.
2290                 */
2291                for (int i = 0; i < mExpectingBetter.size(); i++) {
2292                    final String packageName = mExpectingBetter.keyAt(i);
2293                    if (!mPackages.containsKey(packageName)) {
2294                        final File scanFile = mExpectingBetter.valueAt(i);
2295
2296                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2297                                + " but never showed up; reverting to system");
2298
2299                        final int reparseFlags;
2300                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2301                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2302                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2303                                    | PackageParser.PARSE_IS_PRIVILEGED;
2304                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2305                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2306                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2307                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2308                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2309                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2310                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2311                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2312                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2313                        } else {
2314                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2315                            continue;
2316                        }
2317
2318                        mSettings.enableSystemPackageLPw(packageName);
2319
2320                        try {
2321                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2322                        } catch (PackageManagerException e) {
2323                            Slog.e(TAG, "Failed to parse original system package: "
2324                                    + e.getMessage());
2325                        }
2326                    }
2327                }
2328            }
2329            mExpectingBetter.clear();
2330
2331            // Now that we know all of the shared libraries, update all clients to have
2332            // the correct library paths.
2333            updateAllSharedLibrariesLPw();
2334
2335            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2336                // NOTE: We ignore potential failures here during a system scan (like
2337                // the rest of the commands above) because there's precious little we
2338                // can do about it. A settings error is reported, though.
2339                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2340                        false /* boot complete */);
2341            }
2342
2343            // Now that we know all the packages we are keeping,
2344            // read and update their last usage times.
2345            mPackageUsage.readLP();
2346
2347            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2348                    SystemClock.uptimeMillis());
2349            Slog.i(TAG, "Time to scan packages: "
2350                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2351                    + " seconds");
2352
2353            // If the platform SDK has changed since the last time we booted,
2354            // we need to re-grant app permission to catch any new ones that
2355            // appear.  This is really a hack, and means that apps can in some
2356            // cases get permissions that the user didn't initially explicitly
2357            // allow...  it would be nice to have some better way to handle
2358            // this situation.
2359            int updateFlags = UPDATE_PERMISSIONS_ALL;
2360            if (ver.sdkVersion != mSdkVersion) {
2361                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2362                        + mSdkVersion + "; regranting permissions for internal storage");
2363                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2364            }
2365            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2366            ver.sdkVersion = mSdkVersion;
2367
2368            // If this is the first boot or an update from pre-M, and it is a normal
2369            // boot, then we need to initialize the default preferred apps across
2370            // all defined users.
2371            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2372                for (UserInfo user : sUserManager.getUsers(true)) {
2373                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2374                    applyFactoryDefaultBrowserLPw(user.id);
2375                    primeDomainVerificationsLPw(user.id);
2376                }
2377            }
2378
2379            // Prepare storage for system user really early during boot,
2380            // since core system apps like SettingsProvider and SystemUI
2381            // can't wait for user to start
2382            final int flags;
2383            if (StorageManager.isFileBasedEncryptionEnabled()) {
2384                flags = Installer.FLAG_DE_STORAGE;
2385            } else {
2386                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
2387            }
2388            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2389
2390            // If this is first boot after an OTA, and a normal boot, then
2391            // we need to clear code cache directories.
2392            if (mIsUpgrade && !onlyCore) {
2393                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2394                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2395                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2396                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2397                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2398                    }
2399                }
2400                ver.fingerprint = Build.FINGERPRINT;
2401            }
2402
2403            checkDefaultBrowser();
2404
2405            // clear only after permissions and other defaults have been updated
2406            mExistingSystemPackages.clear();
2407            mPromoteSystemApps = false;
2408
2409            // All the changes are done during package scanning.
2410            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2411
2412            // can downgrade to reader
2413            mSettings.writeLPr();
2414
2415            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2416                    SystemClock.uptimeMillis());
2417
2418            if (!mOnlyCore) {
2419                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2420                mRequiredInstallerPackage = getRequiredInstallerLPr();
2421                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2422                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2423                        mIntentFilterVerifierComponent);
2424            } else {
2425                mRequiredVerifierPackage = null;
2426                mRequiredInstallerPackage = null;
2427                mIntentFilterVerifierComponent = null;
2428                mIntentFilterVerifier = null;
2429            }
2430
2431            mInstallerService = new PackageInstallerService(context, this);
2432
2433            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2434            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2435            // both the installer and resolver must be present to enable ephemeral
2436            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2437                if (DEBUG_EPHEMERAL) {
2438                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2439                            + " installer:" + ephemeralInstallerComponent);
2440                }
2441                mEphemeralResolverComponent = ephemeralResolverComponent;
2442                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2443                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2444                mEphemeralResolverConnection =
2445                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2446            } else {
2447                if (DEBUG_EPHEMERAL) {
2448                    final String missingComponent =
2449                            (ephemeralResolverComponent == null)
2450                            ? (ephemeralInstallerComponent == null)
2451                                    ? "resolver and installer"
2452                                    : "resolver"
2453                            : "installer";
2454                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2455                }
2456                mEphemeralResolverComponent = null;
2457                mEphemeralInstallerComponent = null;
2458                mEphemeralResolverConnection = null;
2459            }
2460
2461            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2462        } // synchronized (mPackages)
2463        } // synchronized (mInstallLock)
2464
2465        // Now after opening every single application zip, make sure they
2466        // are all flushed.  Not really needed, but keeps things nice and
2467        // tidy.
2468        Runtime.getRuntime().gc();
2469
2470        // The initial scanning above does many calls into installd while
2471        // holding the mPackages lock, but we're mostly interested in yelling
2472        // once we have a booted system.
2473        mInstaller.setWarnIfHeld(mPackages);
2474
2475        // Expose private service for system components to use.
2476        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2477    }
2478
2479    @Override
2480    public boolean isFirstBoot() {
2481        return !mRestoredSettings;
2482    }
2483
2484    @Override
2485    public boolean isOnlyCoreApps() {
2486        return mOnlyCore;
2487    }
2488
2489    @Override
2490    public boolean isUpgrade() {
2491        return mIsUpgrade;
2492    }
2493
2494    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2495        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2496
2497        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2498                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2499        if (matches.size() == 1) {
2500            return matches.get(0).getComponentInfo().packageName;
2501        } else {
2502            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2503            return null;
2504        }
2505    }
2506
2507    private @NonNull String getRequiredInstallerLPr() {
2508        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2509        intent.addCategory(Intent.CATEGORY_DEFAULT);
2510        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2511
2512        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2513                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2514        if (matches.size() == 1) {
2515            return matches.get(0).getComponentInfo().packageName;
2516        } else {
2517            throw new RuntimeException("There must be exactly one installer; found " + matches);
2518        }
2519    }
2520
2521    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2522        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2523
2524        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2525                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2526        ResolveInfo best = null;
2527        final int N = matches.size();
2528        for (int i = 0; i < N; i++) {
2529            final ResolveInfo cur = matches.get(i);
2530            final String packageName = cur.getComponentInfo().packageName;
2531            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2532                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2533                continue;
2534            }
2535
2536            if (best == null || cur.priority > best.priority) {
2537                best = cur;
2538            }
2539        }
2540
2541        if (best != null) {
2542            return best.getComponentInfo().getComponentName();
2543        } else {
2544            throw new RuntimeException("There must be at least one intent filter verifier");
2545        }
2546    }
2547
2548    private @Nullable ComponentName getEphemeralResolverLPr() {
2549        final String[] packageArray =
2550                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2551        if (packageArray.length == 0) {
2552            if (DEBUG_EPHEMERAL) {
2553                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2554            }
2555            return null;
2556        }
2557
2558        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2559        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2560                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2561
2562        final int N = resolvers.size();
2563        if (N == 0) {
2564            if (DEBUG_EPHEMERAL) {
2565                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2566            }
2567            return null;
2568        }
2569
2570        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2571        for (int i = 0; i < N; i++) {
2572            final ResolveInfo info = resolvers.get(i);
2573
2574            if (info.serviceInfo == null) {
2575                continue;
2576            }
2577
2578            final String packageName = info.serviceInfo.packageName;
2579            if (!possiblePackages.contains(packageName)) {
2580                if (DEBUG_EPHEMERAL) {
2581                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2582                            + " pkg: " + packageName + ", info:" + info);
2583                }
2584                continue;
2585            }
2586
2587            if (DEBUG_EPHEMERAL) {
2588                Slog.v(TAG, "Ephemeral resolver found;"
2589                        + " pkg: " + packageName + ", info:" + info);
2590            }
2591            return new ComponentName(packageName, info.serviceInfo.name);
2592        }
2593        if (DEBUG_EPHEMERAL) {
2594            Slog.v(TAG, "Ephemeral resolver NOT found");
2595        }
2596        return null;
2597    }
2598
2599    private @Nullable ComponentName getEphemeralInstallerLPr() {
2600        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2601        intent.addCategory(Intent.CATEGORY_DEFAULT);
2602        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2603
2604        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2605                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2606        if (matches.size() == 0) {
2607            return null;
2608        } else if (matches.size() == 1) {
2609            return matches.get(0).getComponentInfo().getComponentName();
2610        } else {
2611            throw new RuntimeException(
2612                    "There must be at most one ephemeral installer; found " + matches);
2613        }
2614    }
2615
2616    private void primeDomainVerificationsLPw(int userId) {
2617        if (DEBUG_DOMAIN_VERIFICATION) {
2618            Slog.d(TAG, "Priming domain verifications in user " + userId);
2619        }
2620
2621        SystemConfig systemConfig = SystemConfig.getInstance();
2622        ArraySet<String> packages = systemConfig.getLinkedApps();
2623        ArraySet<String> domains = new ArraySet<String>();
2624
2625        for (String packageName : packages) {
2626            PackageParser.Package pkg = mPackages.get(packageName);
2627            if (pkg != null) {
2628                if (!pkg.isSystemApp()) {
2629                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2630                    continue;
2631                }
2632
2633                domains.clear();
2634                for (PackageParser.Activity a : pkg.activities) {
2635                    for (ActivityIntentInfo filter : a.intents) {
2636                        if (hasValidDomains(filter)) {
2637                            domains.addAll(filter.getHostsList());
2638                        }
2639                    }
2640                }
2641
2642                if (domains.size() > 0) {
2643                    if (DEBUG_DOMAIN_VERIFICATION) {
2644                        Slog.v(TAG, "      + " + packageName);
2645                    }
2646                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2647                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2648                    // and then 'always' in the per-user state actually used for intent resolution.
2649                    final IntentFilterVerificationInfo ivi;
2650                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2651                            new ArrayList<String>(domains));
2652                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2653                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2654                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2655                } else {
2656                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2657                            + "' does not handle web links");
2658                }
2659            } else {
2660                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2661            }
2662        }
2663
2664        scheduleWritePackageRestrictionsLocked(userId);
2665        scheduleWriteSettingsLocked();
2666    }
2667
2668    private void applyFactoryDefaultBrowserLPw(int userId) {
2669        // The default browser app's package name is stored in a string resource,
2670        // with a product-specific overlay used for vendor customization.
2671        String browserPkg = mContext.getResources().getString(
2672                com.android.internal.R.string.default_browser);
2673        if (!TextUtils.isEmpty(browserPkg)) {
2674            // non-empty string => required to be a known package
2675            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2676            if (ps == null) {
2677                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2678                browserPkg = null;
2679            } else {
2680                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2681            }
2682        }
2683
2684        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2685        // default.  If there's more than one, just leave everything alone.
2686        if (browserPkg == null) {
2687            calculateDefaultBrowserLPw(userId);
2688        }
2689    }
2690
2691    private void calculateDefaultBrowserLPw(int userId) {
2692        List<String> allBrowsers = resolveAllBrowserApps(userId);
2693        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2694        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2695    }
2696
2697    private List<String> resolveAllBrowserApps(int userId) {
2698        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2699        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2700                PackageManager.MATCH_ALL, userId);
2701
2702        final int count = list.size();
2703        List<String> result = new ArrayList<String>(count);
2704        for (int i=0; i<count; i++) {
2705            ResolveInfo info = list.get(i);
2706            if (info.activityInfo == null
2707                    || !info.handleAllWebDataURI
2708                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2709                    || result.contains(info.activityInfo.packageName)) {
2710                continue;
2711            }
2712            result.add(info.activityInfo.packageName);
2713        }
2714
2715        return result;
2716    }
2717
2718    private boolean packageIsBrowser(String packageName, int userId) {
2719        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2720                PackageManager.MATCH_ALL, userId);
2721        final int N = list.size();
2722        for (int i = 0; i < N; i++) {
2723            ResolveInfo info = list.get(i);
2724            if (packageName.equals(info.activityInfo.packageName)) {
2725                return true;
2726            }
2727        }
2728        return false;
2729    }
2730
2731    private void checkDefaultBrowser() {
2732        final int myUserId = UserHandle.myUserId();
2733        final String packageName = getDefaultBrowserPackageName(myUserId);
2734        if (packageName != null) {
2735            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2736            if (info == null) {
2737                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2738                synchronized (mPackages) {
2739                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2740                }
2741            }
2742        }
2743    }
2744
2745    @Override
2746    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2747            throws RemoteException {
2748        try {
2749            return super.onTransact(code, data, reply, flags);
2750        } catch (RuntimeException e) {
2751            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2752                Slog.wtf(TAG, "Package Manager Crash", e);
2753            }
2754            throw e;
2755        }
2756    }
2757
2758    void cleanupInstallFailedPackage(PackageSetting ps) {
2759        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2760
2761        removeDataDirsLI(ps.volumeUuid, ps.name);
2762        if (ps.codePath != null) {
2763            removeCodePathLI(ps.codePath);
2764        }
2765        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2766            if (ps.resourcePath.isDirectory()) {
2767                FileUtils.deleteContents(ps.resourcePath);
2768            }
2769            ps.resourcePath.delete();
2770        }
2771        mSettings.removePackageLPw(ps.name);
2772    }
2773
2774    static int[] appendInts(int[] cur, int[] add) {
2775        if (add == null) return cur;
2776        if (cur == null) return add;
2777        final int N = add.length;
2778        for (int i=0; i<N; i++) {
2779            cur = appendInt(cur, add[i]);
2780        }
2781        return cur;
2782    }
2783
2784    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2785        if (!sUserManager.exists(userId)) return null;
2786        final PackageSetting ps = (PackageSetting) p.mExtras;
2787        if (ps == null) {
2788            return null;
2789        }
2790
2791        final PermissionsState permissionsState = ps.getPermissionsState();
2792
2793        final int[] gids = permissionsState.computeGids(userId);
2794        final Set<String> permissions = permissionsState.getPermissions(userId);
2795        final PackageUserState state = ps.readUserState(userId);
2796
2797        return PackageParser.generatePackageInfo(p, gids, flags,
2798                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2799    }
2800
2801    @Override
2802    public void checkPackageStartable(String packageName, int userId) {
2803        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2804
2805        synchronized (mPackages) {
2806            final PackageSetting ps = mSettings.mPackages.get(packageName);
2807            if (ps == null) {
2808                throw new SecurityException("Package " + packageName + " was not found!");
2809            }
2810
2811            if (ps.frozen) {
2812                throw new SecurityException("Package " + packageName + " is currently frozen!");
2813            }
2814
2815            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2816                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2817                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2818            }
2819        }
2820    }
2821
2822    @Override
2823    public boolean isPackageAvailable(String packageName, int userId) {
2824        if (!sUserManager.exists(userId)) return false;
2825        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2826        synchronized (mPackages) {
2827            PackageParser.Package p = mPackages.get(packageName);
2828            if (p != null) {
2829                final PackageSetting ps = (PackageSetting) p.mExtras;
2830                if (ps != null) {
2831                    final PackageUserState state = ps.readUserState(userId);
2832                    if (state != null) {
2833                        return PackageParser.isAvailable(state);
2834                    }
2835                }
2836            }
2837        }
2838        return false;
2839    }
2840
2841    @Override
2842    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2843        if (!sUserManager.exists(userId)) return null;
2844        flags = updateFlagsForPackage(flags, userId, packageName);
2845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2846        // reader
2847        synchronized (mPackages) {
2848            PackageParser.Package p = mPackages.get(packageName);
2849            if (DEBUG_PACKAGE_INFO)
2850                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2851            if (p != null) {
2852                return generatePackageInfo(p, flags, userId);
2853            }
2854            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2855                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2856            }
2857        }
2858        return null;
2859    }
2860
2861    @Override
2862    public String[] currentToCanonicalPackageNames(String[] names) {
2863        String[] out = new String[names.length];
2864        // reader
2865        synchronized (mPackages) {
2866            for (int i=names.length-1; i>=0; i--) {
2867                PackageSetting ps = mSettings.mPackages.get(names[i]);
2868                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2869            }
2870        }
2871        return out;
2872    }
2873
2874    @Override
2875    public String[] canonicalToCurrentPackageNames(String[] names) {
2876        String[] out = new String[names.length];
2877        // reader
2878        synchronized (mPackages) {
2879            for (int i=names.length-1; i>=0; i--) {
2880                String cur = mSettings.mRenamedPackages.get(names[i]);
2881                out[i] = cur != null ? cur : names[i];
2882            }
2883        }
2884        return out;
2885    }
2886
2887    @Override
2888    public int getPackageUid(String packageName, int flags, int userId) {
2889        if (!sUserManager.exists(userId)) return -1;
2890        flags = updateFlagsForPackage(flags, userId, packageName);
2891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2892
2893        // reader
2894        synchronized (mPackages) {
2895            final PackageParser.Package p = mPackages.get(packageName);
2896            if (p != null && p.isMatch(flags)) {
2897                return UserHandle.getUid(userId, p.applicationInfo.uid);
2898            }
2899            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2900                final PackageSetting ps = mSettings.mPackages.get(packageName);
2901                if (ps != null && ps.isMatch(flags)) {
2902                    return UserHandle.getUid(userId, ps.appId);
2903                }
2904            }
2905        }
2906
2907        return -1;
2908    }
2909
2910    @Override
2911    public int[] getPackageGids(String packageName, int flags, int userId) {
2912        if (!sUserManager.exists(userId)) return null;
2913        flags = updateFlagsForPackage(flags, userId, packageName);
2914        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2915                "getPackageGids");
2916
2917        // reader
2918        synchronized (mPackages) {
2919            final PackageParser.Package p = mPackages.get(packageName);
2920            if (p != null && p.isMatch(flags)) {
2921                PackageSetting ps = (PackageSetting) p.mExtras;
2922                return ps.getPermissionsState().computeGids(userId);
2923            }
2924            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2925                final PackageSetting ps = mSettings.mPackages.get(packageName);
2926                if (ps != null && ps.isMatch(flags)) {
2927                    return ps.getPermissionsState().computeGids(userId);
2928                }
2929            }
2930        }
2931
2932        return null;
2933    }
2934
2935    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2936        if (bp.perm != null) {
2937            return PackageParser.generatePermissionInfo(bp.perm, flags);
2938        }
2939        PermissionInfo pi = new PermissionInfo();
2940        pi.name = bp.name;
2941        pi.packageName = bp.sourcePackage;
2942        pi.nonLocalizedLabel = bp.name;
2943        pi.protectionLevel = bp.protectionLevel;
2944        return pi;
2945    }
2946
2947    @Override
2948    public PermissionInfo getPermissionInfo(String name, int flags) {
2949        // reader
2950        synchronized (mPackages) {
2951            final BasePermission p = mSettings.mPermissions.get(name);
2952            if (p != null) {
2953                return generatePermissionInfo(p, flags);
2954            }
2955            return null;
2956        }
2957    }
2958
2959    @Override
2960    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2961        // reader
2962        synchronized (mPackages) {
2963            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2964            for (BasePermission p : mSettings.mPermissions.values()) {
2965                if (group == null) {
2966                    if (p.perm == null || p.perm.info.group == null) {
2967                        out.add(generatePermissionInfo(p, flags));
2968                    }
2969                } else {
2970                    if (p.perm != null && group.equals(p.perm.info.group)) {
2971                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2972                    }
2973                }
2974            }
2975
2976            if (out.size() > 0) {
2977                return out;
2978            }
2979            return mPermissionGroups.containsKey(group) ? out : null;
2980        }
2981    }
2982
2983    @Override
2984    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2985        // reader
2986        synchronized (mPackages) {
2987            return PackageParser.generatePermissionGroupInfo(
2988                    mPermissionGroups.get(name), flags);
2989        }
2990    }
2991
2992    @Override
2993    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2994        // reader
2995        synchronized (mPackages) {
2996            final int N = mPermissionGroups.size();
2997            ArrayList<PermissionGroupInfo> out
2998                    = new ArrayList<PermissionGroupInfo>(N);
2999            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3000                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3001            }
3002            return out;
3003        }
3004    }
3005
3006    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3007            int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        PackageSetting ps = mSettings.mPackages.get(packageName);
3010        if (ps != null) {
3011            if (ps.pkg == null) {
3012                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3013                        flags, userId);
3014                if (pInfo != null) {
3015                    return pInfo.applicationInfo;
3016                }
3017                return null;
3018            }
3019            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3020                    ps.readUserState(userId), userId);
3021        }
3022        return null;
3023    }
3024
3025    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3026            int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        PackageSetting ps = mSettings.mPackages.get(packageName);
3029        if (ps != null) {
3030            PackageParser.Package pkg = ps.pkg;
3031            if (pkg == null) {
3032                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3033                    return null;
3034                }
3035                // Only data remains, so we aren't worried about code paths
3036                pkg = new PackageParser.Package(packageName);
3037                pkg.applicationInfo.packageName = packageName;
3038                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3039                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3040                pkg.applicationInfo.uid = ps.appId;
3041                pkg.applicationInfo.initForUser(userId);
3042                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3043                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3044            }
3045            return generatePackageInfo(pkg, flags, userId);
3046        }
3047        return null;
3048    }
3049
3050    @Override
3051    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3052        if (!sUserManager.exists(userId)) return null;
3053        flags = updateFlagsForApplication(flags, userId, packageName);
3054        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3055        // writer
3056        synchronized (mPackages) {
3057            PackageParser.Package p = mPackages.get(packageName);
3058            if (DEBUG_PACKAGE_INFO) Log.v(
3059                    TAG, "getApplicationInfo " + packageName
3060                    + ": " + p);
3061            if (p != null) {
3062                PackageSetting ps = mSettings.mPackages.get(packageName);
3063                if (ps == null) return null;
3064                // Note: isEnabledLP() does not apply here - always return info
3065                return PackageParser.generateApplicationInfo(
3066                        p, flags, ps.readUserState(userId), userId);
3067            }
3068            if ("android".equals(packageName)||"system".equals(packageName)) {
3069                return mAndroidApplication;
3070            }
3071            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3072                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3080            final IPackageDataObserver observer) {
3081        mContext.enforceCallingOrSelfPermission(
3082                android.Manifest.permission.CLEAR_APP_CACHE, null);
3083        // Queue up an async operation since clearing cache may take a little while.
3084        mHandler.post(new Runnable() {
3085            public void run() {
3086                mHandler.removeCallbacks(this);
3087                boolean success = true;
3088                synchronized (mInstallLock) {
3089                    try {
3090                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3091                    } catch (InstallerException e) {
3092                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3093                        success = false;
3094                    }
3095                }
3096                if (observer != null) {
3097                    try {
3098                        observer.onRemoveCompleted(null, success);
3099                    } catch (RemoteException e) {
3100                        Slog.w(TAG, "RemoveException when invoking call back");
3101                    }
3102                }
3103            }
3104        });
3105    }
3106
3107    @Override
3108    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3109            final IntentSender pi) {
3110        mContext.enforceCallingOrSelfPermission(
3111                android.Manifest.permission.CLEAR_APP_CACHE, null);
3112        // Queue up an async operation since clearing cache may take a little while.
3113        mHandler.post(new Runnable() {
3114            public void run() {
3115                mHandler.removeCallbacks(this);
3116                boolean success = true;
3117                synchronized (mInstallLock) {
3118                    try {
3119                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3120                    } catch (InstallerException e) {
3121                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3122                        success = false;
3123                    }
3124                }
3125                if(pi != null) {
3126                    try {
3127                        // Callback via pending intent
3128                        int code = success ? 1 : 0;
3129                        pi.sendIntent(null, code, null,
3130                                null, null);
3131                    } catch (SendIntentException e1) {
3132                        Slog.i(TAG, "Failed to send pending intent");
3133                    }
3134                }
3135            }
3136        });
3137    }
3138
3139    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3140        synchronized (mInstallLock) {
3141            try {
3142                mInstaller.freeCache(volumeUuid, freeStorageSize);
3143            } catch (InstallerException e) {
3144                throw new IOException("Failed to free enough space", e);
3145            }
3146        }
3147    }
3148
3149    /**
3150     * Return if the user key is currently unlocked.
3151     */
3152    private boolean isUserKeyUnlocked(int userId) {
3153        if (StorageManager.isFileBasedEncryptionEnabled()) {
3154            final IMountService mount = IMountService.Stub
3155                    .asInterface(ServiceManager.getService("mount"));
3156            if (mount == null) {
3157                Slog.w(TAG, "Early during boot, assuming locked");
3158                return false;
3159            }
3160            final long token = Binder.clearCallingIdentity();
3161            try {
3162                return mount.isUserKeyUnlocked(userId);
3163            } catch (RemoteException e) {
3164                throw e.rethrowAsRuntimeException();
3165            } finally {
3166                Binder.restoreCallingIdentity(token);
3167            }
3168        } else {
3169            return true;
3170        }
3171    }
3172
3173    /**
3174     * Update given flags based on encryption status of current user.
3175     */
3176    private int updateFlags(int flags, int userId) {
3177        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3178                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3179            // Caller expressed an explicit opinion about what encryption
3180            // aware/unaware components they want to see, so fall through and
3181            // give them what they want
3182        } else {
3183            // Caller expressed no opinion, so match based on user state
3184            if (isUserKeyUnlocked(userId)) {
3185                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3186            } else {
3187                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3188            }
3189        }
3190
3191        // Safe mode means we should ignore any third-party apps
3192        if (mSafeMode) {
3193            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3194        }
3195
3196        return flags;
3197    }
3198
3199    /**
3200     * Update given flags when being used to request {@link PackageInfo}.
3201     */
3202    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3203        boolean triaged = true;
3204        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3205                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3206            // Caller is asking for component details, so they'd better be
3207            // asking for specific encryption matching behavior, or be triaged
3208            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3209                    | PackageManager.MATCH_ENCRYPTION_AWARE
3210                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3211                triaged = false;
3212            }
3213        }
3214        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3215                | PackageManager.MATCH_SYSTEM_ONLY
3216                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3217            triaged = false;
3218        }
3219        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3220            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3221                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3222        }
3223        return updateFlags(flags, userId);
3224    }
3225
3226    /**
3227     * Update given flags when being used to request {@link ApplicationInfo}.
3228     */
3229    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3230        return updateFlagsForPackage(flags, userId, cookie);
3231    }
3232
3233    /**
3234     * Update given flags when being used to request {@link ComponentInfo}.
3235     */
3236    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3237        if (cookie instanceof Intent) {
3238            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3239                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3240            }
3241        }
3242
3243        boolean triaged = true;
3244        // Caller is asking for component details, so they'd better be
3245        // asking for specific encryption matching behavior, or be triaged
3246        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3247                | PackageManager.MATCH_ENCRYPTION_AWARE
3248                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3249            triaged = false;
3250        }
3251        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3252            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3253                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3254        }
3255        return updateFlags(flags, userId);
3256    }
3257
3258    /**
3259     * Update given flags when being used to request {@link ResolveInfo}.
3260     */
3261    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3262        return updateFlagsForComponent(flags, userId, cookie);
3263    }
3264
3265    @Override
3266    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3267        if (!sUserManager.exists(userId)) return null;
3268        flags = updateFlagsForComponent(flags, userId, component);
3269        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3270        synchronized (mPackages) {
3271            PackageParser.Activity a = mActivities.mActivities.get(component);
3272
3273            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3274            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3275                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3276                if (ps == null) return null;
3277                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3278                        userId);
3279            }
3280            if (mResolveComponentName.equals(component)) {
3281                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3282                        new PackageUserState(), userId);
3283            }
3284        }
3285        return null;
3286    }
3287
3288    @Override
3289    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3290            String resolvedType) {
3291        synchronized (mPackages) {
3292            if (component.equals(mResolveComponentName)) {
3293                // The resolver supports EVERYTHING!
3294                return true;
3295            }
3296            PackageParser.Activity a = mActivities.mActivities.get(component);
3297            if (a == null) {
3298                return false;
3299            }
3300            for (int i=0; i<a.intents.size(); i++) {
3301                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3302                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3303                    return true;
3304                }
3305            }
3306            return false;
3307        }
3308    }
3309
3310    @Override
3311    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3312        if (!sUserManager.exists(userId)) return null;
3313        flags = updateFlagsForComponent(flags, userId, component);
3314        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3315        synchronized (mPackages) {
3316            PackageParser.Activity a = mReceivers.mActivities.get(component);
3317            if (DEBUG_PACKAGE_INFO) Log.v(
3318                TAG, "getReceiverInfo " + component + ": " + a);
3319            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3320                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3321                if (ps == null) return null;
3322                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3323                        userId);
3324            }
3325        }
3326        return null;
3327    }
3328
3329    @Override
3330    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3331        if (!sUserManager.exists(userId)) return null;
3332        flags = updateFlagsForComponent(flags, userId, component);
3333        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3334        synchronized (mPackages) {
3335            PackageParser.Service s = mServices.mServices.get(component);
3336            if (DEBUG_PACKAGE_INFO) Log.v(
3337                TAG, "getServiceInfo " + component + ": " + s);
3338            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3339                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3340                if (ps == null) return null;
3341                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3342                        userId);
3343            }
3344        }
3345        return null;
3346    }
3347
3348    @Override
3349    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3350        if (!sUserManager.exists(userId)) return null;
3351        flags = updateFlagsForComponent(flags, userId, component);
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3353        synchronized (mPackages) {
3354            PackageParser.Provider p = mProviders.mProviders.get(component);
3355            if (DEBUG_PACKAGE_INFO) Log.v(
3356                TAG, "getProviderInfo " + component + ": " + p);
3357            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3358                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3359                if (ps == null) return null;
3360                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3361                        userId);
3362            }
3363        }
3364        return null;
3365    }
3366
3367    @Override
3368    public String[] getSystemSharedLibraryNames() {
3369        Set<String> libSet;
3370        synchronized (mPackages) {
3371            libSet = mSharedLibraries.keySet();
3372            int size = libSet.size();
3373            if (size > 0) {
3374                String[] libs = new String[size];
3375                libSet.toArray(libs);
3376                return libs;
3377            }
3378        }
3379        return null;
3380    }
3381
3382    /**
3383     * @hide
3384     */
3385    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3386        synchronized (mPackages) {
3387            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3388            if (lib != null && lib.apk != null) {
3389                return mPackages.get(lib.apk);
3390            }
3391        }
3392        return null;
3393    }
3394
3395    @Override
3396    public FeatureInfo[] getSystemAvailableFeatures() {
3397        Collection<FeatureInfo> featSet;
3398        synchronized (mPackages) {
3399            featSet = mAvailableFeatures.values();
3400            int size = featSet.size();
3401            if (size > 0) {
3402                FeatureInfo[] features = new FeatureInfo[size+1];
3403                featSet.toArray(features);
3404                FeatureInfo fi = new FeatureInfo();
3405                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3406                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3407                features[size] = fi;
3408                return features;
3409            }
3410        }
3411        return null;
3412    }
3413
3414    @Override
3415    public boolean hasSystemFeature(String name) {
3416        synchronized (mPackages) {
3417            return mAvailableFeatures.containsKey(name);
3418        }
3419    }
3420
3421    @Override
3422    public int checkPermission(String permName, String pkgName, int userId) {
3423        if (!sUserManager.exists(userId)) {
3424            return PackageManager.PERMISSION_DENIED;
3425        }
3426
3427        synchronized (mPackages) {
3428            final PackageParser.Package p = mPackages.get(pkgName);
3429            if (p != null && p.mExtras != null) {
3430                final PackageSetting ps = (PackageSetting) p.mExtras;
3431                final PermissionsState permissionsState = ps.getPermissionsState();
3432                if (permissionsState.hasPermission(permName, userId)) {
3433                    return PackageManager.PERMISSION_GRANTED;
3434                }
3435                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3436                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3437                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3438                    return PackageManager.PERMISSION_GRANTED;
3439                }
3440            }
3441        }
3442
3443        return PackageManager.PERMISSION_DENIED;
3444    }
3445
3446    @Override
3447    public int checkUidPermission(String permName, int uid) {
3448        final int userId = UserHandle.getUserId(uid);
3449
3450        if (!sUserManager.exists(userId)) {
3451            return PackageManager.PERMISSION_DENIED;
3452        }
3453
3454        synchronized (mPackages) {
3455            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3456            if (obj != null) {
3457                final SettingBase ps = (SettingBase) obj;
3458                final PermissionsState permissionsState = ps.getPermissionsState();
3459                if (permissionsState.hasPermission(permName, userId)) {
3460                    return PackageManager.PERMISSION_GRANTED;
3461                }
3462                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3463                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3464                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3465                    return PackageManager.PERMISSION_GRANTED;
3466                }
3467            } else {
3468                ArraySet<String> perms = mSystemPermissions.get(uid);
3469                if (perms != null) {
3470                    if (perms.contains(permName)) {
3471                        return PackageManager.PERMISSION_GRANTED;
3472                    }
3473                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3474                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3475                        return PackageManager.PERMISSION_GRANTED;
3476                    }
3477                }
3478            }
3479        }
3480
3481        return PackageManager.PERMISSION_DENIED;
3482    }
3483
3484    @Override
3485    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3486        if (UserHandle.getCallingUserId() != userId) {
3487            mContext.enforceCallingPermission(
3488                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3489                    "isPermissionRevokedByPolicy for user " + userId);
3490        }
3491
3492        if (checkPermission(permission, packageName, userId)
3493                == PackageManager.PERMISSION_GRANTED) {
3494            return false;
3495        }
3496
3497        final long identity = Binder.clearCallingIdentity();
3498        try {
3499            final int flags = getPermissionFlags(permission, packageName, userId);
3500            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3501        } finally {
3502            Binder.restoreCallingIdentity(identity);
3503        }
3504    }
3505
3506    @Override
3507    public String getPermissionControllerPackageName() {
3508        synchronized (mPackages) {
3509            return mRequiredInstallerPackage;
3510        }
3511    }
3512
3513    /**
3514     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3515     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3516     * @param checkShell TODO(yamasani):
3517     * @param message the message to log on security exception
3518     */
3519    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3520            boolean checkShell, String message) {
3521        if (userId < 0) {
3522            throw new IllegalArgumentException("Invalid userId " + userId);
3523        }
3524        if (checkShell) {
3525            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3526        }
3527        if (userId == UserHandle.getUserId(callingUid)) return;
3528        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3529            if (requireFullPermission) {
3530                mContext.enforceCallingOrSelfPermission(
3531                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3532            } else {
3533                try {
3534                    mContext.enforceCallingOrSelfPermission(
3535                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3536                } catch (SecurityException se) {
3537                    mContext.enforceCallingOrSelfPermission(
3538                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3539                }
3540            }
3541        }
3542    }
3543
3544    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3545        if (callingUid == Process.SHELL_UID) {
3546            if (userHandle >= 0
3547                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3548                throw new SecurityException("Shell does not have permission to access user "
3549                        + userHandle);
3550            } else if (userHandle < 0) {
3551                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3552                        + Debug.getCallers(3));
3553            }
3554        }
3555    }
3556
3557    private BasePermission findPermissionTreeLP(String permName) {
3558        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3559            if (permName.startsWith(bp.name) &&
3560                    permName.length() > bp.name.length() &&
3561                    permName.charAt(bp.name.length()) == '.') {
3562                return bp;
3563            }
3564        }
3565        return null;
3566    }
3567
3568    private BasePermission checkPermissionTreeLP(String permName) {
3569        if (permName != null) {
3570            BasePermission bp = findPermissionTreeLP(permName);
3571            if (bp != null) {
3572                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3573                    return bp;
3574                }
3575                throw new SecurityException("Calling uid "
3576                        + Binder.getCallingUid()
3577                        + " is not allowed to add to permission tree "
3578                        + bp.name + " owned by uid " + bp.uid);
3579            }
3580        }
3581        throw new SecurityException("No permission tree found for " + permName);
3582    }
3583
3584    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3585        if (s1 == null) {
3586            return s2 == null;
3587        }
3588        if (s2 == null) {
3589            return false;
3590        }
3591        if (s1.getClass() != s2.getClass()) {
3592            return false;
3593        }
3594        return s1.equals(s2);
3595    }
3596
3597    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3598        if (pi1.icon != pi2.icon) return false;
3599        if (pi1.logo != pi2.logo) return false;
3600        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3601        if (!compareStrings(pi1.name, pi2.name)) return false;
3602        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3603        // We'll take care of setting this one.
3604        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3605        // These are not currently stored in settings.
3606        //if (!compareStrings(pi1.group, pi2.group)) return false;
3607        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3608        //if (pi1.labelRes != pi2.labelRes) return false;
3609        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3610        return true;
3611    }
3612
3613    int permissionInfoFootprint(PermissionInfo info) {
3614        int size = info.name.length();
3615        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3616        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3617        return size;
3618    }
3619
3620    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3621        int size = 0;
3622        for (BasePermission perm : mSettings.mPermissions.values()) {
3623            if (perm.uid == tree.uid) {
3624                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3625            }
3626        }
3627        return size;
3628    }
3629
3630    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3631        // We calculate the max size of permissions defined by this uid and throw
3632        // if that plus the size of 'info' would exceed our stated maximum.
3633        if (tree.uid != Process.SYSTEM_UID) {
3634            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3635            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3636                throw new SecurityException("Permission tree size cap exceeded");
3637            }
3638        }
3639    }
3640
3641    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3642        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3643            throw new SecurityException("Label must be specified in permission");
3644        }
3645        BasePermission tree = checkPermissionTreeLP(info.name);
3646        BasePermission bp = mSettings.mPermissions.get(info.name);
3647        boolean added = bp == null;
3648        boolean changed = true;
3649        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3650        if (added) {
3651            enforcePermissionCapLocked(info, tree);
3652            bp = new BasePermission(info.name, tree.sourcePackage,
3653                    BasePermission.TYPE_DYNAMIC);
3654        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3655            throw new SecurityException(
3656                    "Not allowed to modify non-dynamic permission "
3657                    + info.name);
3658        } else {
3659            if (bp.protectionLevel == fixedLevel
3660                    && bp.perm.owner.equals(tree.perm.owner)
3661                    && bp.uid == tree.uid
3662                    && comparePermissionInfos(bp.perm.info, info)) {
3663                changed = false;
3664            }
3665        }
3666        bp.protectionLevel = fixedLevel;
3667        info = new PermissionInfo(info);
3668        info.protectionLevel = fixedLevel;
3669        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3670        bp.perm.info.packageName = tree.perm.info.packageName;
3671        bp.uid = tree.uid;
3672        if (added) {
3673            mSettings.mPermissions.put(info.name, bp);
3674        }
3675        if (changed) {
3676            if (!async) {
3677                mSettings.writeLPr();
3678            } else {
3679                scheduleWriteSettingsLocked();
3680            }
3681        }
3682        return added;
3683    }
3684
3685    @Override
3686    public boolean addPermission(PermissionInfo info) {
3687        synchronized (mPackages) {
3688            return addPermissionLocked(info, false);
3689        }
3690    }
3691
3692    @Override
3693    public boolean addPermissionAsync(PermissionInfo info) {
3694        synchronized (mPackages) {
3695            return addPermissionLocked(info, true);
3696        }
3697    }
3698
3699    @Override
3700    public void removePermission(String name) {
3701        synchronized (mPackages) {
3702            checkPermissionTreeLP(name);
3703            BasePermission bp = mSettings.mPermissions.get(name);
3704            if (bp != null) {
3705                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3706                    throw new SecurityException(
3707                            "Not allowed to modify non-dynamic permission "
3708                            + name);
3709                }
3710                mSettings.mPermissions.remove(name);
3711                mSettings.writeLPr();
3712            }
3713        }
3714    }
3715
3716    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3717            BasePermission bp) {
3718        int index = pkg.requestedPermissions.indexOf(bp.name);
3719        if (index == -1) {
3720            throw new SecurityException("Package " + pkg.packageName
3721                    + " has not requested permission " + bp.name);
3722        }
3723        if (!bp.isRuntime() && !bp.isDevelopment()) {
3724            throw new SecurityException("Permission " + bp.name
3725                    + " is not a changeable permission type");
3726        }
3727    }
3728
3729    @Override
3730    public void grantRuntimePermission(String packageName, String name, final int userId) {
3731        if (!sUserManager.exists(userId)) {
3732            Log.e(TAG, "No such user:" + userId);
3733            return;
3734        }
3735
3736        mContext.enforceCallingOrSelfPermission(
3737                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3738                "grantRuntimePermission");
3739
3740        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3741                "grantRuntimePermission");
3742
3743        final int uid;
3744        final SettingBase sb;
3745
3746        synchronized (mPackages) {
3747            final PackageParser.Package pkg = mPackages.get(packageName);
3748            if (pkg == null) {
3749                throw new IllegalArgumentException("Unknown package: " + packageName);
3750            }
3751
3752            final BasePermission bp = mSettings.mPermissions.get(name);
3753            if (bp == null) {
3754                throw new IllegalArgumentException("Unknown permission: " + name);
3755            }
3756
3757            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3758
3759            // If a permission review is required for legacy apps we represent
3760            // their permissions as always granted runtime ones since we need
3761            // to keep the review required permission flag per user while an
3762            // install permission's state is shared across all users.
3763            if (Build.PERMISSIONS_REVIEW_REQUIRED
3764                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3765                    && bp.isRuntime()) {
3766                return;
3767            }
3768
3769            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3770            sb = (SettingBase) pkg.mExtras;
3771            if (sb == null) {
3772                throw new IllegalArgumentException("Unknown package: " + packageName);
3773            }
3774
3775            final PermissionsState permissionsState = sb.getPermissionsState();
3776
3777            final int flags = permissionsState.getPermissionFlags(name, userId);
3778            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3779                throw new SecurityException("Cannot grant system fixed permission "
3780                        + name + " for package " + packageName);
3781            }
3782
3783            if (bp.isDevelopment()) {
3784                // Development permissions must be handled specially, since they are not
3785                // normal runtime permissions.  For now they apply to all users.
3786                if (permissionsState.grantInstallPermission(bp) !=
3787                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3788                    scheduleWriteSettingsLocked();
3789                }
3790                return;
3791            }
3792
3793            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3794                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3795                return;
3796            }
3797
3798            final int result = permissionsState.grantRuntimePermission(bp, userId);
3799            switch (result) {
3800                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3801                    return;
3802                }
3803
3804                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3805                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3806                    mHandler.post(new Runnable() {
3807                        @Override
3808                        public void run() {
3809                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3810                        }
3811                    });
3812                }
3813                break;
3814            }
3815
3816            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3817
3818            // Not critical if that is lost - app has to request again.
3819            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3820        }
3821
3822        // Only need to do this if user is initialized. Otherwise it's a new user
3823        // and there are no processes running as the user yet and there's no need
3824        // to make an expensive call to remount processes for the changed permissions.
3825        if (READ_EXTERNAL_STORAGE.equals(name)
3826                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3827            final long token = Binder.clearCallingIdentity();
3828            try {
3829                if (sUserManager.isInitialized(userId)) {
3830                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3831                            MountServiceInternal.class);
3832                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3833                }
3834            } finally {
3835                Binder.restoreCallingIdentity(token);
3836            }
3837        }
3838    }
3839
3840    @Override
3841    public void revokeRuntimePermission(String packageName, String name, int userId) {
3842        if (!sUserManager.exists(userId)) {
3843            Log.e(TAG, "No such user:" + userId);
3844            return;
3845        }
3846
3847        mContext.enforceCallingOrSelfPermission(
3848                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3849                "revokeRuntimePermission");
3850
3851        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3852                "revokeRuntimePermission");
3853
3854        final int appId;
3855
3856        synchronized (mPackages) {
3857            final PackageParser.Package pkg = mPackages.get(packageName);
3858            if (pkg == null) {
3859                throw new IllegalArgumentException("Unknown package: " + packageName);
3860            }
3861
3862            final BasePermission bp = mSettings.mPermissions.get(name);
3863            if (bp == null) {
3864                throw new IllegalArgumentException("Unknown permission: " + name);
3865            }
3866
3867            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3868
3869            // If a permission review is required for legacy apps we represent
3870            // their permissions as always granted runtime ones since we need
3871            // to keep the review required permission flag per user while an
3872            // install permission's state is shared across all users.
3873            if (Build.PERMISSIONS_REVIEW_REQUIRED
3874                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3875                    && bp.isRuntime()) {
3876                return;
3877            }
3878
3879            SettingBase sb = (SettingBase) pkg.mExtras;
3880            if (sb == null) {
3881                throw new IllegalArgumentException("Unknown package: " + packageName);
3882            }
3883
3884            final PermissionsState permissionsState = sb.getPermissionsState();
3885
3886            final int flags = permissionsState.getPermissionFlags(name, userId);
3887            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3888                throw new SecurityException("Cannot revoke system fixed permission "
3889                        + name + " for package " + packageName);
3890            }
3891
3892            if (bp.isDevelopment()) {
3893                // Development permissions must be handled specially, since they are not
3894                // normal runtime permissions.  For now they apply to all users.
3895                if (permissionsState.revokeInstallPermission(bp) !=
3896                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3897                    scheduleWriteSettingsLocked();
3898                }
3899                return;
3900            }
3901
3902            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3903                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3904                return;
3905            }
3906
3907            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3908
3909            // Critical, after this call app should never have the permission.
3910            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3911
3912            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3913        }
3914
3915        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3916    }
3917
3918    @Override
3919    public void resetRuntimePermissions() {
3920        mContext.enforceCallingOrSelfPermission(
3921                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3922                "revokeRuntimePermission");
3923
3924        int callingUid = Binder.getCallingUid();
3925        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3926            mContext.enforceCallingOrSelfPermission(
3927                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3928                    "resetRuntimePermissions");
3929        }
3930
3931        synchronized (mPackages) {
3932            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3933            for (int userId : UserManagerService.getInstance().getUserIds()) {
3934                final int packageCount = mPackages.size();
3935                for (int i = 0; i < packageCount; i++) {
3936                    PackageParser.Package pkg = mPackages.valueAt(i);
3937                    if (!(pkg.mExtras instanceof PackageSetting)) {
3938                        continue;
3939                    }
3940                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3941                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3942                }
3943            }
3944        }
3945    }
3946
3947    @Override
3948    public int getPermissionFlags(String name, String packageName, int userId) {
3949        if (!sUserManager.exists(userId)) {
3950            return 0;
3951        }
3952
3953        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3954
3955        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3956                "getPermissionFlags");
3957
3958        synchronized (mPackages) {
3959            final PackageParser.Package pkg = mPackages.get(packageName);
3960            if (pkg == null) {
3961                throw new IllegalArgumentException("Unknown package: " + packageName);
3962            }
3963
3964            final BasePermission bp = mSettings.mPermissions.get(name);
3965            if (bp == null) {
3966                throw new IllegalArgumentException("Unknown permission: " + name);
3967            }
3968
3969            SettingBase sb = (SettingBase) pkg.mExtras;
3970            if (sb == null) {
3971                throw new IllegalArgumentException("Unknown package: " + packageName);
3972            }
3973
3974            PermissionsState permissionsState = sb.getPermissionsState();
3975            return permissionsState.getPermissionFlags(name, userId);
3976        }
3977    }
3978
3979    @Override
3980    public void updatePermissionFlags(String name, String packageName, int flagMask,
3981            int flagValues, int userId) {
3982        if (!sUserManager.exists(userId)) {
3983            return;
3984        }
3985
3986        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3987
3988        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3989                "updatePermissionFlags");
3990
3991        // Only the system can change these flags and nothing else.
3992        if (getCallingUid() != Process.SYSTEM_UID) {
3993            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3994            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3995            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3996            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3997            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3998        }
3999
4000        synchronized (mPackages) {
4001            final PackageParser.Package pkg = mPackages.get(packageName);
4002            if (pkg == null) {
4003                throw new IllegalArgumentException("Unknown package: " + packageName);
4004            }
4005
4006            final BasePermission bp = mSettings.mPermissions.get(name);
4007            if (bp == null) {
4008                throw new IllegalArgumentException("Unknown permission: " + name);
4009            }
4010
4011            SettingBase sb = (SettingBase) pkg.mExtras;
4012            if (sb == null) {
4013                throw new IllegalArgumentException("Unknown package: " + packageName);
4014            }
4015
4016            PermissionsState permissionsState = sb.getPermissionsState();
4017
4018            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4019
4020            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4021                // Install and runtime permissions are stored in different places,
4022                // so figure out what permission changed and persist the change.
4023                if (permissionsState.getInstallPermissionState(name) != null) {
4024                    scheduleWriteSettingsLocked();
4025                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4026                        || hadState) {
4027                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4028                }
4029            }
4030        }
4031    }
4032
4033    /**
4034     * Update the permission flags for all packages and runtime permissions of a user in order
4035     * to allow device or profile owner to remove POLICY_FIXED.
4036     */
4037    @Override
4038    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4039        if (!sUserManager.exists(userId)) {
4040            return;
4041        }
4042
4043        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4044
4045        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4046                "updatePermissionFlagsForAllApps");
4047
4048        // Only the system can change system fixed flags.
4049        if (getCallingUid() != Process.SYSTEM_UID) {
4050            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4051            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4052        }
4053
4054        synchronized (mPackages) {
4055            boolean changed = false;
4056            final int packageCount = mPackages.size();
4057            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4058                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4059                SettingBase sb = (SettingBase) pkg.mExtras;
4060                if (sb == null) {
4061                    continue;
4062                }
4063                PermissionsState permissionsState = sb.getPermissionsState();
4064                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4065                        userId, flagMask, flagValues);
4066            }
4067            if (changed) {
4068                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4069            }
4070        }
4071    }
4072
4073    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4074        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4075                != PackageManager.PERMISSION_GRANTED
4076            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4077                != PackageManager.PERMISSION_GRANTED) {
4078            throw new SecurityException(message + " requires "
4079                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4080                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4081        }
4082    }
4083
4084    @Override
4085    public boolean shouldShowRequestPermissionRationale(String permissionName,
4086            String packageName, int userId) {
4087        if (UserHandle.getCallingUserId() != userId) {
4088            mContext.enforceCallingPermission(
4089                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4090                    "canShowRequestPermissionRationale for user " + userId);
4091        }
4092
4093        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4094        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4095            return false;
4096        }
4097
4098        if (checkPermission(permissionName, packageName, userId)
4099                == PackageManager.PERMISSION_GRANTED) {
4100            return false;
4101        }
4102
4103        final int flags;
4104
4105        final long identity = Binder.clearCallingIdentity();
4106        try {
4107            flags = getPermissionFlags(permissionName,
4108                    packageName, userId);
4109        } finally {
4110            Binder.restoreCallingIdentity(identity);
4111        }
4112
4113        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4114                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4115                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4116
4117        if ((flags & fixedFlags) != 0) {
4118            return false;
4119        }
4120
4121        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4122    }
4123
4124    @Override
4125    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4126        mContext.enforceCallingOrSelfPermission(
4127                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4128                "addOnPermissionsChangeListener");
4129
4130        synchronized (mPackages) {
4131            mOnPermissionChangeListeners.addListenerLocked(listener);
4132        }
4133    }
4134
4135    @Override
4136    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4137        synchronized (mPackages) {
4138            mOnPermissionChangeListeners.removeListenerLocked(listener);
4139        }
4140    }
4141
4142    @Override
4143    public boolean isProtectedBroadcast(String actionName) {
4144        synchronized (mPackages) {
4145            if (mProtectedBroadcasts.contains(actionName)) {
4146                return true;
4147            } else if (actionName != null) {
4148                // TODO: remove these terrible hacks
4149                if (actionName.startsWith("android.net.netmon.lingerExpired")
4150                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4151                    return true;
4152                }
4153            }
4154        }
4155        return false;
4156    }
4157
4158    @Override
4159    public int checkSignatures(String pkg1, String pkg2) {
4160        synchronized (mPackages) {
4161            final PackageParser.Package p1 = mPackages.get(pkg1);
4162            final PackageParser.Package p2 = mPackages.get(pkg2);
4163            if (p1 == null || p1.mExtras == null
4164                    || p2 == null || p2.mExtras == null) {
4165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4166            }
4167            return compareSignatures(p1.mSignatures, p2.mSignatures);
4168        }
4169    }
4170
4171    @Override
4172    public int checkUidSignatures(int uid1, int uid2) {
4173        // Map to base uids.
4174        uid1 = UserHandle.getAppId(uid1);
4175        uid2 = UserHandle.getAppId(uid2);
4176        // reader
4177        synchronized (mPackages) {
4178            Signature[] s1;
4179            Signature[] s2;
4180            Object obj = mSettings.getUserIdLPr(uid1);
4181            if (obj != null) {
4182                if (obj instanceof SharedUserSetting) {
4183                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4184                } else if (obj instanceof PackageSetting) {
4185                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4186                } else {
4187                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4188                }
4189            } else {
4190                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4191            }
4192            obj = mSettings.getUserIdLPr(uid2);
4193            if (obj != null) {
4194                if (obj instanceof SharedUserSetting) {
4195                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4196                } else if (obj instanceof PackageSetting) {
4197                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4198                } else {
4199                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4200                }
4201            } else {
4202                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4203            }
4204            return compareSignatures(s1, s2);
4205        }
4206    }
4207
4208    private void killUid(int appId, int userId, String reason) {
4209        final long identity = Binder.clearCallingIdentity();
4210        try {
4211            IActivityManager am = ActivityManagerNative.getDefault();
4212            if (am != null) {
4213                try {
4214                    am.killUid(appId, userId, reason);
4215                } catch (RemoteException e) {
4216                    /* ignore - same process */
4217                }
4218            }
4219        } finally {
4220            Binder.restoreCallingIdentity(identity);
4221        }
4222    }
4223
4224    /**
4225     * Compares two sets of signatures. Returns:
4226     * <br />
4227     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4228     * <br />
4229     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4230     * <br />
4231     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4232     * <br />
4233     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4234     * <br />
4235     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4236     */
4237    static int compareSignatures(Signature[] s1, Signature[] s2) {
4238        if (s1 == null) {
4239            return s2 == null
4240                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4241                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4242        }
4243
4244        if (s2 == null) {
4245            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4246        }
4247
4248        if (s1.length != s2.length) {
4249            return PackageManager.SIGNATURE_NO_MATCH;
4250        }
4251
4252        // Since both signature sets are of size 1, we can compare without HashSets.
4253        if (s1.length == 1) {
4254            return s1[0].equals(s2[0]) ?
4255                    PackageManager.SIGNATURE_MATCH :
4256                    PackageManager.SIGNATURE_NO_MATCH;
4257        }
4258
4259        ArraySet<Signature> set1 = new ArraySet<Signature>();
4260        for (Signature sig : s1) {
4261            set1.add(sig);
4262        }
4263        ArraySet<Signature> set2 = new ArraySet<Signature>();
4264        for (Signature sig : s2) {
4265            set2.add(sig);
4266        }
4267        // Make sure s2 contains all signatures in s1.
4268        if (set1.equals(set2)) {
4269            return PackageManager.SIGNATURE_MATCH;
4270        }
4271        return PackageManager.SIGNATURE_NO_MATCH;
4272    }
4273
4274    /**
4275     * If the database version for this type of package (internal storage or
4276     * external storage) is less than the version where package signatures
4277     * were updated, return true.
4278     */
4279    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4280        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4281        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4282    }
4283
4284    /**
4285     * Used for backward compatibility to make sure any packages with
4286     * certificate chains get upgraded to the new style. {@code existingSigs}
4287     * will be in the old format (since they were stored on disk from before the
4288     * system upgrade) and {@code scannedSigs} will be in the newer format.
4289     */
4290    private int compareSignaturesCompat(PackageSignatures existingSigs,
4291            PackageParser.Package scannedPkg) {
4292        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4293            return PackageManager.SIGNATURE_NO_MATCH;
4294        }
4295
4296        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4297        for (Signature sig : existingSigs.mSignatures) {
4298            existingSet.add(sig);
4299        }
4300        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4301        for (Signature sig : scannedPkg.mSignatures) {
4302            try {
4303                Signature[] chainSignatures = sig.getChainSignatures();
4304                for (Signature chainSig : chainSignatures) {
4305                    scannedCompatSet.add(chainSig);
4306                }
4307            } catch (CertificateEncodingException e) {
4308                scannedCompatSet.add(sig);
4309            }
4310        }
4311        /*
4312         * Make sure the expanded scanned set contains all signatures in the
4313         * existing one.
4314         */
4315        if (scannedCompatSet.equals(existingSet)) {
4316            // Migrate the old signatures to the new scheme.
4317            existingSigs.assignSignatures(scannedPkg.mSignatures);
4318            // The new KeySets will be re-added later in the scanning process.
4319            synchronized (mPackages) {
4320                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4321            }
4322            return PackageManager.SIGNATURE_MATCH;
4323        }
4324        return PackageManager.SIGNATURE_NO_MATCH;
4325    }
4326
4327    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4328        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4329        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4330    }
4331
4332    private int compareSignaturesRecover(PackageSignatures existingSigs,
4333            PackageParser.Package scannedPkg) {
4334        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4335            return PackageManager.SIGNATURE_NO_MATCH;
4336        }
4337
4338        String msg = null;
4339        try {
4340            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4341                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4342                        + scannedPkg.packageName);
4343                return PackageManager.SIGNATURE_MATCH;
4344            }
4345        } catch (CertificateException e) {
4346            msg = e.getMessage();
4347        }
4348
4349        logCriticalInfo(Log.INFO,
4350                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4351        return PackageManager.SIGNATURE_NO_MATCH;
4352    }
4353
4354    @Override
4355    public String[] getPackagesForUid(int uid) {
4356        uid = UserHandle.getAppId(uid);
4357        // reader
4358        synchronized (mPackages) {
4359            Object obj = mSettings.getUserIdLPr(uid);
4360            if (obj instanceof SharedUserSetting) {
4361                final SharedUserSetting sus = (SharedUserSetting) obj;
4362                final int N = sus.packages.size();
4363                final String[] res = new String[N];
4364                final Iterator<PackageSetting> it = sus.packages.iterator();
4365                int i = 0;
4366                while (it.hasNext()) {
4367                    res[i++] = it.next().name;
4368                }
4369                return res;
4370            } else if (obj instanceof PackageSetting) {
4371                final PackageSetting ps = (PackageSetting) obj;
4372                return new String[] { ps.name };
4373            }
4374        }
4375        return null;
4376    }
4377
4378    @Override
4379    public String getNameForUid(int uid) {
4380        // reader
4381        synchronized (mPackages) {
4382            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4383            if (obj instanceof SharedUserSetting) {
4384                final SharedUserSetting sus = (SharedUserSetting) obj;
4385                return sus.name + ":" + sus.userId;
4386            } else if (obj instanceof PackageSetting) {
4387                final PackageSetting ps = (PackageSetting) obj;
4388                return ps.name;
4389            }
4390        }
4391        return null;
4392    }
4393
4394    @Override
4395    public int getUidForSharedUser(String sharedUserName) {
4396        if(sharedUserName == null) {
4397            return -1;
4398        }
4399        // reader
4400        synchronized (mPackages) {
4401            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4402            if (suid == null) {
4403                return -1;
4404            }
4405            return suid.userId;
4406        }
4407    }
4408
4409    @Override
4410    public int getFlagsForUid(int uid) {
4411        synchronized (mPackages) {
4412            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4413            if (obj instanceof SharedUserSetting) {
4414                final SharedUserSetting sus = (SharedUserSetting) obj;
4415                return sus.pkgFlags;
4416            } else if (obj instanceof PackageSetting) {
4417                final PackageSetting ps = (PackageSetting) obj;
4418                return ps.pkgFlags;
4419            }
4420        }
4421        return 0;
4422    }
4423
4424    @Override
4425    public int getPrivateFlagsForUid(int uid) {
4426        synchronized (mPackages) {
4427            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4428            if (obj instanceof SharedUserSetting) {
4429                final SharedUserSetting sus = (SharedUserSetting) obj;
4430                return sus.pkgPrivateFlags;
4431            } else if (obj instanceof PackageSetting) {
4432                final PackageSetting ps = (PackageSetting) obj;
4433                return ps.pkgPrivateFlags;
4434            }
4435        }
4436        return 0;
4437    }
4438
4439    @Override
4440    public boolean isUidPrivileged(int uid) {
4441        uid = UserHandle.getAppId(uid);
4442        // reader
4443        synchronized (mPackages) {
4444            Object obj = mSettings.getUserIdLPr(uid);
4445            if (obj instanceof SharedUserSetting) {
4446                final SharedUserSetting sus = (SharedUserSetting) obj;
4447                final Iterator<PackageSetting> it = sus.packages.iterator();
4448                while (it.hasNext()) {
4449                    if (it.next().isPrivileged()) {
4450                        return true;
4451                    }
4452                }
4453            } else if (obj instanceof PackageSetting) {
4454                final PackageSetting ps = (PackageSetting) obj;
4455                return ps.isPrivileged();
4456            }
4457        }
4458        return false;
4459    }
4460
4461    @Override
4462    public String[] getAppOpPermissionPackages(String permissionName) {
4463        synchronized (mPackages) {
4464            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4465            if (pkgs == null) {
4466                return null;
4467            }
4468            return pkgs.toArray(new String[pkgs.size()]);
4469        }
4470    }
4471
4472    @Override
4473    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4474            int flags, int userId) {
4475        if (!sUserManager.exists(userId)) return null;
4476        flags = updateFlagsForResolve(flags, userId, intent);
4477        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4478        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4479        final ResolveInfo bestChoice =
4480                chooseBestActivity(intent, resolvedType, flags, query, userId);
4481
4482        if (isEphemeralAllowed(intent, query, userId)) {
4483            final EphemeralResolveInfo ai =
4484                    getEphemeralResolveInfo(intent, resolvedType, userId);
4485            if (ai != null) {
4486                if (DEBUG_EPHEMERAL) {
4487                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4488                }
4489                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4490                bestChoice.ephemeralResolveInfo = ai;
4491            }
4492        }
4493        return bestChoice;
4494    }
4495
4496    @Override
4497    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4498            IntentFilter filter, int match, ComponentName activity) {
4499        final int userId = UserHandle.getCallingUserId();
4500        if (DEBUG_PREFERRED) {
4501            Log.v(TAG, "setLastChosenActivity intent=" + intent
4502                + " resolvedType=" + resolvedType
4503                + " flags=" + flags
4504                + " filter=" + filter
4505                + " match=" + match
4506                + " activity=" + activity);
4507            filter.dump(new PrintStreamPrinter(System.out), "    ");
4508        }
4509        intent.setComponent(null);
4510        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4511        // Find any earlier preferred or last chosen entries and nuke them
4512        findPreferredActivity(intent, resolvedType,
4513                flags, query, 0, false, true, false, userId);
4514        // Add the new activity as the last chosen for this filter
4515        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4516                "Setting last chosen");
4517    }
4518
4519    @Override
4520    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4521        final int userId = UserHandle.getCallingUserId();
4522        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4523        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4524        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4525                false, false, false, userId);
4526    }
4527
4528
4529    private boolean isEphemeralAllowed(
4530            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4531        // Short circuit and return early if possible.
4532        if (DISABLE_EPHEMERAL_APPS) {
4533            return false;
4534        }
4535        final int callingUser = UserHandle.getCallingUserId();
4536        if (callingUser != UserHandle.USER_SYSTEM) {
4537            return false;
4538        }
4539        if (mEphemeralResolverConnection == null) {
4540            return false;
4541        }
4542        if (intent.getComponent() != null) {
4543            return false;
4544        }
4545        if (intent.getPackage() != null) {
4546            return false;
4547        }
4548        final boolean isWebUri = hasWebURI(intent);
4549        if (!isWebUri) {
4550            return false;
4551        }
4552        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4553        synchronized (mPackages) {
4554            final int count = resolvedActivites.size();
4555            for (int n = 0; n < count; n++) {
4556                ResolveInfo info = resolvedActivites.get(n);
4557                String packageName = info.activityInfo.packageName;
4558                PackageSetting ps = mSettings.mPackages.get(packageName);
4559                if (ps != null) {
4560                    // Try to get the status from User settings first
4561                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4562                    int status = (int) (packedStatus >> 32);
4563                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4564                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4565                        if (DEBUG_EPHEMERAL) {
4566                            Slog.v(TAG, "DENY ephemeral apps;"
4567                                + " pkg: " + packageName + ", status: " + status);
4568                        }
4569                        return false;
4570                    }
4571                }
4572            }
4573        }
4574        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4575        return true;
4576    }
4577
4578    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4579            int userId) {
4580        MessageDigest digest = null;
4581        try {
4582            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4583        } catch (NoSuchAlgorithmException e) {
4584            // If we can't create a digest, ignore ephemeral apps.
4585            return null;
4586        }
4587
4588        final byte[] hostBytes = intent.getData().getHost().getBytes();
4589        final byte[] digestBytes = digest.digest(hostBytes);
4590        int shaPrefix =
4591                digestBytes[0] << 24
4592                | digestBytes[1] << 16
4593                | digestBytes[2] << 8
4594                | digestBytes[3] << 0;
4595        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4596                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4597        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4598            // No hash prefix match; there are no ephemeral apps for this domain.
4599            return null;
4600        }
4601        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4602            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4603            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4604                continue;
4605            }
4606            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4607            // No filters; this should never happen.
4608            if (filters.isEmpty()) {
4609                continue;
4610            }
4611            // We have a domain match; resolve the filters to see if anything matches.
4612            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4613            for (int j = filters.size() - 1; j >= 0; --j) {
4614                final EphemeralResolveIntentInfo intentInfo =
4615                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4616                ephemeralResolver.addFilter(intentInfo);
4617            }
4618            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4619                    intent, resolvedType, false /*defaultOnly*/, userId);
4620            if (!matchedResolveInfoList.isEmpty()) {
4621                return matchedResolveInfoList.get(0);
4622            }
4623        }
4624        // Hash or filter mis-match; no ephemeral apps for this domain.
4625        return null;
4626    }
4627
4628    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4629            int flags, List<ResolveInfo> query, int userId) {
4630        if (query != null) {
4631            final int N = query.size();
4632            if (N == 1) {
4633                return query.get(0);
4634            } else if (N > 1) {
4635                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4636                // If there is more than one activity with the same priority,
4637                // then let the user decide between them.
4638                ResolveInfo r0 = query.get(0);
4639                ResolveInfo r1 = query.get(1);
4640                if (DEBUG_INTENT_MATCHING || debug) {
4641                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4642                            + r1.activityInfo.name + "=" + r1.priority);
4643                }
4644                // If the first activity has a higher priority, or a different
4645                // default, then it is always desirable to pick it.
4646                if (r0.priority != r1.priority
4647                        || r0.preferredOrder != r1.preferredOrder
4648                        || r0.isDefault != r1.isDefault) {
4649                    return query.get(0);
4650                }
4651                // If we have saved a preference for a preferred activity for
4652                // this Intent, use that.
4653                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4654                        flags, query, r0.priority, true, false, debug, userId);
4655                if (ri != null) {
4656                    return ri;
4657                }
4658                ri = new ResolveInfo(mResolveInfo);
4659                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4660                ri.activityInfo.applicationInfo = new ApplicationInfo(
4661                        ri.activityInfo.applicationInfo);
4662                if (userId != 0) {
4663                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4664                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4665                }
4666                // Make sure that the resolver is displayable in car mode
4667                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4668                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4669                return ri;
4670            }
4671        }
4672        return null;
4673    }
4674
4675    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4676            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4677        final int N = query.size();
4678        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4679                .get(userId);
4680        // Get the list of persistent preferred activities that handle the intent
4681        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4682        List<PersistentPreferredActivity> pprefs = ppir != null
4683                ? ppir.queryIntent(intent, resolvedType,
4684                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4685                : null;
4686        if (pprefs != null && pprefs.size() > 0) {
4687            final int M = pprefs.size();
4688            for (int i=0; i<M; i++) {
4689                final PersistentPreferredActivity ppa = pprefs.get(i);
4690                if (DEBUG_PREFERRED || debug) {
4691                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4692                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4693                            + "\n  component=" + ppa.mComponent);
4694                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4695                }
4696                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4697                        flags | MATCH_DISABLED_COMPONENTS, userId);
4698                if (DEBUG_PREFERRED || debug) {
4699                    Slog.v(TAG, "Found persistent preferred activity:");
4700                    if (ai != null) {
4701                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4702                    } else {
4703                        Slog.v(TAG, "  null");
4704                    }
4705                }
4706                if (ai == null) {
4707                    // This previously registered persistent preferred activity
4708                    // component is no longer known. Ignore it and do NOT remove it.
4709                    continue;
4710                }
4711                for (int j=0; j<N; j++) {
4712                    final ResolveInfo ri = query.get(j);
4713                    if (!ri.activityInfo.applicationInfo.packageName
4714                            .equals(ai.applicationInfo.packageName)) {
4715                        continue;
4716                    }
4717                    if (!ri.activityInfo.name.equals(ai.name)) {
4718                        continue;
4719                    }
4720                    //  Found a persistent preference that can handle the intent.
4721                    if (DEBUG_PREFERRED || debug) {
4722                        Slog.v(TAG, "Returning persistent preferred activity: " +
4723                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4724                    }
4725                    return ri;
4726                }
4727            }
4728        }
4729        return null;
4730    }
4731
4732    // TODO: handle preferred activities missing while user has amnesia
4733    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4734            List<ResolveInfo> query, int priority, boolean always,
4735            boolean removeMatches, boolean debug, int userId) {
4736        if (!sUserManager.exists(userId)) return null;
4737        flags = updateFlagsForResolve(flags, userId, intent);
4738        // writer
4739        synchronized (mPackages) {
4740            if (intent.getSelector() != null) {
4741                intent = intent.getSelector();
4742            }
4743            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4744
4745            // Try to find a matching persistent preferred activity.
4746            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4747                    debug, userId);
4748
4749            // If a persistent preferred activity matched, use it.
4750            if (pri != null) {
4751                return pri;
4752            }
4753
4754            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4755            // Get the list of preferred activities that handle the intent
4756            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4757            List<PreferredActivity> prefs = pir != null
4758                    ? pir.queryIntent(intent, resolvedType,
4759                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4760                    : null;
4761            if (prefs != null && prefs.size() > 0) {
4762                boolean changed = false;
4763                try {
4764                    // First figure out how good the original match set is.
4765                    // We will only allow preferred activities that came
4766                    // from the same match quality.
4767                    int match = 0;
4768
4769                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4770
4771                    final int N = query.size();
4772                    for (int j=0; j<N; j++) {
4773                        final ResolveInfo ri = query.get(j);
4774                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4775                                + ": 0x" + Integer.toHexString(match));
4776                        if (ri.match > match) {
4777                            match = ri.match;
4778                        }
4779                    }
4780
4781                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4782                            + Integer.toHexString(match));
4783
4784                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4785                    final int M = prefs.size();
4786                    for (int i=0; i<M; i++) {
4787                        final PreferredActivity pa = prefs.get(i);
4788                        if (DEBUG_PREFERRED || debug) {
4789                            Slog.v(TAG, "Checking PreferredActivity ds="
4790                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4791                                    + "\n  component=" + pa.mPref.mComponent);
4792                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4793                        }
4794                        if (pa.mPref.mMatch != match) {
4795                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4796                                    + Integer.toHexString(pa.mPref.mMatch));
4797                            continue;
4798                        }
4799                        // If it's not an "always" type preferred activity and that's what we're
4800                        // looking for, skip it.
4801                        if (always && !pa.mPref.mAlways) {
4802                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4803                            continue;
4804                        }
4805                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4806                                flags | MATCH_DISABLED_COMPONENTS, userId);
4807                        if (DEBUG_PREFERRED || debug) {
4808                            Slog.v(TAG, "Found preferred activity:");
4809                            if (ai != null) {
4810                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4811                            } else {
4812                                Slog.v(TAG, "  null");
4813                            }
4814                        }
4815                        if (ai == null) {
4816                            // This previously registered preferred activity
4817                            // component is no longer known.  Most likely an update
4818                            // to the app was installed and in the new version this
4819                            // component no longer exists.  Clean it up by removing
4820                            // it from the preferred activities list, and skip it.
4821                            Slog.w(TAG, "Removing dangling preferred activity: "
4822                                    + pa.mPref.mComponent);
4823                            pir.removeFilter(pa);
4824                            changed = true;
4825                            continue;
4826                        }
4827                        for (int j=0; j<N; j++) {
4828                            final ResolveInfo ri = query.get(j);
4829                            if (!ri.activityInfo.applicationInfo.packageName
4830                                    .equals(ai.applicationInfo.packageName)) {
4831                                continue;
4832                            }
4833                            if (!ri.activityInfo.name.equals(ai.name)) {
4834                                continue;
4835                            }
4836
4837                            if (removeMatches) {
4838                                pir.removeFilter(pa);
4839                                changed = true;
4840                                if (DEBUG_PREFERRED) {
4841                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4842                                }
4843                                break;
4844                            }
4845
4846                            // Okay we found a previously set preferred or last chosen app.
4847                            // If the result set is different from when this
4848                            // was created, we need to clear it and re-ask the
4849                            // user their preference, if we're looking for an "always" type entry.
4850                            if (always && !pa.mPref.sameSet(query)) {
4851                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4852                                        + intent + " type " + resolvedType);
4853                                if (DEBUG_PREFERRED) {
4854                                    Slog.v(TAG, "Removing preferred activity since set changed "
4855                                            + pa.mPref.mComponent);
4856                                }
4857                                pir.removeFilter(pa);
4858                                // Re-add the filter as a "last chosen" entry (!always)
4859                                PreferredActivity lastChosen = new PreferredActivity(
4860                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4861                                pir.addFilter(lastChosen);
4862                                changed = true;
4863                                return null;
4864                            }
4865
4866                            // Yay! Either the set matched or we're looking for the last chosen
4867                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4868                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4869                            return ri;
4870                        }
4871                    }
4872                } finally {
4873                    if (changed) {
4874                        if (DEBUG_PREFERRED) {
4875                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4876                        }
4877                        scheduleWritePackageRestrictionsLocked(userId);
4878                    }
4879                }
4880            }
4881        }
4882        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4883        return null;
4884    }
4885
4886    /*
4887     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4888     */
4889    @Override
4890    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4891            int targetUserId) {
4892        mContext.enforceCallingOrSelfPermission(
4893                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4894        List<CrossProfileIntentFilter> matches =
4895                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4896        if (matches != null) {
4897            int size = matches.size();
4898            for (int i = 0; i < size; i++) {
4899                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4900            }
4901        }
4902        if (hasWebURI(intent)) {
4903            // cross-profile app linking works only towards the parent.
4904            final UserInfo parent = getProfileParent(sourceUserId);
4905            synchronized(mPackages) {
4906                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4907                        intent, resolvedType, 0, sourceUserId, parent.id);
4908                return xpDomainInfo != null;
4909            }
4910        }
4911        return false;
4912    }
4913
4914    private UserInfo getProfileParent(int userId) {
4915        final long identity = Binder.clearCallingIdentity();
4916        try {
4917            return sUserManager.getProfileParent(userId);
4918        } finally {
4919            Binder.restoreCallingIdentity(identity);
4920        }
4921    }
4922
4923    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4924            String resolvedType, int userId) {
4925        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4926        if (resolver != null) {
4927            return resolver.queryIntent(intent, resolvedType, false, userId);
4928        }
4929        return null;
4930    }
4931
4932    @Override
4933    public List<ResolveInfo> queryIntentActivities(Intent intent,
4934            String resolvedType, int flags, int userId) {
4935        if (!sUserManager.exists(userId)) return Collections.emptyList();
4936        flags = updateFlagsForResolve(flags, userId, intent);
4937        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4938        ComponentName comp = intent.getComponent();
4939        if (comp == null) {
4940            if (intent.getSelector() != null) {
4941                intent = intent.getSelector();
4942                comp = intent.getComponent();
4943            }
4944        }
4945
4946        if (comp != null) {
4947            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4948            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4949            if (ai != null) {
4950                final ResolveInfo ri = new ResolveInfo();
4951                ri.activityInfo = ai;
4952                list.add(ri);
4953            }
4954            return list;
4955        }
4956
4957        // reader
4958        synchronized (mPackages) {
4959            final String pkgName = intent.getPackage();
4960            if (pkgName == null) {
4961                List<CrossProfileIntentFilter> matchingFilters =
4962                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4963                // Check for results that need to skip the current profile.
4964                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4965                        resolvedType, flags, userId);
4966                if (xpResolveInfo != null) {
4967                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4968                    result.add(xpResolveInfo);
4969                    return filterIfNotSystemUser(result, userId);
4970                }
4971
4972                // Check for results in the current profile.
4973                List<ResolveInfo> result = mActivities.queryIntent(
4974                        intent, resolvedType, flags, userId);
4975                result = filterIfNotSystemUser(result, userId);
4976
4977                // Check for cross profile results.
4978                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4979                xpResolveInfo = queryCrossProfileIntents(
4980                        matchingFilters, intent, resolvedType, flags, userId,
4981                        hasNonNegativePriorityResult);
4982                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4983                    boolean isVisibleToUser = filterIfNotSystemUser(
4984                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4985                    if (isVisibleToUser) {
4986                        result.add(xpResolveInfo);
4987                        Collections.sort(result, mResolvePrioritySorter);
4988                    }
4989                }
4990                if (hasWebURI(intent)) {
4991                    CrossProfileDomainInfo xpDomainInfo = null;
4992                    final UserInfo parent = getProfileParent(userId);
4993                    if (parent != null) {
4994                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4995                                flags, userId, parent.id);
4996                    }
4997                    if (xpDomainInfo != null) {
4998                        if (xpResolveInfo != null) {
4999                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5000                            // in the result.
5001                            result.remove(xpResolveInfo);
5002                        }
5003                        if (result.size() == 0) {
5004                            result.add(xpDomainInfo.resolveInfo);
5005                            return result;
5006                        }
5007                    } else if (result.size() <= 1) {
5008                        return result;
5009                    }
5010                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5011                            xpDomainInfo, userId);
5012                    Collections.sort(result, mResolvePrioritySorter);
5013                }
5014                return result;
5015            }
5016            final PackageParser.Package pkg = mPackages.get(pkgName);
5017            if (pkg != null) {
5018                return filterIfNotSystemUser(
5019                        mActivities.queryIntentForPackage(
5020                                intent, resolvedType, flags, pkg.activities, userId),
5021                        userId);
5022            }
5023            return new ArrayList<ResolveInfo>();
5024        }
5025    }
5026
5027    private static class CrossProfileDomainInfo {
5028        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5029        ResolveInfo resolveInfo;
5030        /* Best domain verification status of the activities found in the other profile */
5031        int bestDomainVerificationStatus;
5032    }
5033
5034    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5035            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5036        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5037                sourceUserId)) {
5038            return null;
5039        }
5040        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5041                resolvedType, flags, parentUserId);
5042
5043        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5044            return null;
5045        }
5046        CrossProfileDomainInfo result = null;
5047        int size = resultTargetUser.size();
5048        for (int i = 0; i < size; i++) {
5049            ResolveInfo riTargetUser = resultTargetUser.get(i);
5050            // Intent filter verification is only for filters that specify a host. So don't return
5051            // those that handle all web uris.
5052            if (riTargetUser.handleAllWebDataURI) {
5053                continue;
5054            }
5055            String packageName = riTargetUser.activityInfo.packageName;
5056            PackageSetting ps = mSettings.mPackages.get(packageName);
5057            if (ps == null) {
5058                continue;
5059            }
5060            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5061            int status = (int)(verificationState >> 32);
5062            if (result == null) {
5063                result = new CrossProfileDomainInfo();
5064                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5065                        sourceUserId, parentUserId);
5066                result.bestDomainVerificationStatus = status;
5067            } else {
5068                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5069                        result.bestDomainVerificationStatus);
5070            }
5071        }
5072        // Don't consider matches with status NEVER across profiles.
5073        if (result != null && result.bestDomainVerificationStatus
5074                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5075            return null;
5076        }
5077        return result;
5078    }
5079
5080    /**
5081     * Verification statuses are ordered from the worse to the best, except for
5082     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5083     */
5084    private int bestDomainVerificationStatus(int status1, int status2) {
5085        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5086            return status2;
5087        }
5088        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5089            return status1;
5090        }
5091        return (int) MathUtils.max(status1, status2);
5092    }
5093
5094    private boolean isUserEnabled(int userId) {
5095        long callingId = Binder.clearCallingIdentity();
5096        try {
5097            UserInfo userInfo = sUserManager.getUserInfo(userId);
5098            return userInfo != null && userInfo.isEnabled();
5099        } finally {
5100            Binder.restoreCallingIdentity(callingId);
5101        }
5102    }
5103
5104    /**
5105     * Filter out activities with systemUserOnly flag set, when current user is not System.
5106     *
5107     * @return filtered list
5108     */
5109    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5110        if (userId == UserHandle.USER_SYSTEM) {
5111            return resolveInfos;
5112        }
5113        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5114            ResolveInfo info = resolveInfos.get(i);
5115            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5116                resolveInfos.remove(i);
5117            }
5118        }
5119        return resolveInfos;
5120    }
5121
5122    /**
5123     * @param resolveInfos list of resolve infos in descending priority order
5124     * @return if the list contains a resolve info with non-negative priority
5125     */
5126    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5127        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5128    }
5129
5130    private static boolean hasWebURI(Intent intent) {
5131        if (intent.getData() == null) {
5132            return false;
5133        }
5134        final String scheme = intent.getScheme();
5135        if (TextUtils.isEmpty(scheme)) {
5136            return false;
5137        }
5138        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5139    }
5140
5141    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5142            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5143            int userId) {
5144        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5145
5146        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5147            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5148                    candidates.size());
5149        }
5150
5151        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5152        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5153        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5154        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5155        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5156        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5157
5158        synchronized (mPackages) {
5159            final int count = candidates.size();
5160            // First, try to use linked apps. Partition the candidates into four lists:
5161            // one for the final results, one for the "do not use ever", one for "undefined status"
5162            // and finally one for "browser app type".
5163            for (int n=0; n<count; n++) {
5164                ResolveInfo info = candidates.get(n);
5165                String packageName = info.activityInfo.packageName;
5166                PackageSetting ps = mSettings.mPackages.get(packageName);
5167                if (ps != null) {
5168                    // Add to the special match all list (Browser use case)
5169                    if (info.handleAllWebDataURI) {
5170                        matchAllList.add(info);
5171                        continue;
5172                    }
5173                    // Try to get the status from User settings first
5174                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5175                    int status = (int)(packedStatus >> 32);
5176                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5177                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5178                        if (DEBUG_DOMAIN_VERIFICATION) {
5179                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5180                                    + " : linkgen=" + linkGeneration);
5181                        }
5182                        // Use link-enabled generation as preferredOrder, i.e.
5183                        // prefer newly-enabled over earlier-enabled.
5184                        info.preferredOrder = linkGeneration;
5185                        alwaysList.add(info);
5186                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5187                        if (DEBUG_DOMAIN_VERIFICATION) {
5188                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5189                        }
5190                        neverList.add(info);
5191                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5192                        if (DEBUG_DOMAIN_VERIFICATION) {
5193                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5194                        }
5195                        alwaysAskList.add(info);
5196                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5197                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5198                        if (DEBUG_DOMAIN_VERIFICATION) {
5199                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5200                        }
5201                        undefinedList.add(info);
5202                    }
5203                }
5204            }
5205
5206            // We'll want to include browser possibilities in a few cases
5207            boolean includeBrowser = false;
5208
5209            // First try to add the "always" resolution(s) for the current user, if any
5210            if (alwaysList.size() > 0) {
5211                result.addAll(alwaysList);
5212            } else {
5213                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5214                result.addAll(undefinedList);
5215                // Maybe add one for the other profile.
5216                if (xpDomainInfo != null && (
5217                        xpDomainInfo.bestDomainVerificationStatus
5218                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5219                    result.add(xpDomainInfo.resolveInfo);
5220                }
5221                includeBrowser = true;
5222            }
5223
5224            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5225            // If there were 'always' entries their preferred order has been set, so we also
5226            // back that off to make the alternatives equivalent
5227            if (alwaysAskList.size() > 0) {
5228                for (ResolveInfo i : result) {
5229                    i.preferredOrder = 0;
5230                }
5231                result.addAll(alwaysAskList);
5232                includeBrowser = true;
5233            }
5234
5235            if (includeBrowser) {
5236                // Also add browsers (all of them or only the default one)
5237                if (DEBUG_DOMAIN_VERIFICATION) {
5238                    Slog.v(TAG, "   ...including browsers in candidate set");
5239                }
5240                if ((matchFlags & MATCH_ALL) != 0) {
5241                    result.addAll(matchAllList);
5242                } else {
5243                    // Browser/generic handling case.  If there's a default browser, go straight
5244                    // to that (but only if there is no other higher-priority match).
5245                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5246                    int maxMatchPrio = 0;
5247                    ResolveInfo defaultBrowserMatch = null;
5248                    final int numCandidates = matchAllList.size();
5249                    for (int n = 0; n < numCandidates; n++) {
5250                        ResolveInfo info = matchAllList.get(n);
5251                        // track the highest overall match priority...
5252                        if (info.priority > maxMatchPrio) {
5253                            maxMatchPrio = info.priority;
5254                        }
5255                        // ...and the highest-priority default browser match
5256                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5257                            if (defaultBrowserMatch == null
5258                                    || (defaultBrowserMatch.priority < info.priority)) {
5259                                if (debug) {
5260                                    Slog.v(TAG, "Considering default browser match " + info);
5261                                }
5262                                defaultBrowserMatch = info;
5263                            }
5264                        }
5265                    }
5266                    if (defaultBrowserMatch != null
5267                            && defaultBrowserMatch.priority >= maxMatchPrio
5268                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5269                    {
5270                        if (debug) {
5271                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5272                        }
5273                        result.add(defaultBrowserMatch);
5274                    } else {
5275                        result.addAll(matchAllList);
5276                    }
5277                }
5278
5279                // If there is nothing selected, add all candidates and remove the ones that the user
5280                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5281                if (result.size() == 0) {
5282                    result.addAll(candidates);
5283                    result.removeAll(neverList);
5284                }
5285            }
5286        }
5287        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5288            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5289                    result.size());
5290            for (ResolveInfo info : result) {
5291                Slog.v(TAG, "  + " + info.activityInfo);
5292            }
5293        }
5294        return result;
5295    }
5296
5297    // Returns a packed value as a long:
5298    //
5299    // high 'int'-sized word: link status: undefined/ask/never/always.
5300    // low 'int'-sized word: relative priority among 'always' results.
5301    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5302        long result = ps.getDomainVerificationStatusForUser(userId);
5303        // if none available, get the master status
5304        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5305            if (ps.getIntentFilterVerificationInfo() != null) {
5306                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5307            }
5308        }
5309        return result;
5310    }
5311
5312    private ResolveInfo querySkipCurrentProfileIntents(
5313            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5314            int flags, int sourceUserId) {
5315        if (matchingFilters != null) {
5316            int size = matchingFilters.size();
5317            for (int i = 0; i < size; i ++) {
5318                CrossProfileIntentFilter filter = matchingFilters.get(i);
5319                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5320                    // Checking if there are activities in the target user that can handle the
5321                    // intent.
5322                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5323                            resolvedType, flags, sourceUserId);
5324                    if (resolveInfo != null) {
5325                        return resolveInfo;
5326                    }
5327                }
5328            }
5329        }
5330        return null;
5331    }
5332
5333    // Return matching ResolveInfo in target user if any.
5334    private ResolveInfo queryCrossProfileIntents(
5335            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5336            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5337        if (matchingFilters != null) {
5338            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5339            // match the same intent. For performance reasons, it is better not to
5340            // run queryIntent twice for the same userId
5341            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5342            int size = matchingFilters.size();
5343            for (int i = 0; i < size; i++) {
5344                CrossProfileIntentFilter filter = matchingFilters.get(i);
5345                int targetUserId = filter.getTargetUserId();
5346                boolean skipCurrentProfile =
5347                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5348                boolean skipCurrentProfileIfNoMatchFound =
5349                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5350                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5351                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5352                    // Checking if there are activities in the target user that can handle the
5353                    // intent.
5354                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5355                            resolvedType, flags, sourceUserId);
5356                    if (resolveInfo != null) return resolveInfo;
5357                    alreadyTriedUserIds.put(targetUserId, true);
5358                }
5359            }
5360        }
5361        return null;
5362    }
5363
5364    /**
5365     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5366     * will forward the intent to the filter's target user.
5367     * Otherwise, returns null.
5368     */
5369    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5370            String resolvedType, int flags, int sourceUserId) {
5371        int targetUserId = filter.getTargetUserId();
5372        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5373                resolvedType, flags, targetUserId);
5374        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5375                && isUserEnabled(targetUserId)) {
5376            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5377        }
5378        return null;
5379    }
5380
5381    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5382            int sourceUserId, int targetUserId) {
5383        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5384        long ident = Binder.clearCallingIdentity();
5385        boolean targetIsProfile;
5386        try {
5387            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5388        } finally {
5389            Binder.restoreCallingIdentity(ident);
5390        }
5391        String className;
5392        if (targetIsProfile) {
5393            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5394        } else {
5395            className = FORWARD_INTENT_TO_PARENT;
5396        }
5397        ComponentName forwardingActivityComponentName = new ComponentName(
5398                mAndroidApplication.packageName, className);
5399        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5400                sourceUserId);
5401        if (!targetIsProfile) {
5402            forwardingActivityInfo.showUserIcon = targetUserId;
5403            forwardingResolveInfo.noResourceId = true;
5404        }
5405        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5406        forwardingResolveInfo.priority = 0;
5407        forwardingResolveInfo.preferredOrder = 0;
5408        forwardingResolveInfo.match = 0;
5409        forwardingResolveInfo.isDefault = true;
5410        forwardingResolveInfo.filter = filter;
5411        forwardingResolveInfo.targetUserId = targetUserId;
5412        return forwardingResolveInfo;
5413    }
5414
5415    @Override
5416    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5417            Intent[] specifics, String[] specificTypes, Intent intent,
5418            String resolvedType, int flags, int userId) {
5419        if (!sUserManager.exists(userId)) return Collections.emptyList();
5420        flags = updateFlagsForResolve(flags, userId, intent);
5421        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5422                false, "query intent activity options");
5423        final String resultsAction = intent.getAction();
5424
5425        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5426                | PackageManager.GET_RESOLVED_FILTER, userId);
5427
5428        if (DEBUG_INTENT_MATCHING) {
5429            Log.v(TAG, "Query " + intent + ": " + results);
5430        }
5431
5432        int specificsPos = 0;
5433        int N;
5434
5435        // todo: note that the algorithm used here is O(N^2).  This
5436        // isn't a problem in our current environment, but if we start running
5437        // into situations where we have more than 5 or 10 matches then this
5438        // should probably be changed to something smarter...
5439
5440        // First we go through and resolve each of the specific items
5441        // that were supplied, taking care of removing any corresponding
5442        // duplicate items in the generic resolve list.
5443        if (specifics != null) {
5444            for (int i=0; i<specifics.length; i++) {
5445                final Intent sintent = specifics[i];
5446                if (sintent == null) {
5447                    continue;
5448                }
5449
5450                if (DEBUG_INTENT_MATCHING) {
5451                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5452                }
5453
5454                String action = sintent.getAction();
5455                if (resultsAction != null && resultsAction.equals(action)) {
5456                    // If this action was explicitly requested, then don't
5457                    // remove things that have it.
5458                    action = null;
5459                }
5460
5461                ResolveInfo ri = null;
5462                ActivityInfo ai = null;
5463
5464                ComponentName comp = sintent.getComponent();
5465                if (comp == null) {
5466                    ri = resolveIntent(
5467                        sintent,
5468                        specificTypes != null ? specificTypes[i] : null,
5469                            flags, userId);
5470                    if (ri == null) {
5471                        continue;
5472                    }
5473                    if (ri == mResolveInfo) {
5474                        // ACK!  Must do something better with this.
5475                    }
5476                    ai = ri.activityInfo;
5477                    comp = new ComponentName(ai.applicationInfo.packageName,
5478                            ai.name);
5479                } else {
5480                    ai = getActivityInfo(comp, flags, userId);
5481                    if (ai == null) {
5482                        continue;
5483                    }
5484                }
5485
5486                // Look for any generic query activities that are duplicates
5487                // of this specific one, and remove them from the results.
5488                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5489                N = results.size();
5490                int j;
5491                for (j=specificsPos; j<N; j++) {
5492                    ResolveInfo sri = results.get(j);
5493                    if ((sri.activityInfo.name.equals(comp.getClassName())
5494                            && sri.activityInfo.applicationInfo.packageName.equals(
5495                                    comp.getPackageName()))
5496                        || (action != null && sri.filter.matchAction(action))) {
5497                        results.remove(j);
5498                        if (DEBUG_INTENT_MATCHING) Log.v(
5499                            TAG, "Removing duplicate item from " + j
5500                            + " due to specific " + specificsPos);
5501                        if (ri == null) {
5502                            ri = sri;
5503                        }
5504                        j--;
5505                        N--;
5506                    }
5507                }
5508
5509                // Add this specific item to its proper place.
5510                if (ri == null) {
5511                    ri = new ResolveInfo();
5512                    ri.activityInfo = ai;
5513                }
5514                results.add(specificsPos, ri);
5515                ri.specificIndex = i;
5516                specificsPos++;
5517            }
5518        }
5519
5520        // Now we go through the remaining generic results and remove any
5521        // duplicate actions that are found here.
5522        N = results.size();
5523        for (int i=specificsPos; i<N-1; i++) {
5524            final ResolveInfo rii = results.get(i);
5525            if (rii.filter == null) {
5526                continue;
5527            }
5528
5529            // Iterate over all of the actions of this result's intent
5530            // filter...  typically this should be just one.
5531            final Iterator<String> it = rii.filter.actionsIterator();
5532            if (it == null) {
5533                continue;
5534            }
5535            while (it.hasNext()) {
5536                final String action = it.next();
5537                if (resultsAction != null && resultsAction.equals(action)) {
5538                    // If this action was explicitly requested, then don't
5539                    // remove things that have it.
5540                    continue;
5541                }
5542                for (int j=i+1; j<N; j++) {
5543                    final ResolveInfo rij = results.get(j);
5544                    if (rij.filter != null && rij.filter.hasAction(action)) {
5545                        results.remove(j);
5546                        if (DEBUG_INTENT_MATCHING) Log.v(
5547                            TAG, "Removing duplicate item from " + j
5548                            + " due to action " + action + " at " + i);
5549                        j--;
5550                        N--;
5551                    }
5552                }
5553            }
5554
5555            // If the caller didn't request filter information, drop it now
5556            // so we don't have to marshall/unmarshall it.
5557            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5558                rii.filter = null;
5559            }
5560        }
5561
5562        // Filter out the caller activity if so requested.
5563        if (caller != null) {
5564            N = results.size();
5565            for (int i=0; i<N; i++) {
5566                ActivityInfo ainfo = results.get(i).activityInfo;
5567                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5568                        && caller.getClassName().equals(ainfo.name)) {
5569                    results.remove(i);
5570                    break;
5571                }
5572            }
5573        }
5574
5575        // If the caller didn't request filter information,
5576        // drop them now so we don't have to
5577        // marshall/unmarshall it.
5578        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5579            N = results.size();
5580            for (int i=0; i<N; i++) {
5581                results.get(i).filter = null;
5582            }
5583        }
5584
5585        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5586        return results;
5587    }
5588
5589    @Override
5590    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5591            int userId) {
5592        if (!sUserManager.exists(userId)) return Collections.emptyList();
5593        flags = updateFlagsForResolve(flags, userId, intent);
5594        ComponentName comp = intent.getComponent();
5595        if (comp == null) {
5596            if (intent.getSelector() != null) {
5597                intent = intent.getSelector();
5598                comp = intent.getComponent();
5599            }
5600        }
5601        if (comp != null) {
5602            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5603            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5604            if (ai != null) {
5605                ResolveInfo ri = new ResolveInfo();
5606                ri.activityInfo = ai;
5607                list.add(ri);
5608            }
5609            return list;
5610        }
5611
5612        // reader
5613        synchronized (mPackages) {
5614            String pkgName = intent.getPackage();
5615            if (pkgName == null) {
5616                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5617            }
5618            final PackageParser.Package pkg = mPackages.get(pkgName);
5619            if (pkg != null) {
5620                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5621                        userId);
5622            }
5623            return null;
5624        }
5625    }
5626
5627    @Override
5628    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5629        if (!sUserManager.exists(userId)) return null;
5630        flags = updateFlagsForResolve(flags, userId, intent);
5631        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5632        if (query != null) {
5633            if (query.size() >= 1) {
5634                // If there is more than one service with the same priority,
5635                // just arbitrarily pick the first one.
5636                return query.get(0);
5637            }
5638        }
5639        return null;
5640    }
5641
5642    @Override
5643    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5644            int userId) {
5645        if (!sUserManager.exists(userId)) return Collections.emptyList();
5646        flags = updateFlagsForResolve(flags, userId, intent);
5647        ComponentName comp = intent.getComponent();
5648        if (comp == null) {
5649            if (intent.getSelector() != null) {
5650                intent = intent.getSelector();
5651                comp = intent.getComponent();
5652            }
5653        }
5654        if (comp != null) {
5655            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5656            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5657            if (si != null) {
5658                final ResolveInfo ri = new ResolveInfo();
5659                ri.serviceInfo = si;
5660                list.add(ri);
5661            }
5662            return list;
5663        }
5664
5665        // reader
5666        synchronized (mPackages) {
5667            String pkgName = intent.getPackage();
5668            if (pkgName == null) {
5669                return mServices.queryIntent(intent, resolvedType, flags, userId);
5670            }
5671            final PackageParser.Package pkg = mPackages.get(pkgName);
5672            if (pkg != null) {
5673                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5674                        userId);
5675            }
5676            return null;
5677        }
5678    }
5679
5680    @Override
5681    public List<ResolveInfo> queryIntentContentProviders(
5682            Intent intent, String resolvedType, int flags, int userId) {
5683        if (!sUserManager.exists(userId)) return Collections.emptyList();
5684        flags = updateFlagsForResolve(flags, userId, intent);
5685        ComponentName comp = intent.getComponent();
5686        if (comp == null) {
5687            if (intent.getSelector() != null) {
5688                intent = intent.getSelector();
5689                comp = intent.getComponent();
5690            }
5691        }
5692        if (comp != null) {
5693            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5694            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5695            if (pi != null) {
5696                final ResolveInfo ri = new ResolveInfo();
5697                ri.providerInfo = pi;
5698                list.add(ri);
5699            }
5700            return list;
5701        }
5702
5703        // reader
5704        synchronized (mPackages) {
5705            String pkgName = intent.getPackage();
5706            if (pkgName == null) {
5707                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5708            }
5709            final PackageParser.Package pkg = mPackages.get(pkgName);
5710            if (pkg != null) {
5711                return mProviders.queryIntentForPackage(
5712                        intent, resolvedType, flags, pkg.providers, userId);
5713            }
5714            return null;
5715        }
5716    }
5717
5718    @Override
5719    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5720        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5721        flags = updateFlagsForPackage(flags, userId, null);
5722        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5724
5725        // writer
5726        synchronized (mPackages) {
5727            ArrayList<PackageInfo> list;
5728            if (listUninstalled) {
5729                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5730                for (PackageSetting ps : mSettings.mPackages.values()) {
5731                    PackageInfo pi;
5732                    if (ps.pkg != null) {
5733                        pi = generatePackageInfo(ps.pkg, flags, userId);
5734                    } else {
5735                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5736                    }
5737                    if (pi != null) {
5738                        list.add(pi);
5739                    }
5740                }
5741            } else {
5742                list = new ArrayList<PackageInfo>(mPackages.size());
5743                for (PackageParser.Package p : mPackages.values()) {
5744                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5745                    if (pi != null) {
5746                        list.add(pi);
5747                    }
5748                }
5749            }
5750
5751            return new ParceledListSlice<PackageInfo>(list);
5752        }
5753    }
5754
5755    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5756            String[] permissions, boolean[] tmp, int flags, int userId) {
5757        int numMatch = 0;
5758        final PermissionsState permissionsState = ps.getPermissionsState();
5759        for (int i=0; i<permissions.length; i++) {
5760            final String permission = permissions[i];
5761            if (permissionsState.hasPermission(permission, userId)) {
5762                tmp[i] = true;
5763                numMatch++;
5764            } else {
5765                tmp[i] = false;
5766            }
5767        }
5768        if (numMatch == 0) {
5769            return;
5770        }
5771        PackageInfo pi;
5772        if (ps.pkg != null) {
5773            pi = generatePackageInfo(ps.pkg, flags, userId);
5774        } else {
5775            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5776        }
5777        // The above might return null in cases of uninstalled apps or install-state
5778        // skew across users/profiles.
5779        if (pi != null) {
5780            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5781                if (numMatch == permissions.length) {
5782                    pi.requestedPermissions = permissions;
5783                } else {
5784                    pi.requestedPermissions = new String[numMatch];
5785                    numMatch = 0;
5786                    for (int i=0; i<permissions.length; i++) {
5787                        if (tmp[i]) {
5788                            pi.requestedPermissions[numMatch] = permissions[i];
5789                            numMatch++;
5790                        }
5791                    }
5792                }
5793            }
5794            list.add(pi);
5795        }
5796    }
5797
5798    @Override
5799    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5800            String[] permissions, int flags, int userId) {
5801        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5802        flags = updateFlagsForPackage(flags, userId, permissions);
5803        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5804
5805        // writer
5806        synchronized (mPackages) {
5807            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5808            boolean[] tmpBools = new boolean[permissions.length];
5809            if (listUninstalled) {
5810                for (PackageSetting ps : mSettings.mPackages.values()) {
5811                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5812                }
5813            } else {
5814                for (PackageParser.Package pkg : mPackages.values()) {
5815                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5816                    if (ps != null) {
5817                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5818                                userId);
5819                    }
5820                }
5821            }
5822
5823            return new ParceledListSlice<PackageInfo>(list);
5824        }
5825    }
5826
5827    @Override
5828    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5829        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5830        flags = updateFlagsForApplication(flags, userId, null);
5831        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5832
5833        // writer
5834        synchronized (mPackages) {
5835            ArrayList<ApplicationInfo> list;
5836            if (listUninstalled) {
5837                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5838                for (PackageSetting ps : mSettings.mPackages.values()) {
5839                    ApplicationInfo ai;
5840                    if (ps.pkg != null) {
5841                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5842                                ps.readUserState(userId), userId);
5843                    } else {
5844                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5845                    }
5846                    if (ai != null) {
5847                        list.add(ai);
5848                    }
5849                }
5850            } else {
5851                list = new ArrayList<ApplicationInfo>(mPackages.size());
5852                for (PackageParser.Package p : mPackages.values()) {
5853                    if (p.mExtras != null) {
5854                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5855                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5856                        if (ai != null) {
5857                            list.add(ai);
5858                        }
5859                    }
5860                }
5861            }
5862
5863            return new ParceledListSlice<ApplicationInfo>(list);
5864        }
5865    }
5866
5867    @Override
5868    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5869        if (DISABLE_EPHEMERAL_APPS) {
5870            return null;
5871        }
5872
5873        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5874                "getEphemeralApplications");
5875        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5876                "getEphemeralApplications");
5877        synchronized (mPackages) {
5878            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5879                    .getEphemeralApplicationsLPw(userId);
5880            if (ephemeralApps != null) {
5881                return new ParceledListSlice<>(ephemeralApps);
5882            }
5883        }
5884        return null;
5885    }
5886
5887    @Override
5888    public boolean isEphemeralApplication(String packageName, int userId) {
5889        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5890                "isEphemeral");
5891        if (DISABLE_EPHEMERAL_APPS) {
5892            return false;
5893        }
5894
5895        if (!isCallerSameApp(packageName)) {
5896            return false;
5897        }
5898        synchronized (mPackages) {
5899            PackageParser.Package pkg = mPackages.get(packageName);
5900            if (pkg != null) {
5901                return pkg.applicationInfo.isEphemeralApp();
5902            }
5903        }
5904        return false;
5905    }
5906
5907    @Override
5908    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5909        if (DISABLE_EPHEMERAL_APPS) {
5910            return null;
5911        }
5912
5913        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5914                "getCookie");
5915        if (!isCallerSameApp(packageName)) {
5916            return null;
5917        }
5918        synchronized (mPackages) {
5919            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5920                    packageName, userId);
5921        }
5922    }
5923
5924    @Override
5925    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5926        if (DISABLE_EPHEMERAL_APPS) {
5927            return true;
5928        }
5929
5930        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5931                "setCookie");
5932        if (!isCallerSameApp(packageName)) {
5933            return false;
5934        }
5935        synchronized (mPackages) {
5936            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5937                    packageName, cookie, userId);
5938        }
5939    }
5940
5941    @Override
5942    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5943        if (DISABLE_EPHEMERAL_APPS) {
5944            return null;
5945        }
5946
5947        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5948                "getEphemeralApplicationIcon");
5949        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5950                "getEphemeralApplicationIcon");
5951        synchronized (mPackages) {
5952            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5953                    packageName, userId);
5954        }
5955    }
5956
5957    private boolean isCallerSameApp(String packageName) {
5958        PackageParser.Package pkg = mPackages.get(packageName);
5959        return pkg != null
5960                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5961    }
5962
5963    public List<ApplicationInfo> getPersistentApplications(int flags) {
5964        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5965
5966        // reader
5967        synchronized (mPackages) {
5968            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5969            final int userId = UserHandle.getCallingUserId();
5970            while (i.hasNext()) {
5971                final PackageParser.Package p = i.next();
5972                if (p.applicationInfo != null
5973                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5974                        && (!mSafeMode || isSystemApp(p))) {
5975                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5976                    if (ps != null) {
5977                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5978                                ps.readUserState(userId), userId);
5979                        if (ai != null) {
5980                            finalList.add(ai);
5981                        }
5982                    }
5983                }
5984            }
5985        }
5986
5987        return finalList;
5988    }
5989
5990    @Override
5991    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5992        if (!sUserManager.exists(userId)) return null;
5993        flags = updateFlagsForComponent(flags, userId, name);
5994        // reader
5995        synchronized (mPackages) {
5996            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5997            PackageSetting ps = provider != null
5998                    ? mSettings.mPackages.get(provider.owner.packageName)
5999                    : null;
6000            return ps != null
6001                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6002                    ? PackageParser.generateProviderInfo(provider, flags,
6003                            ps.readUserState(userId), userId)
6004                    : null;
6005        }
6006    }
6007
6008    /**
6009     * @deprecated
6010     */
6011    @Deprecated
6012    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6013        // reader
6014        synchronized (mPackages) {
6015            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6016                    .entrySet().iterator();
6017            final int userId = UserHandle.getCallingUserId();
6018            while (i.hasNext()) {
6019                Map.Entry<String, PackageParser.Provider> entry = i.next();
6020                PackageParser.Provider p = entry.getValue();
6021                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6022
6023                if (ps != null && p.syncable
6024                        && (!mSafeMode || (p.info.applicationInfo.flags
6025                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6026                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6027                            ps.readUserState(userId), userId);
6028                    if (info != null) {
6029                        outNames.add(entry.getKey());
6030                        outInfo.add(info);
6031                    }
6032                }
6033            }
6034        }
6035    }
6036
6037    @Override
6038    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6039            int uid, int flags) {
6040        final int userId = processName != null ? UserHandle.getUserId(uid)
6041                : UserHandle.getCallingUserId();
6042        if (!sUserManager.exists(userId)) return null;
6043        flags = updateFlagsForComponent(flags, userId, processName);
6044
6045        ArrayList<ProviderInfo> finalList = null;
6046        // reader
6047        synchronized (mPackages) {
6048            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6049            while (i.hasNext()) {
6050                final PackageParser.Provider p = i.next();
6051                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6052                if (ps != null && p.info.authority != null
6053                        && (processName == null
6054                                || (p.info.processName.equals(processName)
6055                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6056                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6057                    if (finalList == null) {
6058                        finalList = new ArrayList<ProviderInfo>(3);
6059                    }
6060                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6061                            ps.readUserState(userId), userId);
6062                    if (info != null) {
6063                        finalList.add(info);
6064                    }
6065                }
6066            }
6067        }
6068
6069        if (finalList != null) {
6070            Collections.sort(finalList, mProviderInitOrderSorter);
6071            return new ParceledListSlice<ProviderInfo>(finalList);
6072        }
6073
6074        return null;
6075    }
6076
6077    @Override
6078    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6079        // reader
6080        synchronized (mPackages) {
6081            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6082            return PackageParser.generateInstrumentationInfo(i, flags);
6083        }
6084    }
6085
6086    @Override
6087    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6088            int flags) {
6089        ArrayList<InstrumentationInfo> finalList =
6090            new ArrayList<InstrumentationInfo>();
6091
6092        // reader
6093        synchronized (mPackages) {
6094            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6095            while (i.hasNext()) {
6096                final PackageParser.Instrumentation p = i.next();
6097                if (targetPackage == null
6098                        || targetPackage.equals(p.info.targetPackage)) {
6099                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6100                            flags);
6101                    if (ii != null) {
6102                        finalList.add(ii);
6103                    }
6104                }
6105            }
6106        }
6107
6108        return finalList;
6109    }
6110
6111    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6112        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6113        if (overlays == null) {
6114            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6115            return;
6116        }
6117        for (PackageParser.Package opkg : overlays.values()) {
6118            // Not much to do if idmap fails: we already logged the error
6119            // and we certainly don't want to abort installation of pkg simply
6120            // because an overlay didn't fit properly. For these reasons,
6121            // ignore the return value of createIdmapForPackagePairLI.
6122            createIdmapForPackagePairLI(pkg, opkg);
6123        }
6124    }
6125
6126    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6127            PackageParser.Package opkg) {
6128        if (!opkg.mTrustedOverlay) {
6129            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6130                    opkg.baseCodePath + ": overlay not trusted");
6131            return false;
6132        }
6133        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6134        if (overlaySet == null) {
6135            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6136                    opkg.baseCodePath + " but target package has no known overlays");
6137            return false;
6138        }
6139        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6140        // TODO: generate idmap for split APKs
6141        try {
6142            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6143        } catch (InstallerException e) {
6144            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6145                    + opkg.baseCodePath);
6146            return false;
6147        }
6148        PackageParser.Package[] overlayArray =
6149            overlaySet.values().toArray(new PackageParser.Package[0]);
6150        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6151            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6152                return p1.mOverlayPriority - p2.mOverlayPriority;
6153            }
6154        };
6155        Arrays.sort(overlayArray, cmp);
6156
6157        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6158        int i = 0;
6159        for (PackageParser.Package p : overlayArray) {
6160            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6161        }
6162        return true;
6163    }
6164
6165    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6167        try {
6168            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6169        } finally {
6170            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6171        }
6172    }
6173
6174    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6175        final File[] files = dir.listFiles();
6176        if (ArrayUtils.isEmpty(files)) {
6177            Log.d(TAG, "No files in app dir " + dir);
6178            return;
6179        }
6180
6181        if (DEBUG_PACKAGE_SCANNING) {
6182            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6183                    + " flags=0x" + Integer.toHexString(parseFlags));
6184        }
6185
6186        for (File file : files) {
6187            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6188                    && !PackageInstallerService.isStageName(file.getName());
6189            if (!isPackage) {
6190                // Ignore entries which are not packages
6191                continue;
6192            }
6193            try {
6194                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6195                        scanFlags, currentTime, null);
6196            } catch (PackageManagerException e) {
6197                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6198
6199                // Delete invalid userdata apps
6200                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6201                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6202                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6203                    removeCodePathLI(file);
6204                }
6205            }
6206        }
6207    }
6208
6209    private static File getSettingsProblemFile() {
6210        File dataDir = Environment.getDataDirectory();
6211        File systemDir = new File(dataDir, "system");
6212        File fname = new File(systemDir, "uiderrors.txt");
6213        return fname;
6214    }
6215
6216    static void reportSettingsProblem(int priority, String msg) {
6217        logCriticalInfo(priority, msg);
6218    }
6219
6220    static void logCriticalInfo(int priority, String msg) {
6221        Slog.println(priority, TAG, msg);
6222        EventLogTags.writePmCriticalInfo(msg);
6223        try {
6224            File fname = getSettingsProblemFile();
6225            FileOutputStream out = new FileOutputStream(fname, true);
6226            PrintWriter pw = new FastPrintWriter(out);
6227            SimpleDateFormat formatter = new SimpleDateFormat();
6228            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6229            pw.println(dateString + ": " + msg);
6230            pw.close();
6231            FileUtils.setPermissions(
6232                    fname.toString(),
6233                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6234                    -1, -1);
6235        } catch (java.io.IOException e) {
6236        }
6237    }
6238
6239    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6240            PackageParser.Package pkg, File srcFile, int parseFlags)
6241            throws PackageManagerException {
6242        if (ps != null
6243                && ps.codePath.equals(srcFile)
6244                && ps.timeStamp == srcFile.lastModified()
6245                && !isCompatSignatureUpdateNeeded(pkg)
6246                && !isRecoverSignatureUpdateNeeded(pkg)) {
6247            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6248            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6249            ArraySet<PublicKey> signingKs;
6250            synchronized (mPackages) {
6251                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6252            }
6253            if (ps.signatures.mSignatures != null
6254                    && ps.signatures.mSignatures.length != 0
6255                    && signingKs != null) {
6256                // Optimization: reuse the existing cached certificates
6257                // if the package appears to be unchanged.
6258                pkg.mSignatures = ps.signatures.mSignatures;
6259                pkg.mSigningKeys = signingKs;
6260                return;
6261            }
6262
6263            Slog.w(TAG, "PackageSetting for " + ps.name
6264                    + " is missing signatures.  Collecting certs again to recover them.");
6265        } else {
6266            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6267        }
6268
6269        try {
6270            pp.collectCertificates(pkg, parseFlags);
6271        } catch (PackageParserException e) {
6272            throw PackageManagerException.from(e);
6273        }
6274    }
6275
6276    /**
6277     *  Traces a package scan.
6278     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6279     */
6280    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6281            long currentTime, UserHandle user) throws PackageManagerException {
6282        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6283        try {
6284            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6285        } finally {
6286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6287        }
6288    }
6289
6290    /**
6291     *  Scans a package and returns the newly parsed package.
6292     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6293     */
6294    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6295            long currentTime, UserHandle user) throws PackageManagerException {
6296        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6297        parseFlags |= mDefParseFlags;
6298        PackageParser pp = new PackageParser();
6299        pp.setSeparateProcesses(mSeparateProcesses);
6300        pp.setOnlyCoreApps(mOnlyCore);
6301        pp.setDisplayMetrics(mMetrics);
6302
6303        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6304            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6305        }
6306
6307        final PackageParser.Package pkg;
6308        try {
6309            pkg = pp.parsePackage(scanFile, parseFlags);
6310        } catch (PackageParserException e) {
6311            throw PackageManagerException.from(e);
6312        }
6313
6314        PackageSetting ps = null;
6315        PackageSetting updatedPkg;
6316        // reader
6317        synchronized (mPackages) {
6318            // Look to see if we already know about this package.
6319            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6320            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6321                // This package has been renamed to its original name.  Let's
6322                // use that.
6323                ps = mSettings.peekPackageLPr(oldName);
6324            }
6325            // If there was no original package, see one for the real package name.
6326            if (ps == null) {
6327                ps = mSettings.peekPackageLPr(pkg.packageName);
6328            }
6329            // Check to see if this package could be hiding/updating a system
6330            // package.  Must look for it either under the original or real
6331            // package name depending on our state.
6332            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6333            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6334        }
6335        boolean updatedPkgBetter = false;
6336        // First check if this is a system package that may involve an update
6337        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6338            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6339            // it needs to drop FLAG_PRIVILEGED.
6340            if (locationIsPrivileged(scanFile)) {
6341                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6342            } else {
6343                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6344            }
6345
6346            if (ps != null && !ps.codePath.equals(scanFile)) {
6347                // The path has changed from what was last scanned...  check the
6348                // version of the new path against what we have stored to determine
6349                // what to do.
6350                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6351                if (pkg.mVersionCode <= ps.versionCode) {
6352                    // The system package has been updated and the code path does not match
6353                    // Ignore entry. Skip it.
6354                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6355                            + " ignored: updated version " + ps.versionCode
6356                            + " better than this " + pkg.mVersionCode);
6357                    if (!updatedPkg.codePath.equals(scanFile)) {
6358                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6359                                + ps.name + " changing from " + updatedPkg.codePathString
6360                                + " to " + scanFile);
6361                        updatedPkg.codePath = scanFile;
6362                        updatedPkg.codePathString = scanFile.toString();
6363                        updatedPkg.resourcePath = scanFile;
6364                        updatedPkg.resourcePathString = scanFile.toString();
6365                    }
6366                    updatedPkg.pkg = pkg;
6367                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6368                            "Package " + ps.name + " at " + scanFile
6369                                    + " ignored: updated version " + ps.versionCode
6370                                    + " better than this " + pkg.mVersionCode);
6371                } else {
6372                    // The current app on the system partition is better than
6373                    // what we have updated to on the data partition; switch
6374                    // back to the system partition version.
6375                    // At this point, its safely assumed that package installation for
6376                    // apps in system partition will go through. If not there won't be a working
6377                    // version of the app
6378                    // writer
6379                    synchronized (mPackages) {
6380                        // Just remove the loaded entries from package lists.
6381                        mPackages.remove(ps.name);
6382                    }
6383
6384                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6385                            + " reverting from " + ps.codePathString
6386                            + ": new version " + pkg.mVersionCode
6387                            + " better than installed " + ps.versionCode);
6388
6389                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6390                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6391                    synchronized (mInstallLock) {
6392                        args.cleanUpResourcesLI();
6393                    }
6394                    synchronized (mPackages) {
6395                        mSettings.enableSystemPackageLPw(ps.name);
6396                    }
6397                    updatedPkgBetter = true;
6398                }
6399            }
6400        }
6401
6402        if (updatedPkg != null) {
6403            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6404            // initially
6405            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6406
6407            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6408            // flag set initially
6409            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6410                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6411            }
6412        }
6413
6414        // Verify certificates against what was last scanned
6415        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6416
6417        /*
6418         * A new system app appeared, but we already had a non-system one of the
6419         * same name installed earlier.
6420         */
6421        boolean shouldHideSystemApp = false;
6422        if (updatedPkg == null && ps != null
6423                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6424            /*
6425             * Check to make sure the signatures match first. If they don't,
6426             * wipe the installed application and its data.
6427             */
6428            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6429                    != PackageManager.SIGNATURE_MATCH) {
6430                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6431                        + " signatures don't match existing userdata copy; removing");
6432                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6433                ps = null;
6434            } else {
6435                /*
6436                 * If the newly-added system app is an older version than the
6437                 * already installed version, hide it. It will be scanned later
6438                 * and re-added like an update.
6439                 */
6440                if (pkg.mVersionCode <= ps.versionCode) {
6441                    shouldHideSystemApp = true;
6442                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6443                            + " but new version " + pkg.mVersionCode + " better than installed "
6444                            + ps.versionCode + "; hiding system");
6445                } else {
6446                    /*
6447                     * The newly found system app is a newer version that the
6448                     * one previously installed. Simply remove the
6449                     * already-installed application and replace it with our own
6450                     * while keeping the application data.
6451                     */
6452                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6453                            + " reverting from " + ps.codePathString + ": new version "
6454                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6455                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6456                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6457                    synchronized (mInstallLock) {
6458                        args.cleanUpResourcesLI();
6459                    }
6460                }
6461            }
6462        }
6463
6464        // The apk is forward locked (not public) if its code and resources
6465        // are kept in different files. (except for app in either system or
6466        // vendor path).
6467        // TODO grab this value from PackageSettings
6468        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6469            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6470                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6471            }
6472        }
6473
6474        // TODO: extend to support forward-locked splits
6475        String resourcePath = null;
6476        String baseResourcePath = null;
6477        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6478            if (ps != null && ps.resourcePathString != null) {
6479                resourcePath = ps.resourcePathString;
6480                baseResourcePath = ps.resourcePathString;
6481            } else {
6482                // Should not happen at all. Just log an error.
6483                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6484            }
6485        } else {
6486            resourcePath = pkg.codePath;
6487            baseResourcePath = pkg.baseCodePath;
6488        }
6489
6490        // Set application objects path explicitly.
6491        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6492        pkg.applicationInfo.setCodePath(pkg.codePath);
6493        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6494        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6495        pkg.applicationInfo.setResourcePath(resourcePath);
6496        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6497        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6498
6499        // Note that we invoke the following method only if we are about to unpack an application
6500        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6501                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6502
6503        /*
6504         * If the system app should be overridden by a previously installed
6505         * data, hide the system app now and let the /data/app scan pick it up
6506         * again.
6507         */
6508        if (shouldHideSystemApp) {
6509            synchronized (mPackages) {
6510                mSettings.disableSystemPackageLPw(pkg.packageName);
6511            }
6512        }
6513
6514        return scannedPkg;
6515    }
6516
6517    private static String fixProcessName(String defProcessName,
6518            String processName, int uid) {
6519        if (processName == null) {
6520            return defProcessName;
6521        }
6522        return processName;
6523    }
6524
6525    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6526            throws PackageManagerException {
6527        if (pkgSetting.signatures.mSignatures != null) {
6528            // Already existing package. Make sure signatures match
6529            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6530                    == PackageManager.SIGNATURE_MATCH;
6531            if (!match) {
6532                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6533                        == PackageManager.SIGNATURE_MATCH;
6534            }
6535            if (!match) {
6536                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6537                        == PackageManager.SIGNATURE_MATCH;
6538            }
6539            if (!match) {
6540                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6541                        + pkg.packageName + " signatures do not match the "
6542                        + "previously installed version; ignoring!");
6543            }
6544        }
6545
6546        // Check for shared user signatures
6547        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6548            // Already existing package. Make sure signatures match
6549            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6550                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6551            if (!match) {
6552                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6553                        == PackageManager.SIGNATURE_MATCH;
6554            }
6555            if (!match) {
6556                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6557                        == PackageManager.SIGNATURE_MATCH;
6558            }
6559            if (!match) {
6560                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6561                        "Package " + pkg.packageName
6562                        + " has no signatures that match those in shared user "
6563                        + pkgSetting.sharedUser.name + "; ignoring!");
6564            }
6565        }
6566    }
6567
6568    /**
6569     * Enforces that only the system UID or root's UID can call a method exposed
6570     * via Binder.
6571     *
6572     * @param message used as message if SecurityException is thrown
6573     * @throws SecurityException if the caller is not system or root
6574     */
6575    private static final void enforceSystemOrRoot(String message) {
6576        final int uid = Binder.getCallingUid();
6577        if (uid != Process.SYSTEM_UID && uid != 0) {
6578            throw new SecurityException(message);
6579        }
6580    }
6581
6582    @Override
6583    public void performFstrimIfNeeded() {
6584        enforceSystemOrRoot("Only the system can request fstrim");
6585
6586        // Before everything else, see whether we need to fstrim.
6587        try {
6588            IMountService ms = PackageHelper.getMountService();
6589            if (ms != null) {
6590                final boolean isUpgrade = isUpgrade();
6591                boolean doTrim = isUpgrade;
6592                if (doTrim) {
6593                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6594                } else {
6595                    final long interval = android.provider.Settings.Global.getLong(
6596                            mContext.getContentResolver(),
6597                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6598                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6599                    if (interval > 0) {
6600                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6601                        if (timeSinceLast > interval) {
6602                            doTrim = true;
6603                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6604                                    + "; running immediately");
6605                        }
6606                    }
6607                }
6608                if (doTrim) {
6609                    if (!isFirstBoot()) {
6610                        try {
6611                            ActivityManagerNative.getDefault().showBootMessage(
6612                                    mContext.getResources().getString(
6613                                            R.string.android_upgrading_fstrim), true);
6614                        } catch (RemoteException e) {
6615                        }
6616                    }
6617                    ms.runMaintenance();
6618                }
6619            } else {
6620                Slog.e(TAG, "Mount service unavailable!");
6621            }
6622        } catch (RemoteException e) {
6623            // Can't happen; MountService is local
6624        }
6625    }
6626
6627    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6628        List<ResolveInfo> ris = null;
6629        try {
6630            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6631                    intent, null, 0, userId);
6632        } catch (RemoteException e) {
6633        }
6634        ArraySet<String> pkgNames = new ArraySet<String>();
6635        if (ris != null) {
6636            for (ResolveInfo ri : ris) {
6637                pkgNames.add(ri.activityInfo.packageName);
6638            }
6639        }
6640        return pkgNames;
6641    }
6642
6643    @Override
6644    public void notifyPackageUse(String packageName) {
6645        synchronized (mPackages) {
6646            PackageParser.Package p = mPackages.get(packageName);
6647            if (p == null) {
6648                return;
6649            }
6650            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6651        }
6652    }
6653
6654    // TODO: this is not used nor needed. Delete it.
6655    @Override
6656    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6657        return performDexOptTraced(packageName, instructionSet, false);
6658    }
6659
6660    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles) {
6661        return performDexOptTraced(packageName, instructionSet, useProfiles);
6662    }
6663
6664    private boolean performDexOptTraced(String packageName, String instructionSet,
6665                boolean useProfiles) {
6666        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6667        try {
6668            return performDexOptInternal(packageName, instructionSet, useProfiles);
6669        } finally {
6670            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6671        }
6672    }
6673
6674    private boolean performDexOptInternal(String packageName, String instructionSet,
6675                boolean useProfiles) {
6676        PackageParser.Package p;
6677        final String targetInstructionSet;
6678        synchronized (mPackages) {
6679            p = mPackages.get(packageName);
6680            if (p == null) {
6681                return false;
6682            }
6683            mPackageUsage.write(false);
6684
6685            targetInstructionSet = instructionSet != null ? instructionSet :
6686                    getPrimaryInstructionSet(p.applicationInfo);
6687            if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6688                // Skip only if we do not use profiles since they might trigger a recompilation.
6689                return false;
6690            }
6691        }
6692        long callingId = Binder.clearCallingIdentity();
6693        try {
6694            synchronized (mInstallLock) {
6695                final String[] instructionSets = new String[] { targetInstructionSet };
6696                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6697                        true /* inclDependencies */, p.volumeUuid, useProfiles);
6698                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6699            }
6700        } finally {
6701            Binder.restoreCallingIdentity(callingId);
6702        }
6703    }
6704
6705    public ArraySet<String> getOptimizablePackages() {
6706        ArraySet<String> pkgs = new ArraySet<String>();
6707        synchronized (mPackages) {
6708            for (PackageParser.Package p : mPackages.values()) {
6709                if (PackageDexOptimizer.canOptimizePackage(p)) {
6710                    pkgs.add(p.packageName);
6711                }
6712            }
6713        }
6714        return pkgs;
6715    }
6716
6717    public void shutdown() {
6718        mPackageUsage.write(true);
6719    }
6720
6721    @Override
6722    public void forceDexOpt(String packageName) {
6723        enforceSystemOrRoot("forceDexOpt");
6724
6725        PackageParser.Package pkg;
6726        synchronized (mPackages) {
6727            pkg = mPackages.get(packageName);
6728            if (pkg == null) {
6729                throw new IllegalArgumentException("Unknown package: " + packageName);
6730            }
6731        }
6732
6733        synchronized (mInstallLock) {
6734            final String[] instructionSets = new String[] {
6735                    getPrimaryInstructionSet(pkg.applicationInfo) };
6736
6737            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6738
6739            // Whoever is calling forceDexOpt wants a fully compiled package.
6740            // Don't use profiles since that may cause compilation to be skipped.
6741            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6742                    true /* inclDependencies */, pkg.volumeUuid, false /* useProfiles */);
6743
6744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6745            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6746                throw new IllegalStateException("Failed to dexopt: " + res);
6747            }
6748        }
6749    }
6750
6751    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6752        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6753            Slog.w(TAG, "Unable to update from " + oldPkg.name
6754                    + " to " + newPkg.packageName
6755                    + ": old package not in system partition");
6756            return false;
6757        } else if (mPackages.get(oldPkg.name) != null) {
6758            Slog.w(TAG, "Unable to update from " + oldPkg.name
6759                    + " to " + newPkg.packageName
6760                    + ": old package still exists");
6761            return false;
6762        }
6763        return true;
6764    }
6765
6766    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6767        // TODO: triage flags as part of 26466827
6768        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6769
6770        boolean res = true;
6771        final int[] users = sUserManager.getUserIds();
6772        for (int user : users) {
6773            try {
6774                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6775            } catch (InstallerException e) {
6776                Slog.w(TAG, "Failed to delete data directory", e);
6777                res = false;
6778            }
6779        }
6780        return res;
6781    }
6782
6783    void removeCodePathLI(File codePath) {
6784        if (codePath.isDirectory()) {
6785            try {
6786                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6787            } catch (InstallerException e) {
6788                Slog.w(TAG, "Failed to remove code path", e);
6789            }
6790        } else {
6791            codePath.delete();
6792        }
6793    }
6794
6795    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6796        try {
6797            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6798        } catch (InstallerException e) {
6799            Slog.w(TAG, "Failed to destroy app data", e);
6800        }
6801    }
6802
6803    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6804            int appId, String seinfo) {
6805        try {
6806            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6807        } catch (InstallerException e) {
6808            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6809        }
6810    }
6811
6812    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6813        // TODO: triage flags as part of 26466827
6814        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6815
6816        final int[] users = sUserManager.getUserIds();
6817        for (int user : users) {
6818            try {
6819                mInstaller.clearAppData(volumeUuid, packageName, user,
6820                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6821            } catch (InstallerException e) {
6822                Slog.w(TAG, "Failed to delete code cache directory", e);
6823            }
6824        }
6825    }
6826
6827    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6828            PackageParser.Package changingLib) {
6829        if (file.path != null) {
6830            usesLibraryFiles.add(file.path);
6831            return;
6832        }
6833        PackageParser.Package p = mPackages.get(file.apk);
6834        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6835            // If we are doing this while in the middle of updating a library apk,
6836            // then we need to make sure to use that new apk for determining the
6837            // dependencies here.  (We haven't yet finished committing the new apk
6838            // to the package manager state.)
6839            if (p == null || p.packageName.equals(changingLib.packageName)) {
6840                p = changingLib;
6841            }
6842        }
6843        if (p != null) {
6844            usesLibraryFiles.addAll(p.getAllCodePaths());
6845        }
6846    }
6847
6848    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6849            PackageParser.Package changingLib) throws PackageManagerException {
6850        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6851            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6852            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6853            for (int i=0; i<N; i++) {
6854                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6855                if (file == null) {
6856                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6857                            "Package " + pkg.packageName + " requires unavailable shared library "
6858                            + pkg.usesLibraries.get(i) + "; failing!");
6859                }
6860                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6861            }
6862            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6863            for (int i=0; i<N; i++) {
6864                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6865                if (file == null) {
6866                    Slog.w(TAG, "Package " + pkg.packageName
6867                            + " desires unavailable shared library "
6868                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6869                } else {
6870                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6871                }
6872            }
6873            N = usesLibraryFiles.size();
6874            if (N > 0) {
6875                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6876            } else {
6877                pkg.usesLibraryFiles = null;
6878            }
6879        }
6880    }
6881
6882    private static boolean hasString(List<String> list, List<String> which) {
6883        if (list == null) {
6884            return false;
6885        }
6886        for (int i=list.size()-1; i>=0; i--) {
6887            for (int j=which.size()-1; j>=0; j--) {
6888                if (which.get(j).equals(list.get(i))) {
6889                    return true;
6890                }
6891            }
6892        }
6893        return false;
6894    }
6895
6896    private void updateAllSharedLibrariesLPw() {
6897        for (PackageParser.Package pkg : mPackages.values()) {
6898            try {
6899                updateSharedLibrariesLPw(pkg, null);
6900            } catch (PackageManagerException e) {
6901                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6902            }
6903        }
6904    }
6905
6906    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6907            PackageParser.Package changingPkg) {
6908        ArrayList<PackageParser.Package> res = null;
6909        for (PackageParser.Package pkg : mPackages.values()) {
6910            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6911                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6912                if (res == null) {
6913                    res = new ArrayList<PackageParser.Package>();
6914                }
6915                res.add(pkg);
6916                try {
6917                    updateSharedLibrariesLPw(pkg, changingPkg);
6918                } catch (PackageManagerException e) {
6919                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6920                }
6921            }
6922        }
6923        return res;
6924    }
6925
6926    /**
6927     * Derive the value of the {@code cpuAbiOverride} based on the provided
6928     * value and an optional stored value from the package settings.
6929     */
6930    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6931        String cpuAbiOverride = null;
6932
6933        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6934            cpuAbiOverride = null;
6935        } else if (abiOverride != null) {
6936            cpuAbiOverride = abiOverride;
6937        } else if (settings != null) {
6938            cpuAbiOverride = settings.cpuAbiOverrideString;
6939        }
6940
6941        return cpuAbiOverride;
6942    }
6943
6944    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6945            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6946        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6947        try {
6948            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6949        } finally {
6950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6951        }
6952    }
6953
6954    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6955            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6956        boolean success = false;
6957        try {
6958            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6959                    currentTime, user);
6960            success = true;
6961            return res;
6962        } finally {
6963            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6964                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6965            }
6966        }
6967    }
6968
6969    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6970            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6971        final File scanFile = new File(pkg.codePath);
6972        if (pkg.applicationInfo.getCodePath() == null ||
6973                pkg.applicationInfo.getResourcePath() == null) {
6974            // Bail out. The resource and code paths haven't been set.
6975            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6976                    "Code and resource paths haven't been set correctly");
6977        }
6978
6979        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6980            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6981        } else {
6982            // Only allow system apps to be flagged as core apps.
6983            pkg.coreApp = false;
6984        }
6985
6986        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6987            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6988        }
6989
6990        if (mCustomResolverComponentName != null &&
6991                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6992            setUpCustomResolverActivity(pkg);
6993        }
6994
6995        if (pkg.packageName.equals("android")) {
6996            synchronized (mPackages) {
6997                if (mAndroidApplication != null) {
6998                    Slog.w(TAG, "*************************************************");
6999                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7000                    Slog.w(TAG, " file=" + scanFile);
7001                    Slog.w(TAG, "*************************************************");
7002                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7003                            "Core android package being redefined.  Skipping.");
7004                }
7005
7006                // Set up information for our fall-back user intent resolution activity.
7007                mPlatformPackage = pkg;
7008                pkg.mVersionCode = mSdkVersion;
7009                mAndroidApplication = pkg.applicationInfo;
7010
7011                if (!mResolverReplaced) {
7012                    mResolveActivity.applicationInfo = mAndroidApplication;
7013                    mResolveActivity.name = ResolverActivity.class.getName();
7014                    mResolveActivity.packageName = mAndroidApplication.packageName;
7015                    mResolveActivity.processName = "system:ui";
7016                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7017                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7018                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7019                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7020                    mResolveActivity.exported = true;
7021                    mResolveActivity.enabled = true;
7022                    mResolveInfo.activityInfo = mResolveActivity;
7023                    mResolveInfo.priority = 0;
7024                    mResolveInfo.preferredOrder = 0;
7025                    mResolveInfo.match = 0;
7026                    mResolveComponentName = new ComponentName(
7027                            mAndroidApplication.packageName, mResolveActivity.name);
7028                }
7029            }
7030        }
7031
7032        if (DEBUG_PACKAGE_SCANNING) {
7033            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7034                Log.d(TAG, "Scanning package " + pkg.packageName);
7035        }
7036
7037        if (mPackages.containsKey(pkg.packageName)
7038                || mSharedLibraries.containsKey(pkg.packageName)) {
7039            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7040                    "Application package " + pkg.packageName
7041                    + " already installed.  Skipping duplicate.");
7042        }
7043
7044        // If we're only installing presumed-existing packages, require that the
7045        // scanned APK is both already known and at the path previously established
7046        // for it.  Previously unknown packages we pick up normally, but if we have an
7047        // a priori expectation about this package's install presence, enforce it.
7048        // With a singular exception for new system packages. When an OTA contains
7049        // a new system package, we allow the codepath to change from a system location
7050        // to the user-installed location. If we don't allow this change, any newer,
7051        // user-installed version of the application will be ignored.
7052        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7053            if (mExpectingBetter.containsKey(pkg.packageName)) {
7054                logCriticalInfo(Log.WARN,
7055                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7056            } else {
7057                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7058                if (known != null) {
7059                    if (DEBUG_PACKAGE_SCANNING) {
7060                        Log.d(TAG, "Examining " + pkg.codePath
7061                                + " and requiring known paths " + known.codePathString
7062                                + " & " + known.resourcePathString);
7063                    }
7064                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7065                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7066                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7067                                "Application package " + pkg.packageName
7068                                + " found at " + pkg.applicationInfo.getCodePath()
7069                                + " but expected at " + known.codePathString + "; ignoring.");
7070                    }
7071                }
7072            }
7073        }
7074
7075        // Initialize package source and resource directories
7076        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7077        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7078
7079        SharedUserSetting suid = null;
7080        PackageSetting pkgSetting = null;
7081
7082        if (!isSystemApp(pkg)) {
7083            // Only system apps can use these features.
7084            pkg.mOriginalPackages = null;
7085            pkg.mRealPackage = null;
7086            pkg.mAdoptPermissions = null;
7087        }
7088
7089        // writer
7090        synchronized (mPackages) {
7091            if (pkg.mSharedUserId != null) {
7092                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7093                if (suid == null) {
7094                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7095                            "Creating application package " + pkg.packageName
7096                            + " for shared user failed");
7097                }
7098                if (DEBUG_PACKAGE_SCANNING) {
7099                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7100                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7101                                + "): packages=" + suid.packages);
7102                }
7103            }
7104
7105            // Check if we are renaming from an original package name.
7106            PackageSetting origPackage = null;
7107            String realName = null;
7108            if (pkg.mOriginalPackages != null) {
7109                // This package may need to be renamed to a previously
7110                // installed name.  Let's check on that...
7111                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7112                if (pkg.mOriginalPackages.contains(renamed)) {
7113                    // This package had originally been installed as the
7114                    // original name, and we have already taken care of
7115                    // transitioning to the new one.  Just update the new
7116                    // one to continue using the old name.
7117                    realName = pkg.mRealPackage;
7118                    if (!pkg.packageName.equals(renamed)) {
7119                        // Callers into this function may have already taken
7120                        // care of renaming the package; only do it here if
7121                        // it is not already done.
7122                        pkg.setPackageName(renamed);
7123                    }
7124
7125                } else {
7126                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7127                        if ((origPackage = mSettings.peekPackageLPr(
7128                                pkg.mOriginalPackages.get(i))) != null) {
7129                            // We do have the package already installed under its
7130                            // original name...  should we use it?
7131                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7132                                // New package is not compatible with original.
7133                                origPackage = null;
7134                                continue;
7135                            } else if (origPackage.sharedUser != null) {
7136                                // Make sure uid is compatible between packages.
7137                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7138                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7139                                            + " to " + pkg.packageName + ": old uid "
7140                                            + origPackage.sharedUser.name
7141                                            + " differs from " + pkg.mSharedUserId);
7142                                    origPackage = null;
7143                                    continue;
7144                                }
7145                            } else {
7146                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7147                                        + pkg.packageName + " to old name " + origPackage.name);
7148                            }
7149                            break;
7150                        }
7151                    }
7152                }
7153            }
7154
7155            if (mTransferedPackages.contains(pkg.packageName)) {
7156                Slog.w(TAG, "Package " + pkg.packageName
7157                        + " was transferred to another, but its .apk remains");
7158            }
7159
7160            // Just create the setting, don't add it yet. For already existing packages
7161            // the PkgSetting exists already and doesn't have to be created.
7162            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7163                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7164                    pkg.applicationInfo.primaryCpuAbi,
7165                    pkg.applicationInfo.secondaryCpuAbi,
7166                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7167                    user, false);
7168            if (pkgSetting == null) {
7169                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7170                        "Creating application package " + pkg.packageName + " failed");
7171            }
7172
7173            if (pkgSetting.origPackage != null) {
7174                // If we are first transitioning from an original package,
7175                // fix up the new package's name now.  We need to do this after
7176                // looking up the package under its new name, so getPackageLP
7177                // can take care of fiddling things correctly.
7178                pkg.setPackageName(origPackage.name);
7179
7180                // File a report about this.
7181                String msg = "New package " + pkgSetting.realName
7182                        + " renamed to replace old package " + pkgSetting.name;
7183                reportSettingsProblem(Log.WARN, msg);
7184
7185                // Make a note of it.
7186                mTransferedPackages.add(origPackage.name);
7187
7188                // No longer need to retain this.
7189                pkgSetting.origPackage = null;
7190            }
7191
7192            if (realName != null) {
7193                // Make a note of it.
7194                mTransferedPackages.add(pkg.packageName);
7195            }
7196
7197            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7198                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7199            }
7200
7201            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7202                // Check all shared libraries and map to their actual file path.
7203                // We only do this here for apps not on a system dir, because those
7204                // are the only ones that can fail an install due to this.  We
7205                // will take care of the system apps by updating all of their
7206                // library paths after the scan is done.
7207                updateSharedLibrariesLPw(pkg, null);
7208            }
7209
7210            if (mFoundPolicyFile) {
7211                SELinuxMMAC.assignSeinfoValue(pkg);
7212            }
7213
7214            pkg.applicationInfo.uid = pkgSetting.appId;
7215            pkg.mExtras = pkgSetting;
7216            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7217                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7218                    // We just determined the app is signed correctly, so bring
7219                    // over the latest parsed certs.
7220                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7221                } else {
7222                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7223                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7224                                "Package " + pkg.packageName + " upgrade keys do not match the "
7225                                + "previously installed version");
7226                    } else {
7227                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7228                        String msg = "System package " + pkg.packageName
7229                            + " signature changed; retaining data.";
7230                        reportSettingsProblem(Log.WARN, msg);
7231                    }
7232                }
7233            } else {
7234                try {
7235                    verifySignaturesLP(pkgSetting, pkg);
7236                    // We just determined the app is signed correctly, so bring
7237                    // over the latest parsed certs.
7238                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7239                } catch (PackageManagerException e) {
7240                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7241                        throw e;
7242                    }
7243                    // The signature has changed, but this package is in the system
7244                    // image...  let's recover!
7245                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7246                    // However...  if this package is part of a shared user, but it
7247                    // doesn't match the signature of the shared user, let's fail.
7248                    // What this means is that you can't change the signatures
7249                    // associated with an overall shared user, which doesn't seem all
7250                    // that unreasonable.
7251                    if (pkgSetting.sharedUser != null) {
7252                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7253                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7254                            throw new PackageManagerException(
7255                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7256                                            "Signature mismatch for shared user: "
7257                                            + pkgSetting.sharedUser);
7258                        }
7259                    }
7260                    // File a report about this.
7261                    String msg = "System package " + pkg.packageName
7262                        + " signature changed; retaining data.";
7263                    reportSettingsProblem(Log.WARN, msg);
7264                }
7265            }
7266            // Verify that this new package doesn't have any content providers
7267            // that conflict with existing packages.  Only do this if the
7268            // package isn't already installed, since we don't want to break
7269            // things that are installed.
7270            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7271                final int N = pkg.providers.size();
7272                int i;
7273                for (i=0; i<N; i++) {
7274                    PackageParser.Provider p = pkg.providers.get(i);
7275                    if (p.info.authority != null) {
7276                        String names[] = p.info.authority.split(";");
7277                        for (int j = 0; j < names.length; j++) {
7278                            if (mProvidersByAuthority.containsKey(names[j])) {
7279                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7280                                final String otherPackageName =
7281                                        ((other != null && other.getComponentName() != null) ?
7282                                                other.getComponentName().getPackageName() : "?");
7283                                throw new PackageManagerException(
7284                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7285                                                "Can't install because provider name " + names[j]
7286                                                + " (in package " + pkg.applicationInfo.packageName
7287                                                + ") is already used by " + otherPackageName);
7288                            }
7289                        }
7290                    }
7291                }
7292            }
7293
7294            if (pkg.mAdoptPermissions != null) {
7295                // This package wants to adopt ownership of permissions from
7296                // another package.
7297                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7298                    final String origName = pkg.mAdoptPermissions.get(i);
7299                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7300                    if (orig != null) {
7301                        if (verifyPackageUpdateLPr(orig, pkg)) {
7302                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7303                                    + pkg.packageName);
7304                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7305                        }
7306                    }
7307                }
7308            }
7309        }
7310
7311        final String pkgName = pkg.packageName;
7312
7313        final long scanFileTime = scanFile.lastModified();
7314        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7315        pkg.applicationInfo.processName = fixProcessName(
7316                pkg.applicationInfo.packageName,
7317                pkg.applicationInfo.processName,
7318                pkg.applicationInfo.uid);
7319
7320        if (pkg != mPlatformPackage) {
7321            // Get all of our default paths setup
7322            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7323        }
7324
7325        final String path = scanFile.getPath();
7326        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7327
7328        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7329            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7330
7331            // Some system apps still use directory structure for native libraries
7332            // in which case we might end up not detecting abi solely based on apk
7333            // structure. Try to detect abi based on directory structure.
7334            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7335                    pkg.applicationInfo.primaryCpuAbi == null) {
7336                setBundledAppAbisAndRoots(pkg, pkgSetting);
7337                setNativeLibraryPaths(pkg);
7338            }
7339
7340        } else {
7341            if ((scanFlags & SCAN_MOVE) != 0) {
7342                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7343                // but we already have this packages package info in the PackageSetting. We just
7344                // use that and derive the native library path based on the new codepath.
7345                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7346                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7347            }
7348
7349            // Set native library paths again. For moves, the path will be updated based on the
7350            // ABIs we've determined above. For non-moves, the path will be updated based on the
7351            // ABIs we determined during compilation, but the path will depend on the final
7352            // package path (after the rename away from the stage path).
7353            setNativeLibraryPaths(pkg);
7354        }
7355
7356        // This is a special case for the "system" package, where the ABI is
7357        // dictated by the zygote configuration (and init.rc). We should keep track
7358        // of this ABI so that we can deal with "normal" applications that run under
7359        // the same UID correctly.
7360        if (mPlatformPackage == pkg) {
7361            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7362                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7363        }
7364
7365        // If there's a mismatch between the abi-override in the package setting
7366        // and the abiOverride specified for the install. Warn about this because we
7367        // would've already compiled the app without taking the package setting into
7368        // account.
7369        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7370            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7371                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7372                        " for package " + pkg.packageName);
7373            }
7374        }
7375
7376        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7377        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7378        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7379
7380        // Copy the derived override back to the parsed package, so that we can
7381        // update the package settings accordingly.
7382        pkg.cpuAbiOverride = cpuAbiOverride;
7383
7384        if (DEBUG_ABI_SELECTION) {
7385            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7386                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7387                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7388        }
7389
7390        // Push the derived path down into PackageSettings so we know what to
7391        // clean up at uninstall time.
7392        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7393
7394        if (DEBUG_ABI_SELECTION) {
7395            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7396                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7397                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7398        }
7399
7400        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7401            // We don't do this here during boot because we can do it all
7402            // at once after scanning all existing packages.
7403            //
7404            // We also do this *before* we perform dexopt on this package, so that
7405            // we can avoid redundant dexopts, and also to make sure we've got the
7406            // code and package path correct.
7407            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7408                    pkg, true /* boot complete */);
7409        }
7410
7411        if (mFactoryTest && pkg.requestedPermissions.contains(
7412                android.Manifest.permission.FACTORY_TEST)) {
7413            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7414        }
7415
7416        ArrayList<PackageParser.Package> clientLibPkgs = null;
7417
7418        // writer
7419        synchronized (mPackages) {
7420            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7421                // Only system apps can add new shared libraries.
7422                if (pkg.libraryNames != null) {
7423                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7424                        String name = pkg.libraryNames.get(i);
7425                        boolean allowed = false;
7426                        if (pkg.isUpdatedSystemApp()) {
7427                            // New library entries can only be added through the
7428                            // system image.  This is important to get rid of a lot
7429                            // of nasty edge cases: for example if we allowed a non-
7430                            // system update of the app to add a library, then uninstalling
7431                            // the update would make the library go away, and assumptions
7432                            // we made such as through app install filtering would now
7433                            // have allowed apps on the device which aren't compatible
7434                            // with it.  Better to just have the restriction here, be
7435                            // conservative, and create many fewer cases that can negatively
7436                            // impact the user experience.
7437                            final PackageSetting sysPs = mSettings
7438                                    .getDisabledSystemPkgLPr(pkg.packageName);
7439                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7440                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7441                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7442                                        allowed = true;
7443                                        break;
7444                                    }
7445                                }
7446                            }
7447                        } else {
7448                            allowed = true;
7449                        }
7450                        if (allowed) {
7451                            if (!mSharedLibraries.containsKey(name)) {
7452                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7453                            } else if (!name.equals(pkg.packageName)) {
7454                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7455                                        + name + " already exists; skipping");
7456                            }
7457                        } else {
7458                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7459                                    + name + " that is not declared on system image; skipping");
7460                        }
7461                    }
7462                    if ((scanFlags & SCAN_BOOTING) == 0) {
7463                        // If we are not booting, we need to update any applications
7464                        // that are clients of our shared library.  If we are booting,
7465                        // this will all be done once the scan is complete.
7466                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7467                    }
7468                }
7469            }
7470        }
7471
7472        // Request the ActivityManager to kill the process(only for existing packages)
7473        // so that we do not end up in a confused state while the user is still using the older
7474        // version of the application while the new one gets installed.
7475        if ((scanFlags & SCAN_REPLACING) != 0) {
7476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7477
7478            killApplication(pkg.applicationInfo.packageName,
7479                        pkg.applicationInfo.uid, "replace pkg");
7480
7481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7482        }
7483
7484        // Also need to kill any apps that are dependent on the library.
7485        if (clientLibPkgs != null) {
7486            for (int i=0; i<clientLibPkgs.size(); i++) {
7487                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7488                killApplication(clientPkg.applicationInfo.packageName,
7489                        clientPkg.applicationInfo.uid, "update lib");
7490            }
7491        }
7492
7493        // Make sure we're not adding any bogus keyset info
7494        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7495        ksms.assertScannedPackageValid(pkg);
7496
7497        // writer
7498        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7499
7500        boolean createIdmapFailed = false;
7501        synchronized (mPackages) {
7502            // We don't expect installation to fail beyond this point
7503
7504            // Add the new setting to mSettings
7505            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7506            // Add the new setting to mPackages
7507            mPackages.put(pkg.applicationInfo.packageName, pkg);
7508            // Make sure we don't accidentally delete its data.
7509            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7510            while (iter.hasNext()) {
7511                PackageCleanItem item = iter.next();
7512                if (pkgName.equals(item.packageName)) {
7513                    iter.remove();
7514                }
7515            }
7516
7517            // Take care of first install / last update times.
7518            if (currentTime != 0) {
7519                if (pkgSetting.firstInstallTime == 0) {
7520                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7521                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7522                    pkgSetting.lastUpdateTime = currentTime;
7523                }
7524            } else if (pkgSetting.firstInstallTime == 0) {
7525                // We need *something*.  Take time time stamp of the file.
7526                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7527            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7528                if (scanFileTime != pkgSetting.timeStamp) {
7529                    // A package on the system image has changed; consider this
7530                    // to be an update.
7531                    pkgSetting.lastUpdateTime = scanFileTime;
7532                }
7533            }
7534
7535            // Add the package's KeySets to the global KeySetManagerService
7536            ksms.addScannedPackageLPw(pkg);
7537
7538            int N = pkg.providers.size();
7539            StringBuilder r = null;
7540            int i;
7541            for (i=0; i<N; i++) {
7542                PackageParser.Provider p = pkg.providers.get(i);
7543                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7544                        p.info.processName, pkg.applicationInfo.uid);
7545                mProviders.addProvider(p);
7546                p.syncable = p.info.isSyncable;
7547                if (p.info.authority != null) {
7548                    String names[] = p.info.authority.split(";");
7549                    p.info.authority = null;
7550                    for (int j = 0; j < names.length; j++) {
7551                        if (j == 1 && p.syncable) {
7552                            // We only want the first authority for a provider to possibly be
7553                            // syncable, so if we already added this provider using a different
7554                            // authority clear the syncable flag. We copy the provider before
7555                            // changing it because the mProviders object contains a reference
7556                            // to a provider that we don't want to change.
7557                            // Only do this for the second authority since the resulting provider
7558                            // object can be the same for all future authorities for this provider.
7559                            p = new PackageParser.Provider(p);
7560                            p.syncable = false;
7561                        }
7562                        if (!mProvidersByAuthority.containsKey(names[j])) {
7563                            mProvidersByAuthority.put(names[j], p);
7564                            if (p.info.authority == null) {
7565                                p.info.authority = names[j];
7566                            } else {
7567                                p.info.authority = p.info.authority + ";" + names[j];
7568                            }
7569                            if (DEBUG_PACKAGE_SCANNING) {
7570                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7571                                    Log.d(TAG, "Registered content provider: " + names[j]
7572                                            + ", className = " + p.info.name + ", isSyncable = "
7573                                            + p.info.isSyncable);
7574                            }
7575                        } else {
7576                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7577                            Slog.w(TAG, "Skipping provider name " + names[j] +
7578                                    " (in package " + pkg.applicationInfo.packageName +
7579                                    "): name already used by "
7580                                    + ((other != null && other.getComponentName() != null)
7581                                            ? other.getComponentName().getPackageName() : "?"));
7582                        }
7583                    }
7584                }
7585                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7586                    if (r == null) {
7587                        r = new StringBuilder(256);
7588                    } else {
7589                        r.append(' ');
7590                    }
7591                    r.append(p.info.name);
7592                }
7593            }
7594            if (r != null) {
7595                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7596            }
7597
7598            N = pkg.services.size();
7599            r = null;
7600            for (i=0; i<N; i++) {
7601                PackageParser.Service s = pkg.services.get(i);
7602                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7603                        s.info.processName, pkg.applicationInfo.uid);
7604                mServices.addService(s);
7605                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7606                    if (r == null) {
7607                        r = new StringBuilder(256);
7608                    } else {
7609                        r.append(' ');
7610                    }
7611                    r.append(s.info.name);
7612                }
7613            }
7614            if (r != null) {
7615                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7616            }
7617
7618            N = pkg.receivers.size();
7619            r = null;
7620            for (i=0; i<N; i++) {
7621                PackageParser.Activity a = pkg.receivers.get(i);
7622                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7623                        a.info.processName, pkg.applicationInfo.uid);
7624                mReceivers.addActivity(a, "receiver");
7625                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7626                    if (r == null) {
7627                        r = new StringBuilder(256);
7628                    } else {
7629                        r.append(' ');
7630                    }
7631                    r.append(a.info.name);
7632                }
7633            }
7634            if (r != null) {
7635                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7636            }
7637
7638            N = pkg.activities.size();
7639            r = null;
7640            for (i=0; i<N; i++) {
7641                PackageParser.Activity a = pkg.activities.get(i);
7642                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7643                        a.info.processName, pkg.applicationInfo.uid);
7644                mActivities.addActivity(a, "activity");
7645                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7646                    if (r == null) {
7647                        r = new StringBuilder(256);
7648                    } else {
7649                        r.append(' ');
7650                    }
7651                    r.append(a.info.name);
7652                }
7653            }
7654            if (r != null) {
7655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7656            }
7657
7658            N = pkg.permissionGroups.size();
7659            r = null;
7660            for (i=0; i<N; i++) {
7661                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7662                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7663                if (cur == null) {
7664                    mPermissionGroups.put(pg.info.name, pg);
7665                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                        if (r == null) {
7667                            r = new StringBuilder(256);
7668                        } else {
7669                            r.append(' ');
7670                        }
7671                        r.append(pg.info.name);
7672                    }
7673                } else {
7674                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7675                            + pg.info.packageName + " ignored: original from "
7676                            + cur.info.packageName);
7677                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7678                        if (r == null) {
7679                            r = new StringBuilder(256);
7680                        } else {
7681                            r.append(' ');
7682                        }
7683                        r.append("DUP:");
7684                        r.append(pg.info.name);
7685                    }
7686                }
7687            }
7688            if (r != null) {
7689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7690            }
7691
7692            N = pkg.permissions.size();
7693            r = null;
7694            for (i=0; i<N; i++) {
7695                PackageParser.Permission p = pkg.permissions.get(i);
7696
7697                // Assume by default that we did not install this permission into the system.
7698                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7699
7700                // Now that permission groups have a special meaning, we ignore permission
7701                // groups for legacy apps to prevent unexpected behavior. In particular,
7702                // permissions for one app being granted to someone just becuase they happen
7703                // to be in a group defined by another app (before this had no implications).
7704                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7705                    p.group = mPermissionGroups.get(p.info.group);
7706                    // Warn for a permission in an unknown group.
7707                    if (p.info.group != null && p.group == null) {
7708                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7709                                + p.info.packageName + " in an unknown group " + p.info.group);
7710                    }
7711                }
7712
7713                ArrayMap<String, BasePermission> permissionMap =
7714                        p.tree ? mSettings.mPermissionTrees
7715                                : mSettings.mPermissions;
7716                BasePermission bp = permissionMap.get(p.info.name);
7717
7718                // Allow system apps to redefine non-system permissions
7719                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7720                    final boolean currentOwnerIsSystem = (bp.perm != null
7721                            && isSystemApp(bp.perm.owner));
7722                    if (isSystemApp(p.owner)) {
7723                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7724                            // It's a built-in permission and no owner, take ownership now
7725                            bp.packageSetting = pkgSetting;
7726                            bp.perm = p;
7727                            bp.uid = pkg.applicationInfo.uid;
7728                            bp.sourcePackage = p.info.packageName;
7729                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7730                        } else if (!currentOwnerIsSystem) {
7731                            String msg = "New decl " + p.owner + " of permission  "
7732                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7733                            reportSettingsProblem(Log.WARN, msg);
7734                            bp = null;
7735                        }
7736                    }
7737                }
7738
7739                if (bp == null) {
7740                    bp = new BasePermission(p.info.name, p.info.packageName,
7741                            BasePermission.TYPE_NORMAL);
7742                    permissionMap.put(p.info.name, bp);
7743                }
7744
7745                if (bp.perm == null) {
7746                    if (bp.sourcePackage == null
7747                            || bp.sourcePackage.equals(p.info.packageName)) {
7748                        BasePermission tree = findPermissionTreeLP(p.info.name);
7749                        if (tree == null
7750                                || tree.sourcePackage.equals(p.info.packageName)) {
7751                            bp.packageSetting = pkgSetting;
7752                            bp.perm = p;
7753                            bp.uid = pkg.applicationInfo.uid;
7754                            bp.sourcePackage = p.info.packageName;
7755                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7756                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7757                                if (r == null) {
7758                                    r = new StringBuilder(256);
7759                                } else {
7760                                    r.append(' ');
7761                                }
7762                                r.append(p.info.name);
7763                            }
7764                        } else {
7765                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7766                                    + p.info.packageName + " ignored: base tree "
7767                                    + tree.name + " is from package "
7768                                    + tree.sourcePackage);
7769                        }
7770                    } else {
7771                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7772                                + p.info.packageName + " ignored: original from "
7773                                + bp.sourcePackage);
7774                    }
7775                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7776                    if (r == null) {
7777                        r = new StringBuilder(256);
7778                    } else {
7779                        r.append(' ');
7780                    }
7781                    r.append("DUP:");
7782                    r.append(p.info.name);
7783                }
7784                if (bp.perm == p) {
7785                    bp.protectionLevel = p.info.protectionLevel;
7786                }
7787            }
7788
7789            if (r != null) {
7790                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7791            }
7792
7793            N = pkg.instrumentation.size();
7794            r = null;
7795            for (i=0; i<N; i++) {
7796                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7797                a.info.packageName = pkg.applicationInfo.packageName;
7798                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7799                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7800                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7801                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7802                a.info.dataDir = pkg.applicationInfo.dataDir;
7803                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7804                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7805
7806                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7807                // need other information about the application, like the ABI and what not ?
7808                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7809                mInstrumentation.put(a.getComponentName(), a);
7810                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7811                    if (r == null) {
7812                        r = new StringBuilder(256);
7813                    } else {
7814                        r.append(' ');
7815                    }
7816                    r.append(a.info.name);
7817                }
7818            }
7819            if (r != null) {
7820                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7821            }
7822
7823            if (pkg.protectedBroadcasts != null) {
7824                N = pkg.protectedBroadcasts.size();
7825                for (i=0; i<N; i++) {
7826                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7827                }
7828            }
7829
7830            pkgSetting.setTimeStamp(scanFileTime);
7831
7832            // Create idmap files for pairs of (packages, overlay packages).
7833            // Note: "android", ie framework-res.apk, is handled by native layers.
7834            if (pkg.mOverlayTarget != null) {
7835                // This is an overlay package.
7836                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7837                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7838                        mOverlays.put(pkg.mOverlayTarget,
7839                                new ArrayMap<String, PackageParser.Package>());
7840                    }
7841                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7842                    map.put(pkg.packageName, pkg);
7843                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7844                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7845                        createIdmapFailed = true;
7846                    }
7847                }
7848            } else if (mOverlays.containsKey(pkg.packageName) &&
7849                    !pkg.packageName.equals("android")) {
7850                // This is a regular package, with one or more known overlay packages.
7851                createIdmapsForPackageLI(pkg);
7852            }
7853        }
7854
7855        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7856
7857        if (createIdmapFailed) {
7858            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7859                    "scanPackageLI failed to createIdmap");
7860        }
7861        return pkg;
7862    }
7863
7864    /**
7865     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7866     * is derived purely on the basis of the contents of {@code scanFile} and
7867     * {@code cpuAbiOverride}.
7868     *
7869     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7870     */
7871    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7872                                 String cpuAbiOverride, boolean extractLibs)
7873            throws PackageManagerException {
7874        // TODO: We can probably be smarter about this stuff. For installed apps,
7875        // we can calculate this information at install time once and for all. For
7876        // system apps, we can probably assume that this information doesn't change
7877        // after the first boot scan. As things stand, we do lots of unnecessary work.
7878
7879        // Give ourselves some initial paths; we'll come back for another
7880        // pass once we've determined ABI below.
7881        setNativeLibraryPaths(pkg);
7882
7883        // We would never need to extract libs for forward-locked and external packages,
7884        // since the container service will do it for us. We shouldn't attempt to
7885        // extract libs from system app when it was not updated.
7886        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7887                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7888            extractLibs = false;
7889        }
7890
7891        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7892        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7893
7894        NativeLibraryHelper.Handle handle = null;
7895        try {
7896            handle = NativeLibraryHelper.Handle.create(pkg);
7897            // TODO(multiArch): This can be null for apps that didn't go through the
7898            // usual installation process. We can calculate it again, like we
7899            // do during install time.
7900            //
7901            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7902            // unnecessary.
7903            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7904
7905            // Null out the abis so that they can be recalculated.
7906            pkg.applicationInfo.primaryCpuAbi = null;
7907            pkg.applicationInfo.secondaryCpuAbi = null;
7908            if (isMultiArch(pkg.applicationInfo)) {
7909                // Warn if we've set an abiOverride for multi-lib packages..
7910                // By definition, we need to copy both 32 and 64 bit libraries for
7911                // such packages.
7912                if (pkg.cpuAbiOverride != null
7913                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7914                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7915                }
7916
7917                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7918                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7919                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7920                    if (extractLibs) {
7921                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7922                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7923                                useIsaSpecificSubdirs);
7924                    } else {
7925                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7926                    }
7927                }
7928
7929                maybeThrowExceptionForMultiArchCopy(
7930                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7931
7932                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7933                    if (extractLibs) {
7934                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7935                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7936                                useIsaSpecificSubdirs);
7937                    } else {
7938                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7939                    }
7940                }
7941
7942                maybeThrowExceptionForMultiArchCopy(
7943                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7944
7945                if (abi64 >= 0) {
7946                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7947                }
7948
7949                if (abi32 >= 0) {
7950                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7951                    if (abi64 >= 0) {
7952                        pkg.applicationInfo.secondaryCpuAbi = abi;
7953                    } else {
7954                        pkg.applicationInfo.primaryCpuAbi = abi;
7955                    }
7956                }
7957            } else {
7958                String[] abiList = (cpuAbiOverride != null) ?
7959                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7960
7961                // Enable gross and lame hacks for apps that are built with old
7962                // SDK tools. We must scan their APKs for renderscript bitcode and
7963                // not launch them if it's present. Don't bother checking on devices
7964                // that don't have 64 bit support.
7965                boolean needsRenderScriptOverride = false;
7966                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7967                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7968                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7969                    needsRenderScriptOverride = true;
7970                }
7971
7972                final int copyRet;
7973                if (extractLibs) {
7974                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7975                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7976                } else {
7977                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7978                }
7979
7980                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7981                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7982                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7983                }
7984
7985                if (copyRet >= 0) {
7986                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7987                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7988                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7989                } else if (needsRenderScriptOverride) {
7990                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7991                }
7992            }
7993        } catch (IOException ioe) {
7994            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7995        } finally {
7996            IoUtils.closeQuietly(handle);
7997        }
7998
7999        // Now that we've calculated the ABIs and determined if it's an internal app,
8000        // we will go ahead and populate the nativeLibraryPath.
8001        setNativeLibraryPaths(pkg);
8002    }
8003
8004    /**
8005     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8006     * i.e, so that all packages can be run inside a single process if required.
8007     *
8008     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8009     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8010     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8011     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8012     * updating a package that belongs to a shared user.
8013     *
8014     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8015     * adds unnecessary complexity.
8016     */
8017    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8018            PackageParser.Package scannedPackage, boolean bootComplete) {
8019        String requiredInstructionSet = null;
8020        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8021            requiredInstructionSet = VMRuntime.getInstructionSet(
8022                     scannedPackage.applicationInfo.primaryCpuAbi);
8023        }
8024
8025        PackageSetting requirer = null;
8026        for (PackageSetting ps : packagesForUser) {
8027            // If packagesForUser contains scannedPackage, we skip it. This will happen
8028            // when scannedPackage is an update of an existing package. Without this check,
8029            // we will never be able to change the ABI of any package belonging to a shared
8030            // user, even if it's compatible with other packages.
8031            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8032                if (ps.primaryCpuAbiString == null) {
8033                    continue;
8034                }
8035
8036                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8037                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8038                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8039                    // this but there's not much we can do.
8040                    String errorMessage = "Instruction set mismatch, "
8041                            + ((requirer == null) ? "[caller]" : requirer)
8042                            + " requires " + requiredInstructionSet + " whereas " + ps
8043                            + " requires " + instructionSet;
8044                    Slog.w(TAG, errorMessage);
8045                }
8046
8047                if (requiredInstructionSet == null) {
8048                    requiredInstructionSet = instructionSet;
8049                    requirer = ps;
8050                }
8051            }
8052        }
8053
8054        if (requiredInstructionSet != null) {
8055            String adjustedAbi;
8056            if (requirer != null) {
8057                // requirer != null implies that either scannedPackage was null or that scannedPackage
8058                // did not require an ABI, in which case we have to adjust scannedPackage to match
8059                // the ABI of the set (which is the same as requirer's ABI)
8060                adjustedAbi = requirer.primaryCpuAbiString;
8061                if (scannedPackage != null) {
8062                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8063                }
8064            } else {
8065                // requirer == null implies that we're updating all ABIs in the set to
8066                // match scannedPackage.
8067                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8068            }
8069
8070            for (PackageSetting ps : packagesForUser) {
8071                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8072                    if (ps.primaryCpuAbiString != null) {
8073                        continue;
8074                    }
8075
8076                    ps.primaryCpuAbiString = adjustedAbi;
8077                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8078                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8079                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8080                        try {
8081                            mInstaller.rmdex(ps.codePathString,
8082                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8083                        } catch (InstallerException ignored) {
8084                        }
8085                    }
8086                }
8087            }
8088        }
8089    }
8090
8091    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8092        synchronized (mPackages) {
8093            mResolverReplaced = true;
8094            // Set up information for custom user intent resolution activity.
8095            mResolveActivity.applicationInfo = pkg.applicationInfo;
8096            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8097            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8098            mResolveActivity.processName = pkg.applicationInfo.packageName;
8099            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8100            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8101                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8102            mResolveActivity.theme = 0;
8103            mResolveActivity.exported = true;
8104            mResolveActivity.enabled = true;
8105            mResolveInfo.activityInfo = mResolveActivity;
8106            mResolveInfo.priority = 0;
8107            mResolveInfo.preferredOrder = 0;
8108            mResolveInfo.match = 0;
8109            mResolveComponentName = mCustomResolverComponentName;
8110            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8111                    mResolveComponentName);
8112        }
8113    }
8114
8115    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8116        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8117
8118        // Set up information for ephemeral installer activity
8119        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8120        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8121        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8122        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8123        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8124        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8125                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8126        mEphemeralInstallerActivity.theme = 0;
8127        mEphemeralInstallerActivity.exported = true;
8128        mEphemeralInstallerActivity.enabled = true;
8129        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8130        mEphemeralInstallerInfo.priority = 0;
8131        mEphemeralInstallerInfo.preferredOrder = 0;
8132        mEphemeralInstallerInfo.match = 0;
8133
8134        if (DEBUG_EPHEMERAL) {
8135            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8136        }
8137    }
8138
8139    private static String calculateBundledApkRoot(final String codePathString) {
8140        final File codePath = new File(codePathString);
8141        final File codeRoot;
8142        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8143            codeRoot = Environment.getRootDirectory();
8144        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8145            codeRoot = Environment.getOemDirectory();
8146        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8147            codeRoot = Environment.getVendorDirectory();
8148        } else {
8149            // Unrecognized code path; take its top real segment as the apk root:
8150            // e.g. /something/app/blah.apk => /something
8151            try {
8152                File f = codePath.getCanonicalFile();
8153                File parent = f.getParentFile();    // non-null because codePath is a file
8154                File tmp;
8155                while ((tmp = parent.getParentFile()) != null) {
8156                    f = parent;
8157                    parent = tmp;
8158                }
8159                codeRoot = f;
8160                Slog.w(TAG, "Unrecognized code path "
8161                        + codePath + " - using " + codeRoot);
8162            } catch (IOException e) {
8163                // Can't canonicalize the code path -- shenanigans?
8164                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8165                return Environment.getRootDirectory().getPath();
8166            }
8167        }
8168        return codeRoot.getPath();
8169    }
8170
8171    /**
8172     * Derive and set the location of native libraries for the given package,
8173     * which varies depending on where and how the package was installed.
8174     */
8175    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8176        final ApplicationInfo info = pkg.applicationInfo;
8177        final String codePath = pkg.codePath;
8178        final File codeFile = new File(codePath);
8179        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8180        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8181
8182        info.nativeLibraryRootDir = null;
8183        info.nativeLibraryRootRequiresIsa = false;
8184        info.nativeLibraryDir = null;
8185        info.secondaryNativeLibraryDir = null;
8186
8187        if (isApkFile(codeFile)) {
8188            // Monolithic install
8189            if (bundledApp) {
8190                // If "/system/lib64/apkname" exists, assume that is the per-package
8191                // native library directory to use; otherwise use "/system/lib/apkname".
8192                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8193                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8194                        getPrimaryInstructionSet(info));
8195
8196                // This is a bundled system app so choose the path based on the ABI.
8197                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8198                // is just the default path.
8199                final String apkName = deriveCodePathName(codePath);
8200                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8201                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8202                        apkName).getAbsolutePath();
8203
8204                if (info.secondaryCpuAbi != null) {
8205                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8206                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8207                            secondaryLibDir, apkName).getAbsolutePath();
8208                }
8209            } else if (asecApp) {
8210                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8211                        .getAbsolutePath();
8212            } else {
8213                final String apkName = deriveCodePathName(codePath);
8214                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8215                        .getAbsolutePath();
8216            }
8217
8218            info.nativeLibraryRootRequiresIsa = false;
8219            info.nativeLibraryDir = info.nativeLibraryRootDir;
8220        } else {
8221            // Cluster install
8222            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8223            info.nativeLibraryRootRequiresIsa = true;
8224
8225            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8226                    getPrimaryInstructionSet(info)).getAbsolutePath();
8227
8228            if (info.secondaryCpuAbi != null) {
8229                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8230                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8231            }
8232        }
8233    }
8234
8235    /**
8236     * Calculate the abis and roots for a bundled app. These can uniquely
8237     * be determined from the contents of the system partition, i.e whether
8238     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8239     * of this information, and instead assume that the system was built
8240     * sensibly.
8241     */
8242    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8243                                           PackageSetting pkgSetting) {
8244        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8245
8246        // If "/system/lib64/apkname" exists, assume that is the per-package
8247        // native library directory to use; otherwise use "/system/lib/apkname".
8248        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8249        setBundledAppAbi(pkg, apkRoot, apkName);
8250        // pkgSetting might be null during rescan following uninstall of updates
8251        // to a bundled app, so accommodate that possibility.  The settings in
8252        // that case will be established later from the parsed package.
8253        //
8254        // If the settings aren't null, sync them up with what we've just derived.
8255        // note that apkRoot isn't stored in the package settings.
8256        if (pkgSetting != null) {
8257            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8258            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8259        }
8260    }
8261
8262    /**
8263     * Deduces the ABI of a bundled app and sets the relevant fields on the
8264     * parsed pkg object.
8265     *
8266     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8267     *        under which system libraries are installed.
8268     * @param apkName the name of the installed package.
8269     */
8270    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8271        final File codeFile = new File(pkg.codePath);
8272
8273        final boolean has64BitLibs;
8274        final boolean has32BitLibs;
8275        if (isApkFile(codeFile)) {
8276            // Monolithic install
8277            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8278            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8279        } else {
8280            // Cluster install
8281            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8282            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8283                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8284                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8285                has64BitLibs = (new File(rootDir, isa)).exists();
8286            } else {
8287                has64BitLibs = false;
8288            }
8289            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8290                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8291                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8292                has32BitLibs = (new File(rootDir, isa)).exists();
8293            } else {
8294                has32BitLibs = false;
8295            }
8296        }
8297
8298        if (has64BitLibs && !has32BitLibs) {
8299            // The package has 64 bit libs, but not 32 bit libs. Its primary
8300            // ABI should be 64 bit. We can safely assume here that the bundled
8301            // native libraries correspond to the most preferred ABI in the list.
8302
8303            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8304            pkg.applicationInfo.secondaryCpuAbi = null;
8305        } else if (has32BitLibs && !has64BitLibs) {
8306            // The package has 32 bit libs but not 64 bit libs. Its primary
8307            // ABI should be 32 bit.
8308
8309            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8310            pkg.applicationInfo.secondaryCpuAbi = null;
8311        } else if (has32BitLibs && has64BitLibs) {
8312            // The application has both 64 and 32 bit bundled libraries. We check
8313            // here that the app declares multiArch support, and warn if it doesn't.
8314            //
8315            // We will be lenient here and record both ABIs. The primary will be the
8316            // ABI that's higher on the list, i.e, a device that's configured to prefer
8317            // 64 bit apps will see a 64 bit primary ABI,
8318
8319            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8320                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8321            }
8322
8323            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8324                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8325                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8326            } else {
8327                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8328                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8329            }
8330        } else {
8331            pkg.applicationInfo.primaryCpuAbi = null;
8332            pkg.applicationInfo.secondaryCpuAbi = null;
8333        }
8334    }
8335
8336    private void killApplication(String pkgName, int appId, String reason) {
8337        // Request the ActivityManager to kill the process(only for existing packages)
8338        // so that we do not end up in a confused state while the user is still using the older
8339        // version of the application while the new one gets installed.
8340        IActivityManager am = ActivityManagerNative.getDefault();
8341        if (am != null) {
8342            try {
8343                am.killApplicationWithAppId(pkgName, appId, reason);
8344            } catch (RemoteException e) {
8345            }
8346        }
8347    }
8348
8349    void removePackageLI(PackageSetting ps, boolean chatty) {
8350        if (DEBUG_INSTALL) {
8351            if (chatty)
8352                Log.d(TAG, "Removing package " + ps.name);
8353        }
8354
8355        // writer
8356        synchronized (mPackages) {
8357            mPackages.remove(ps.name);
8358            final PackageParser.Package pkg = ps.pkg;
8359            if (pkg != null) {
8360                cleanPackageDataStructuresLILPw(pkg, chatty);
8361            }
8362        }
8363    }
8364
8365    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8366        if (DEBUG_INSTALL) {
8367            if (chatty)
8368                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8369        }
8370
8371        // writer
8372        synchronized (mPackages) {
8373            mPackages.remove(pkg.applicationInfo.packageName);
8374            cleanPackageDataStructuresLILPw(pkg, chatty);
8375        }
8376    }
8377
8378    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8379        int N = pkg.providers.size();
8380        StringBuilder r = null;
8381        int i;
8382        for (i=0; i<N; i++) {
8383            PackageParser.Provider p = pkg.providers.get(i);
8384            mProviders.removeProvider(p);
8385            if (p.info.authority == null) {
8386
8387                /* There was another ContentProvider with this authority when
8388                 * this app was installed so this authority is null,
8389                 * Ignore it as we don't have to unregister the provider.
8390                 */
8391                continue;
8392            }
8393            String names[] = p.info.authority.split(";");
8394            for (int j = 0; j < names.length; j++) {
8395                if (mProvidersByAuthority.get(names[j]) == p) {
8396                    mProvidersByAuthority.remove(names[j]);
8397                    if (DEBUG_REMOVE) {
8398                        if (chatty)
8399                            Log.d(TAG, "Unregistered content provider: " + names[j]
8400                                    + ", className = " + p.info.name + ", isSyncable = "
8401                                    + p.info.isSyncable);
8402                    }
8403                }
8404            }
8405            if (DEBUG_REMOVE && chatty) {
8406                if (r == null) {
8407                    r = new StringBuilder(256);
8408                } else {
8409                    r.append(' ');
8410                }
8411                r.append(p.info.name);
8412            }
8413        }
8414        if (r != null) {
8415            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8416        }
8417
8418        N = pkg.services.size();
8419        r = null;
8420        for (i=0; i<N; i++) {
8421            PackageParser.Service s = pkg.services.get(i);
8422            mServices.removeService(s);
8423            if (chatty) {
8424                if (r == null) {
8425                    r = new StringBuilder(256);
8426                } else {
8427                    r.append(' ');
8428                }
8429                r.append(s.info.name);
8430            }
8431        }
8432        if (r != null) {
8433            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8434        }
8435
8436        N = pkg.receivers.size();
8437        r = null;
8438        for (i=0; i<N; i++) {
8439            PackageParser.Activity a = pkg.receivers.get(i);
8440            mReceivers.removeActivity(a, "receiver");
8441            if (DEBUG_REMOVE && chatty) {
8442                if (r == null) {
8443                    r = new StringBuilder(256);
8444                } else {
8445                    r.append(' ');
8446                }
8447                r.append(a.info.name);
8448            }
8449        }
8450        if (r != null) {
8451            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8452        }
8453
8454        N = pkg.activities.size();
8455        r = null;
8456        for (i=0; i<N; i++) {
8457            PackageParser.Activity a = pkg.activities.get(i);
8458            mActivities.removeActivity(a, "activity");
8459            if (DEBUG_REMOVE && chatty) {
8460                if (r == null) {
8461                    r = new StringBuilder(256);
8462                } else {
8463                    r.append(' ');
8464                }
8465                r.append(a.info.name);
8466            }
8467        }
8468        if (r != null) {
8469            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8470        }
8471
8472        N = pkg.permissions.size();
8473        r = null;
8474        for (i=0; i<N; i++) {
8475            PackageParser.Permission p = pkg.permissions.get(i);
8476            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8477            if (bp == null) {
8478                bp = mSettings.mPermissionTrees.get(p.info.name);
8479            }
8480            if (bp != null && bp.perm == p) {
8481                bp.perm = null;
8482                if (DEBUG_REMOVE && chatty) {
8483                    if (r == null) {
8484                        r = new StringBuilder(256);
8485                    } else {
8486                        r.append(' ');
8487                    }
8488                    r.append(p.info.name);
8489                }
8490            }
8491            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8492                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8493                if (appOpPkgs != null) {
8494                    appOpPkgs.remove(pkg.packageName);
8495                }
8496            }
8497        }
8498        if (r != null) {
8499            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8500        }
8501
8502        N = pkg.requestedPermissions.size();
8503        r = null;
8504        for (i=0; i<N; i++) {
8505            String perm = pkg.requestedPermissions.get(i);
8506            BasePermission bp = mSettings.mPermissions.get(perm);
8507            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8508                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8509                if (appOpPkgs != null) {
8510                    appOpPkgs.remove(pkg.packageName);
8511                    if (appOpPkgs.isEmpty()) {
8512                        mAppOpPermissionPackages.remove(perm);
8513                    }
8514                }
8515            }
8516        }
8517        if (r != null) {
8518            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8519        }
8520
8521        N = pkg.instrumentation.size();
8522        r = null;
8523        for (i=0; i<N; i++) {
8524            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8525            mInstrumentation.remove(a.getComponentName());
8526            if (DEBUG_REMOVE && chatty) {
8527                if (r == null) {
8528                    r = new StringBuilder(256);
8529                } else {
8530                    r.append(' ');
8531                }
8532                r.append(a.info.name);
8533            }
8534        }
8535        if (r != null) {
8536            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8537        }
8538
8539        r = null;
8540        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8541            // Only system apps can hold shared libraries.
8542            if (pkg.libraryNames != null) {
8543                for (i=0; i<pkg.libraryNames.size(); i++) {
8544                    String name = pkg.libraryNames.get(i);
8545                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8546                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8547                        mSharedLibraries.remove(name);
8548                        if (DEBUG_REMOVE && chatty) {
8549                            if (r == null) {
8550                                r = new StringBuilder(256);
8551                            } else {
8552                                r.append(' ');
8553                            }
8554                            r.append(name);
8555                        }
8556                    }
8557                }
8558            }
8559        }
8560        if (r != null) {
8561            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8562        }
8563    }
8564
8565    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8566        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8567            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8568                return true;
8569            }
8570        }
8571        return false;
8572    }
8573
8574    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8575    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8576    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8577
8578    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8579            int flags) {
8580        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8581        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8582    }
8583
8584    private void updatePermissionsLPw(String changingPkg,
8585            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8586        // Make sure there are no dangling permission trees.
8587        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8588        while (it.hasNext()) {
8589            final BasePermission bp = it.next();
8590            if (bp.packageSetting == null) {
8591                // We may not yet have parsed the package, so just see if
8592                // we still know about its settings.
8593                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8594            }
8595            if (bp.packageSetting == null) {
8596                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8597                        + " from package " + bp.sourcePackage);
8598                it.remove();
8599            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8600                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8601                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8602                            + " from package " + bp.sourcePackage);
8603                    flags |= UPDATE_PERMISSIONS_ALL;
8604                    it.remove();
8605                }
8606            }
8607        }
8608
8609        // Make sure all dynamic permissions have been assigned to a package,
8610        // and make sure there are no dangling permissions.
8611        it = mSettings.mPermissions.values().iterator();
8612        while (it.hasNext()) {
8613            final BasePermission bp = it.next();
8614            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8615                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8616                        + bp.name + " pkg=" + bp.sourcePackage
8617                        + " info=" + bp.pendingInfo);
8618                if (bp.packageSetting == null && bp.pendingInfo != null) {
8619                    final BasePermission tree = findPermissionTreeLP(bp.name);
8620                    if (tree != null && tree.perm != null) {
8621                        bp.packageSetting = tree.packageSetting;
8622                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8623                                new PermissionInfo(bp.pendingInfo));
8624                        bp.perm.info.packageName = tree.perm.info.packageName;
8625                        bp.perm.info.name = bp.name;
8626                        bp.uid = tree.uid;
8627                    }
8628                }
8629            }
8630            if (bp.packageSetting == null) {
8631                // We may not yet have parsed the package, so just see if
8632                // we still know about its settings.
8633                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8634            }
8635            if (bp.packageSetting == null) {
8636                Slog.w(TAG, "Removing dangling permission: " + bp.name
8637                        + " from package " + bp.sourcePackage);
8638                it.remove();
8639            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8640                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8641                    Slog.i(TAG, "Removing old permission: " + bp.name
8642                            + " from package " + bp.sourcePackage);
8643                    flags |= UPDATE_PERMISSIONS_ALL;
8644                    it.remove();
8645                }
8646            }
8647        }
8648
8649        // Now update the permissions for all packages, in particular
8650        // replace the granted permissions of the system packages.
8651        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8652            for (PackageParser.Package pkg : mPackages.values()) {
8653                if (pkg != pkgInfo) {
8654                    // Only replace for packages on requested volume
8655                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8656                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8657                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8658                    grantPermissionsLPw(pkg, replace, changingPkg);
8659                }
8660            }
8661        }
8662
8663        if (pkgInfo != null) {
8664            // Only replace for packages on requested volume
8665            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8666            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8667                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8668            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8669        }
8670    }
8671
8672    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8673            String packageOfInterest) {
8674        // IMPORTANT: There are two types of permissions: install and runtime.
8675        // Install time permissions are granted when the app is installed to
8676        // all device users and users added in the future. Runtime permissions
8677        // are granted at runtime explicitly to specific users. Normal and signature
8678        // protected permissions are install time permissions. Dangerous permissions
8679        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8680        // otherwise they are runtime permissions. This function does not manage
8681        // runtime permissions except for the case an app targeting Lollipop MR1
8682        // being upgraded to target a newer SDK, in which case dangerous permissions
8683        // are transformed from install time to runtime ones.
8684
8685        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8686        if (ps == null) {
8687            return;
8688        }
8689
8690        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8691
8692        PermissionsState permissionsState = ps.getPermissionsState();
8693        PermissionsState origPermissions = permissionsState;
8694
8695        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8696
8697        boolean runtimePermissionsRevoked = false;
8698        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8699
8700        boolean changedInstallPermission = false;
8701
8702        if (replace) {
8703            ps.installPermissionsFixed = false;
8704            if (!ps.isSharedUser()) {
8705                origPermissions = new PermissionsState(permissionsState);
8706                permissionsState.reset();
8707            } else {
8708                // We need to know only about runtime permission changes since the
8709                // calling code always writes the install permissions state but
8710                // the runtime ones are written only if changed. The only cases of
8711                // changed runtime permissions here are promotion of an install to
8712                // runtime and revocation of a runtime from a shared user.
8713                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8714                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8715                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8716                    runtimePermissionsRevoked = true;
8717                }
8718            }
8719        }
8720
8721        permissionsState.setGlobalGids(mGlobalGids);
8722
8723        final int N = pkg.requestedPermissions.size();
8724        for (int i=0; i<N; i++) {
8725            final String name = pkg.requestedPermissions.get(i);
8726            final BasePermission bp = mSettings.mPermissions.get(name);
8727
8728            if (DEBUG_INSTALL) {
8729                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8730            }
8731
8732            if (bp == null || bp.packageSetting == null) {
8733                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8734                    Slog.w(TAG, "Unknown permission " + name
8735                            + " in package " + pkg.packageName);
8736                }
8737                continue;
8738            }
8739
8740            final String perm = bp.name;
8741            boolean allowedSig = false;
8742            int grant = GRANT_DENIED;
8743
8744            // Keep track of app op permissions.
8745            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8746                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8747                if (pkgs == null) {
8748                    pkgs = new ArraySet<>();
8749                    mAppOpPermissionPackages.put(bp.name, pkgs);
8750                }
8751                pkgs.add(pkg.packageName);
8752            }
8753
8754            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8755            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8756                    >= Build.VERSION_CODES.M;
8757            switch (level) {
8758                case PermissionInfo.PROTECTION_NORMAL: {
8759                    // For all apps normal permissions are install time ones.
8760                    grant = GRANT_INSTALL;
8761                } break;
8762
8763                case PermissionInfo.PROTECTION_DANGEROUS: {
8764                    // If a permission review is required for legacy apps we represent
8765                    // their permissions as always granted runtime ones since we need
8766                    // to keep the review required permission flag per user while an
8767                    // install permission's state is shared across all users.
8768                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8769                        // For legacy apps dangerous permissions are install time ones.
8770                        grant = GRANT_INSTALL;
8771                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8772                        // For legacy apps that became modern, install becomes runtime.
8773                        grant = GRANT_UPGRADE;
8774                    } else if (mPromoteSystemApps
8775                            && isSystemApp(ps)
8776                            && mExistingSystemPackages.contains(ps.name)) {
8777                        // For legacy system apps, install becomes runtime.
8778                        // We cannot check hasInstallPermission() for system apps since those
8779                        // permissions were granted implicitly and not persisted pre-M.
8780                        grant = GRANT_UPGRADE;
8781                    } else {
8782                        // For modern apps keep runtime permissions unchanged.
8783                        grant = GRANT_RUNTIME;
8784                    }
8785                } break;
8786
8787                case PermissionInfo.PROTECTION_SIGNATURE: {
8788                    // For all apps signature permissions are install time ones.
8789                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8790                    if (allowedSig) {
8791                        grant = GRANT_INSTALL;
8792                    }
8793                } break;
8794            }
8795
8796            if (DEBUG_INSTALL) {
8797                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8798            }
8799
8800            if (grant != GRANT_DENIED) {
8801                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8802                    // If this is an existing, non-system package, then
8803                    // we can't add any new permissions to it.
8804                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8805                        // Except...  if this is a permission that was added
8806                        // to the platform (note: need to only do this when
8807                        // updating the platform).
8808                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8809                            grant = GRANT_DENIED;
8810                        }
8811                    }
8812                }
8813
8814                switch (grant) {
8815                    case GRANT_INSTALL: {
8816                        // Revoke this as runtime permission to handle the case of
8817                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8818                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8819                            if (origPermissions.getRuntimePermissionState(
8820                                    bp.name, userId) != null) {
8821                                // Revoke the runtime permission and clear the flags.
8822                                origPermissions.revokeRuntimePermission(bp, userId);
8823                                origPermissions.updatePermissionFlags(bp, userId,
8824                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8825                                // If we revoked a permission permission, we have to write.
8826                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8827                                        changedRuntimePermissionUserIds, userId);
8828                            }
8829                        }
8830                        // Grant an install permission.
8831                        if (permissionsState.grantInstallPermission(bp) !=
8832                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8833                            changedInstallPermission = true;
8834                        }
8835                    } break;
8836
8837                    case GRANT_RUNTIME: {
8838                        // Grant previously granted runtime permissions.
8839                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8840                            PermissionState permissionState = origPermissions
8841                                    .getRuntimePermissionState(bp.name, userId);
8842                            int flags = permissionState != null
8843                                    ? permissionState.getFlags() : 0;
8844                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8845                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8846                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8847                                    // If we cannot put the permission as it was, we have to write.
8848                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8849                                            changedRuntimePermissionUserIds, userId);
8850                                }
8851                                // If the app supports runtime permissions no need for a review.
8852                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8853                                        && appSupportsRuntimePermissions
8854                                        && (flags & PackageManager
8855                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8856                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8857                                    // Since we changed the flags, we have to write.
8858                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8859                                            changedRuntimePermissionUserIds, userId);
8860                                }
8861                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8862                                    && !appSupportsRuntimePermissions) {
8863                                // For legacy apps that need a permission review, every new
8864                                // runtime permission is granted but it is pending a review.
8865                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8866                                    permissionsState.grantRuntimePermission(bp, userId);
8867                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8868                                    // We changed the permission and flags, hence have to write.
8869                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8870                                            changedRuntimePermissionUserIds, userId);
8871                                }
8872                            }
8873                            // Propagate the permission flags.
8874                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8875                        }
8876                    } break;
8877
8878                    case GRANT_UPGRADE: {
8879                        // Grant runtime permissions for a previously held install permission.
8880                        PermissionState permissionState = origPermissions
8881                                .getInstallPermissionState(bp.name);
8882                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8883
8884                        if (origPermissions.revokeInstallPermission(bp)
8885                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8886                            // We will be transferring the permission flags, so clear them.
8887                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8888                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8889                            changedInstallPermission = true;
8890                        }
8891
8892                        // If the permission is not to be promoted to runtime we ignore it and
8893                        // also its other flags as they are not applicable to install permissions.
8894                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8895                            for (int userId : currentUserIds) {
8896                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8897                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8898                                    // Transfer the permission flags.
8899                                    permissionsState.updatePermissionFlags(bp, userId,
8900                                            flags, flags);
8901                                    // If we granted the permission, we have to write.
8902                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8903                                            changedRuntimePermissionUserIds, userId);
8904                                }
8905                            }
8906                        }
8907                    } break;
8908
8909                    default: {
8910                        if (packageOfInterest == null
8911                                || packageOfInterest.equals(pkg.packageName)) {
8912                            Slog.w(TAG, "Not granting permission " + perm
8913                                    + " to package " + pkg.packageName
8914                                    + " because it was previously installed without");
8915                        }
8916                    } break;
8917                }
8918            } else {
8919                if (permissionsState.revokeInstallPermission(bp) !=
8920                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8921                    // Also drop the permission flags.
8922                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8923                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8924                    changedInstallPermission = true;
8925                    Slog.i(TAG, "Un-granting permission " + perm
8926                            + " from package " + pkg.packageName
8927                            + " (protectionLevel=" + bp.protectionLevel
8928                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8929                            + ")");
8930                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8931                    // Don't print warning for app op permissions, since it is fine for them
8932                    // not to be granted, there is a UI for the user to decide.
8933                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8934                        Slog.w(TAG, "Not granting permission " + perm
8935                                + " to package " + pkg.packageName
8936                                + " (protectionLevel=" + bp.protectionLevel
8937                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8938                                + ")");
8939                    }
8940                }
8941            }
8942        }
8943
8944        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8945                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8946            // This is the first that we have heard about this package, so the
8947            // permissions we have now selected are fixed until explicitly
8948            // changed.
8949            ps.installPermissionsFixed = true;
8950        }
8951
8952        // Persist the runtime permissions state for users with changes. If permissions
8953        // were revoked because no app in the shared user declares them we have to
8954        // write synchronously to avoid losing runtime permissions state.
8955        for (int userId : changedRuntimePermissionUserIds) {
8956            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8957        }
8958
8959        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8960    }
8961
8962    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8963        boolean allowed = false;
8964        final int NP = PackageParser.NEW_PERMISSIONS.length;
8965        for (int ip=0; ip<NP; ip++) {
8966            final PackageParser.NewPermissionInfo npi
8967                    = PackageParser.NEW_PERMISSIONS[ip];
8968            if (npi.name.equals(perm)
8969                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8970                allowed = true;
8971                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8972                        + pkg.packageName);
8973                break;
8974            }
8975        }
8976        return allowed;
8977    }
8978
8979    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8980            BasePermission bp, PermissionsState origPermissions) {
8981        boolean allowed;
8982        allowed = (compareSignatures(
8983                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8984                        == PackageManager.SIGNATURE_MATCH)
8985                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8986                        == PackageManager.SIGNATURE_MATCH);
8987        if (!allowed && (bp.protectionLevel
8988                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8989            if (isSystemApp(pkg)) {
8990                // For updated system applications, a system permission
8991                // is granted only if it had been defined by the original application.
8992                if (pkg.isUpdatedSystemApp()) {
8993                    final PackageSetting sysPs = mSettings
8994                            .getDisabledSystemPkgLPr(pkg.packageName);
8995                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8996                        // If the original was granted this permission, we take
8997                        // that grant decision as read and propagate it to the
8998                        // update.
8999                        if (sysPs.isPrivileged()) {
9000                            allowed = true;
9001                        }
9002                    } else {
9003                        // The system apk may have been updated with an older
9004                        // version of the one on the data partition, but which
9005                        // granted a new system permission that it didn't have
9006                        // before.  In this case we do want to allow the app to
9007                        // now get the new permission if the ancestral apk is
9008                        // privileged to get it.
9009                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9010                            for (int j=0;
9011                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9012                                if (perm.equals(
9013                                        sysPs.pkg.requestedPermissions.get(j))) {
9014                                    allowed = true;
9015                                    break;
9016                                }
9017                            }
9018                        }
9019                    }
9020                } else {
9021                    allowed = isPrivilegedApp(pkg);
9022                }
9023            }
9024        }
9025        if (!allowed) {
9026            if (!allowed && (bp.protectionLevel
9027                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9028                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9029                // If this was a previously normal/dangerous permission that got moved
9030                // to a system permission as part of the runtime permission redesign, then
9031                // we still want to blindly grant it to old apps.
9032                allowed = true;
9033            }
9034            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9035                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9036                // If this permission is to be granted to the system installer and
9037                // this app is an installer, then it gets the permission.
9038                allowed = true;
9039            }
9040            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9041                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9042                // If this permission is to be granted to the system verifier and
9043                // this app is a verifier, then it gets the permission.
9044                allowed = true;
9045            }
9046            if (!allowed && (bp.protectionLevel
9047                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9048                    && isSystemApp(pkg)) {
9049                // Any pre-installed system app is allowed to get this permission.
9050                allowed = true;
9051            }
9052            if (!allowed && (bp.protectionLevel
9053                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9054                // For development permissions, a development permission
9055                // is granted only if it was already granted.
9056                allowed = origPermissions.hasInstallPermission(perm);
9057            }
9058        }
9059        return allowed;
9060    }
9061
9062    final class ActivityIntentResolver
9063            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9064        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9065                boolean defaultOnly, int userId) {
9066            if (!sUserManager.exists(userId)) return null;
9067            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9068            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9069        }
9070
9071        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9072                int userId) {
9073            if (!sUserManager.exists(userId)) return null;
9074            mFlags = flags;
9075            return super.queryIntent(intent, resolvedType,
9076                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9077        }
9078
9079        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9080                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9081            if (!sUserManager.exists(userId)) return null;
9082            if (packageActivities == null) {
9083                return null;
9084            }
9085            mFlags = flags;
9086            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9087            final int N = packageActivities.size();
9088            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9089                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9090
9091            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9092            for (int i = 0; i < N; ++i) {
9093                intentFilters = packageActivities.get(i).intents;
9094                if (intentFilters != null && intentFilters.size() > 0) {
9095                    PackageParser.ActivityIntentInfo[] array =
9096                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9097                    intentFilters.toArray(array);
9098                    listCut.add(array);
9099                }
9100            }
9101            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9102        }
9103
9104        public final void addActivity(PackageParser.Activity a, String type) {
9105            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9106            mActivities.put(a.getComponentName(), a);
9107            if (DEBUG_SHOW_INFO)
9108                Log.v(
9109                TAG, "  " + type + " " +
9110                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9111            if (DEBUG_SHOW_INFO)
9112                Log.v(TAG, "    Class=" + a.info.name);
9113            final int NI = a.intents.size();
9114            for (int j=0; j<NI; j++) {
9115                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9116                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9117                    intent.setPriority(0);
9118                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9119                            + a.className + " with priority > 0, forcing to 0");
9120                }
9121                if (DEBUG_SHOW_INFO) {
9122                    Log.v(TAG, "    IntentFilter:");
9123                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9124                }
9125                if (!intent.debugCheck()) {
9126                    Log.w(TAG, "==> For Activity " + a.info.name);
9127                }
9128                addFilter(intent);
9129            }
9130        }
9131
9132        public final void removeActivity(PackageParser.Activity a, String type) {
9133            mActivities.remove(a.getComponentName());
9134            if (DEBUG_SHOW_INFO) {
9135                Log.v(TAG, "  " + type + " "
9136                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9137                                : a.info.name) + ":");
9138                Log.v(TAG, "    Class=" + a.info.name);
9139            }
9140            final int NI = a.intents.size();
9141            for (int j=0; j<NI; j++) {
9142                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9143                if (DEBUG_SHOW_INFO) {
9144                    Log.v(TAG, "    IntentFilter:");
9145                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9146                }
9147                removeFilter(intent);
9148            }
9149        }
9150
9151        @Override
9152        protected boolean allowFilterResult(
9153                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9154            ActivityInfo filterAi = filter.activity.info;
9155            for (int i=dest.size()-1; i>=0; i--) {
9156                ActivityInfo destAi = dest.get(i).activityInfo;
9157                if (destAi.name == filterAi.name
9158                        && destAi.packageName == filterAi.packageName) {
9159                    return false;
9160                }
9161            }
9162            return true;
9163        }
9164
9165        @Override
9166        protected ActivityIntentInfo[] newArray(int size) {
9167            return new ActivityIntentInfo[size];
9168        }
9169
9170        @Override
9171        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9172            if (!sUserManager.exists(userId)) return true;
9173            PackageParser.Package p = filter.activity.owner;
9174            if (p != null) {
9175                PackageSetting ps = (PackageSetting)p.mExtras;
9176                if (ps != null) {
9177                    // System apps are never considered stopped for purposes of
9178                    // filtering, because there may be no way for the user to
9179                    // actually re-launch them.
9180                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9181                            && ps.getStopped(userId);
9182                }
9183            }
9184            return false;
9185        }
9186
9187        @Override
9188        protected boolean isPackageForFilter(String packageName,
9189                PackageParser.ActivityIntentInfo info) {
9190            return packageName.equals(info.activity.owner.packageName);
9191        }
9192
9193        @Override
9194        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9195                int match, int userId) {
9196            if (!sUserManager.exists(userId)) return null;
9197            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9198                return null;
9199            }
9200            final PackageParser.Activity activity = info.activity;
9201            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9202            if (ps == null) {
9203                return null;
9204            }
9205            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9206                    ps.readUserState(userId), userId);
9207            if (ai == null) {
9208                return null;
9209            }
9210            final ResolveInfo res = new ResolveInfo();
9211            res.activityInfo = ai;
9212            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9213                res.filter = info;
9214            }
9215            if (info != null) {
9216                res.handleAllWebDataURI = info.handleAllWebDataURI();
9217            }
9218            res.priority = info.getPriority();
9219            res.preferredOrder = activity.owner.mPreferredOrder;
9220            //System.out.println("Result: " + res.activityInfo.className +
9221            //                   " = " + res.priority);
9222            res.match = match;
9223            res.isDefault = info.hasDefault;
9224            res.labelRes = info.labelRes;
9225            res.nonLocalizedLabel = info.nonLocalizedLabel;
9226            if (userNeedsBadging(userId)) {
9227                res.noResourceId = true;
9228            } else {
9229                res.icon = info.icon;
9230            }
9231            res.iconResourceId = info.icon;
9232            res.system = res.activityInfo.applicationInfo.isSystemApp();
9233            return res;
9234        }
9235
9236        @Override
9237        protected void sortResults(List<ResolveInfo> results) {
9238            Collections.sort(results, mResolvePrioritySorter);
9239        }
9240
9241        @Override
9242        protected void dumpFilter(PrintWriter out, String prefix,
9243                PackageParser.ActivityIntentInfo filter) {
9244            out.print(prefix); out.print(
9245                    Integer.toHexString(System.identityHashCode(filter.activity)));
9246                    out.print(' ');
9247                    filter.activity.printComponentShortName(out);
9248                    out.print(" filter ");
9249                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9250        }
9251
9252        @Override
9253        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9254            return filter.activity;
9255        }
9256
9257        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9258            PackageParser.Activity activity = (PackageParser.Activity)label;
9259            out.print(prefix); out.print(
9260                    Integer.toHexString(System.identityHashCode(activity)));
9261                    out.print(' ');
9262                    activity.printComponentShortName(out);
9263            if (count > 1) {
9264                out.print(" ("); out.print(count); out.print(" filters)");
9265            }
9266            out.println();
9267        }
9268
9269//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9270//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9271//            final List<ResolveInfo> retList = Lists.newArrayList();
9272//            while (i.hasNext()) {
9273//                final ResolveInfo resolveInfo = i.next();
9274//                if (isEnabledLP(resolveInfo.activityInfo)) {
9275//                    retList.add(resolveInfo);
9276//                }
9277//            }
9278//            return retList;
9279//        }
9280
9281        // Keys are String (activity class name), values are Activity.
9282        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9283                = new ArrayMap<ComponentName, PackageParser.Activity>();
9284        private int mFlags;
9285    }
9286
9287    private final class ServiceIntentResolver
9288            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9289        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9290                boolean defaultOnly, int userId) {
9291            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9292            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9293        }
9294
9295        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9296                int userId) {
9297            if (!sUserManager.exists(userId)) return null;
9298            mFlags = flags;
9299            return super.queryIntent(intent, resolvedType,
9300                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9301        }
9302
9303        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9304                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9305            if (!sUserManager.exists(userId)) return null;
9306            if (packageServices == null) {
9307                return null;
9308            }
9309            mFlags = flags;
9310            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9311            final int N = packageServices.size();
9312            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9313                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9314
9315            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9316            for (int i = 0; i < N; ++i) {
9317                intentFilters = packageServices.get(i).intents;
9318                if (intentFilters != null && intentFilters.size() > 0) {
9319                    PackageParser.ServiceIntentInfo[] array =
9320                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9321                    intentFilters.toArray(array);
9322                    listCut.add(array);
9323                }
9324            }
9325            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9326        }
9327
9328        public final void addService(PackageParser.Service s) {
9329            mServices.put(s.getComponentName(), s);
9330            if (DEBUG_SHOW_INFO) {
9331                Log.v(TAG, "  "
9332                        + (s.info.nonLocalizedLabel != null
9333                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9334                Log.v(TAG, "    Class=" + s.info.name);
9335            }
9336            final int NI = s.intents.size();
9337            int j;
9338            for (j=0; j<NI; j++) {
9339                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9340                if (DEBUG_SHOW_INFO) {
9341                    Log.v(TAG, "    IntentFilter:");
9342                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9343                }
9344                if (!intent.debugCheck()) {
9345                    Log.w(TAG, "==> For Service " + s.info.name);
9346                }
9347                addFilter(intent);
9348            }
9349        }
9350
9351        public final void removeService(PackageParser.Service s) {
9352            mServices.remove(s.getComponentName());
9353            if (DEBUG_SHOW_INFO) {
9354                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9355                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9356                Log.v(TAG, "    Class=" + s.info.name);
9357            }
9358            final int NI = s.intents.size();
9359            int j;
9360            for (j=0; j<NI; j++) {
9361                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9362                if (DEBUG_SHOW_INFO) {
9363                    Log.v(TAG, "    IntentFilter:");
9364                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9365                }
9366                removeFilter(intent);
9367            }
9368        }
9369
9370        @Override
9371        protected boolean allowFilterResult(
9372                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9373            ServiceInfo filterSi = filter.service.info;
9374            for (int i=dest.size()-1; i>=0; i--) {
9375                ServiceInfo destAi = dest.get(i).serviceInfo;
9376                if (destAi.name == filterSi.name
9377                        && destAi.packageName == filterSi.packageName) {
9378                    return false;
9379                }
9380            }
9381            return true;
9382        }
9383
9384        @Override
9385        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9386            return new PackageParser.ServiceIntentInfo[size];
9387        }
9388
9389        @Override
9390        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9391            if (!sUserManager.exists(userId)) return true;
9392            PackageParser.Package p = filter.service.owner;
9393            if (p != null) {
9394                PackageSetting ps = (PackageSetting)p.mExtras;
9395                if (ps != null) {
9396                    // System apps are never considered stopped for purposes of
9397                    // filtering, because there may be no way for the user to
9398                    // actually re-launch them.
9399                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9400                            && ps.getStopped(userId);
9401                }
9402            }
9403            return false;
9404        }
9405
9406        @Override
9407        protected boolean isPackageForFilter(String packageName,
9408                PackageParser.ServiceIntentInfo info) {
9409            return packageName.equals(info.service.owner.packageName);
9410        }
9411
9412        @Override
9413        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9414                int match, int userId) {
9415            if (!sUserManager.exists(userId)) return null;
9416            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9417            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9418                return null;
9419            }
9420            final PackageParser.Service service = info.service;
9421            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9422            if (ps == null) {
9423                return null;
9424            }
9425            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9426                    ps.readUserState(userId), userId);
9427            if (si == null) {
9428                return null;
9429            }
9430            final ResolveInfo res = new ResolveInfo();
9431            res.serviceInfo = si;
9432            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9433                res.filter = filter;
9434            }
9435            res.priority = info.getPriority();
9436            res.preferredOrder = service.owner.mPreferredOrder;
9437            res.match = match;
9438            res.isDefault = info.hasDefault;
9439            res.labelRes = info.labelRes;
9440            res.nonLocalizedLabel = info.nonLocalizedLabel;
9441            res.icon = info.icon;
9442            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9443            return res;
9444        }
9445
9446        @Override
9447        protected void sortResults(List<ResolveInfo> results) {
9448            Collections.sort(results, mResolvePrioritySorter);
9449        }
9450
9451        @Override
9452        protected void dumpFilter(PrintWriter out, String prefix,
9453                PackageParser.ServiceIntentInfo filter) {
9454            out.print(prefix); out.print(
9455                    Integer.toHexString(System.identityHashCode(filter.service)));
9456                    out.print(' ');
9457                    filter.service.printComponentShortName(out);
9458                    out.print(" filter ");
9459                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9460        }
9461
9462        @Override
9463        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9464            return filter.service;
9465        }
9466
9467        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9468            PackageParser.Service service = (PackageParser.Service)label;
9469            out.print(prefix); out.print(
9470                    Integer.toHexString(System.identityHashCode(service)));
9471                    out.print(' ');
9472                    service.printComponentShortName(out);
9473            if (count > 1) {
9474                out.print(" ("); out.print(count); out.print(" filters)");
9475            }
9476            out.println();
9477        }
9478
9479//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9480//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9481//            final List<ResolveInfo> retList = Lists.newArrayList();
9482//            while (i.hasNext()) {
9483//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9484//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9485//                    retList.add(resolveInfo);
9486//                }
9487//            }
9488//            return retList;
9489//        }
9490
9491        // Keys are String (activity class name), values are Activity.
9492        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9493                = new ArrayMap<ComponentName, PackageParser.Service>();
9494        private int mFlags;
9495    };
9496
9497    private final class ProviderIntentResolver
9498            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9499        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9500                boolean defaultOnly, int userId) {
9501            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9502            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9503        }
9504
9505        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9506                int userId) {
9507            if (!sUserManager.exists(userId))
9508                return null;
9509            mFlags = flags;
9510            return super.queryIntent(intent, resolvedType,
9511                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9512        }
9513
9514        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9515                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9516            if (!sUserManager.exists(userId))
9517                return null;
9518            if (packageProviders == null) {
9519                return null;
9520            }
9521            mFlags = flags;
9522            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9523            final int N = packageProviders.size();
9524            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9525                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9526
9527            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9528            for (int i = 0; i < N; ++i) {
9529                intentFilters = packageProviders.get(i).intents;
9530                if (intentFilters != null && intentFilters.size() > 0) {
9531                    PackageParser.ProviderIntentInfo[] array =
9532                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9533                    intentFilters.toArray(array);
9534                    listCut.add(array);
9535                }
9536            }
9537            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9538        }
9539
9540        public final void addProvider(PackageParser.Provider p) {
9541            if (mProviders.containsKey(p.getComponentName())) {
9542                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9543                return;
9544            }
9545
9546            mProviders.put(p.getComponentName(), p);
9547            if (DEBUG_SHOW_INFO) {
9548                Log.v(TAG, "  "
9549                        + (p.info.nonLocalizedLabel != null
9550                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9551                Log.v(TAG, "    Class=" + p.info.name);
9552            }
9553            final int NI = p.intents.size();
9554            int j;
9555            for (j = 0; j < NI; j++) {
9556                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9557                if (DEBUG_SHOW_INFO) {
9558                    Log.v(TAG, "    IntentFilter:");
9559                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9560                }
9561                if (!intent.debugCheck()) {
9562                    Log.w(TAG, "==> For Provider " + p.info.name);
9563                }
9564                addFilter(intent);
9565            }
9566        }
9567
9568        public final void removeProvider(PackageParser.Provider p) {
9569            mProviders.remove(p.getComponentName());
9570            if (DEBUG_SHOW_INFO) {
9571                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9572                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9573                Log.v(TAG, "    Class=" + p.info.name);
9574            }
9575            final int NI = p.intents.size();
9576            int j;
9577            for (j = 0; j < NI; j++) {
9578                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9579                if (DEBUG_SHOW_INFO) {
9580                    Log.v(TAG, "    IntentFilter:");
9581                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9582                }
9583                removeFilter(intent);
9584            }
9585        }
9586
9587        @Override
9588        protected boolean allowFilterResult(
9589                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9590            ProviderInfo filterPi = filter.provider.info;
9591            for (int i = dest.size() - 1; i >= 0; i--) {
9592                ProviderInfo destPi = dest.get(i).providerInfo;
9593                if (destPi.name == filterPi.name
9594                        && destPi.packageName == filterPi.packageName) {
9595                    return false;
9596                }
9597            }
9598            return true;
9599        }
9600
9601        @Override
9602        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9603            return new PackageParser.ProviderIntentInfo[size];
9604        }
9605
9606        @Override
9607        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9608            if (!sUserManager.exists(userId))
9609                return true;
9610            PackageParser.Package p = filter.provider.owner;
9611            if (p != null) {
9612                PackageSetting ps = (PackageSetting) p.mExtras;
9613                if (ps != null) {
9614                    // System apps are never considered stopped for purposes of
9615                    // filtering, because there may be no way for the user to
9616                    // actually re-launch them.
9617                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9618                            && ps.getStopped(userId);
9619                }
9620            }
9621            return false;
9622        }
9623
9624        @Override
9625        protected boolean isPackageForFilter(String packageName,
9626                PackageParser.ProviderIntentInfo info) {
9627            return packageName.equals(info.provider.owner.packageName);
9628        }
9629
9630        @Override
9631        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9632                int match, int userId) {
9633            if (!sUserManager.exists(userId))
9634                return null;
9635            final PackageParser.ProviderIntentInfo info = filter;
9636            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9637                return null;
9638            }
9639            final PackageParser.Provider provider = info.provider;
9640            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9641            if (ps == null) {
9642                return null;
9643            }
9644            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9645                    ps.readUserState(userId), userId);
9646            if (pi == null) {
9647                return null;
9648            }
9649            final ResolveInfo res = new ResolveInfo();
9650            res.providerInfo = pi;
9651            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9652                res.filter = filter;
9653            }
9654            res.priority = info.getPriority();
9655            res.preferredOrder = provider.owner.mPreferredOrder;
9656            res.match = match;
9657            res.isDefault = info.hasDefault;
9658            res.labelRes = info.labelRes;
9659            res.nonLocalizedLabel = info.nonLocalizedLabel;
9660            res.icon = info.icon;
9661            res.system = res.providerInfo.applicationInfo.isSystemApp();
9662            return res;
9663        }
9664
9665        @Override
9666        protected void sortResults(List<ResolveInfo> results) {
9667            Collections.sort(results, mResolvePrioritySorter);
9668        }
9669
9670        @Override
9671        protected void dumpFilter(PrintWriter out, String prefix,
9672                PackageParser.ProviderIntentInfo filter) {
9673            out.print(prefix);
9674            out.print(
9675                    Integer.toHexString(System.identityHashCode(filter.provider)));
9676            out.print(' ');
9677            filter.provider.printComponentShortName(out);
9678            out.print(" filter ");
9679            out.println(Integer.toHexString(System.identityHashCode(filter)));
9680        }
9681
9682        @Override
9683        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9684            return filter.provider;
9685        }
9686
9687        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9688            PackageParser.Provider provider = (PackageParser.Provider)label;
9689            out.print(prefix); out.print(
9690                    Integer.toHexString(System.identityHashCode(provider)));
9691                    out.print(' ');
9692                    provider.printComponentShortName(out);
9693            if (count > 1) {
9694                out.print(" ("); out.print(count); out.print(" filters)");
9695            }
9696            out.println();
9697        }
9698
9699        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9700                = new ArrayMap<ComponentName, PackageParser.Provider>();
9701        private int mFlags;
9702    }
9703
9704    private static final class EphemeralIntentResolver
9705            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9706        @Override
9707        protected EphemeralResolveIntentInfo[] newArray(int size) {
9708            return new EphemeralResolveIntentInfo[size];
9709        }
9710
9711        @Override
9712        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9713            return true;
9714        }
9715
9716        @Override
9717        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9718                int userId) {
9719            if (!sUserManager.exists(userId)) {
9720                return null;
9721            }
9722            return info.getEphemeralResolveInfo();
9723        }
9724    }
9725
9726    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9727            new Comparator<ResolveInfo>() {
9728        public int compare(ResolveInfo r1, ResolveInfo r2) {
9729            int v1 = r1.priority;
9730            int v2 = r2.priority;
9731            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9732            if (v1 != v2) {
9733                return (v1 > v2) ? -1 : 1;
9734            }
9735            v1 = r1.preferredOrder;
9736            v2 = r2.preferredOrder;
9737            if (v1 != v2) {
9738                return (v1 > v2) ? -1 : 1;
9739            }
9740            if (r1.isDefault != r2.isDefault) {
9741                return r1.isDefault ? -1 : 1;
9742            }
9743            v1 = r1.match;
9744            v2 = r2.match;
9745            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9746            if (v1 != v2) {
9747                return (v1 > v2) ? -1 : 1;
9748            }
9749            if (r1.system != r2.system) {
9750                return r1.system ? -1 : 1;
9751            }
9752            if (r1.activityInfo != null) {
9753                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9754            }
9755            if (r1.serviceInfo != null) {
9756                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9757            }
9758            if (r1.providerInfo != null) {
9759                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9760            }
9761            return 0;
9762        }
9763    };
9764
9765    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9766            new Comparator<ProviderInfo>() {
9767        public int compare(ProviderInfo p1, ProviderInfo p2) {
9768            final int v1 = p1.initOrder;
9769            final int v2 = p2.initOrder;
9770            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9771        }
9772    };
9773
9774    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9775            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9776            final int[] userIds) {
9777        mHandler.post(new Runnable() {
9778            @Override
9779            public void run() {
9780                try {
9781                    final IActivityManager am = ActivityManagerNative.getDefault();
9782                    if (am == null) return;
9783                    final int[] resolvedUserIds;
9784                    if (userIds == null) {
9785                        resolvedUserIds = am.getRunningUserIds();
9786                    } else {
9787                        resolvedUserIds = userIds;
9788                    }
9789                    for (int id : resolvedUserIds) {
9790                        final Intent intent = new Intent(action,
9791                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9792                        if (extras != null) {
9793                            intent.putExtras(extras);
9794                        }
9795                        if (targetPkg != null) {
9796                            intent.setPackage(targetPkg);
9797                        }
9798                        // Modify the UID when posting to other users
9799                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9800                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9801                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9802                            intent.putExtra(Intent.EXTRA_UID, uid);
9803                        }
9804                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9805                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9806                        if (DEBUG_BROADCASTS) {
9807                            RuntimeException here = new RuntimeException("here");
9808                            here.fillInStackTrace();
9809                            Slog.d(TAG, "Sending to user " + id + ": "
9810                                    + intent.toShortString(false, true, false, false)
9811                                    + " " + intent.getExtras(), here);
9812                        }
9813                        am.broadcastIntent(null, intent, null, finishedReceiver,
9814                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9815                                null, finishedReceiver != null, false, id);
9816                    }
9817                } catch (RemoteException ex) {
9818                }
9819            }
9820        });
9821    }
9822
9823    /**
9824     * Check if the external storage media is available. This is true if there
9825     * is a mounted external storage medium or if the external storage is
9826     * emulated.
9827     */
9828    private boolean isExternalMediaAvailable() {
9829        return mMediaMounted || Environment.isExternalStorageEmulated();
9830    }
9831
9832    @Override
9833    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9834        // writer
9835        synchronized (mPackages) {
9836            if (!isExternalMediaAvailable()) {
9837                // If the external storage is no longer mounted at this point,
9838                // the caller may not have been able to delete all of this
9839                // packages files and can not delete any more.  Bail.
9840                return null;
9841            }
9842            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9843            if (lastPackage != null) {
9844                pkgs.remove(lastPackage);
9845            }
9846            if (pkgs.size() > 0) {
9847                return pkgs.get(0);
9848            }
9849        }
9850        return null;
9851    }
9852
9853    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9854        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9855                userId, andCode ? 1 : 0, packageName);
9856        if (mSystemReady) {
9857            msg.sendToTarget();
9858        } else {
9859            if (mPostSystemReadyMessages == null) {
9860                mPostSystemReadyMessages = new ArrayList<>();
9861            }
9862            mPostSystemReadyMessages.add(msg);
9863        }
9864    }
9865
9866    void startCleaningPackages() {
9867        // reader
9868        synchronized (mPackages) {
9869            if (!isExternalMediaAvailable()) {
9870                return;
9871            }
9872            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9873                return;
9874            }
9875        }
9876        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9877        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9878        IActivityManager am = ActivityManagerNative.getDefault();
9879        if (am != null) {
9880            try {
9881                am.startService(null, intent, null, mContext.getOpPackageName(),
9882                        UserHandle.USER_SYSTEM);
9883            } catch (RemoteException e) {
9884            }
9885        }
9886    }
9887
9888    @Override
9889    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9890            int installFlags, String installerPackageName, VerificationParams verificationParams,
9891            String packageAbiOverride) {
9892        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9893                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9894    }
9895
9896    @Override
9897    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9898            int installFlags, String installerPackageName, VerificationParams verificationParams,
9899            String packageAbiOverride, int userId) {
9900        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9901
9902        final int callingUid = Binder.getCallingUid();
9903        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9904
9905        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9906            try {
9907                if (observer != null) {
9908                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9909                }
9910            } catch (RemoteException re) {
9911            }
9912            return;
9913        }
9914
9915        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9916            installFlags |= PackageManager.INSTALL_FROM_ADB;
9917
9918        } else {
9919            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9920            // about installerPackageName.
9921
9922            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9923            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9924        }
9925
9926        UserHandle user;
9927        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9928            user = UserHandle.ALL;
9929        } else {
9930            user = new UserHandle(userId);
9931        }
9932
9933        // Only system components can circumvent runtime permissions when installing.
9934        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9935                && mContext.checkCallingOrSelfPermission(Manifest.permission
9936                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9937            throw new SecurityException("You need the "
9938                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9939                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9940        }
9941
9942        verificationParams.setInstallerUid(callingUid);
9943
9944        final File originFile = new File(originPath);
9945        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9946
9947        final Message msg = mHandler.obtainMessage(INIT_COPY);
9948        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9949                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9950        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9951        msg.obj = params;
9952
9953        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9954                System.identityHashCode(msg.obj));
9955        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9956                System.identityHashCode(msg.obj));
9957
9958        mHandler.sendMessage(msg);
9959    }
9960
9961    void installStage(String packageName, File stagedDir, String stagedCid,
9962            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9963            String installerPackageName, int installerUid, UserHandle user) {
9964        if (DEBUG_EPHEMERAL) {
9965            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9966                Slog.d(TAG, "Ephemeral install of " + packageName);
9967            }
9968        }
9969        final VerificationParams verifParams = new VerificationParams(
9970                null, sessionParams.originatingUri, sessionParams.referrerUri,
9971                sessionParams.originatingUid);
9972        verifParams.setInstallerUid(installerUid);
9973
9974        final OriginInfo origin;
9975        if (stagedDir != null) {
9976            origin = OriginInfo.fromStagedFile(stagedDir);
9977        } else {
9978            origin = OriginInfo.fromStagedContainer(stagedCid);
9979        }
9980
9981        final Message msg = mHandler.obtainMessage(INIT_COPY);
9982        final InstallParams params = new InstallParams(origin, null, observer,
9983                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9984                verifParams, user, sessionParams.abiOverride,
9985                sessionParams.grantedRuntimePermissions);
9986        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9987        msg.obj = params;
9988
9989        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9990                System.identityHashCode(msg.obj));
9991        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9992                System.identityHashCode(msg.obj));
9993
9994        mHandler.sendMessage(msg);
9995    }
9996
9997    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9998        Bundle extras = new Bundle(1);
9999        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10000
10001        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10002                packageName, extras, 0, null, null, new int[] {userId});
10003        try {
10004            IActivityManager am = ActivityManagerNative.getDefault();
10005            final boolean isSystem =
10006                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10007            if (isSystem && am.isUserRunning(userId, 0)) {
10008                // The just-installed/enabled app is bundled on the system, so presumed
10009                // to be able to run automatically without needing an explicit launch.
10010                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10011                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10012                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10013                        .setPackage(packageName);
10014                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10015                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10016            }
10017        } catch (RemoteException e) {
10018            // shouldn't happen
10019            Slog.w(TAG, "Unable to bootstrap installed package", e);
10020        }
10021    }
10022
10023    @Override
10024    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10025            int userId) {
10026        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10027        PackageSetting pkgSetting;
10028        final int uid = Binder.getCallingUid();
10029        enforceCrossUserPermission(uid, userId, true, true,
10030                "setApplicationHiddenSetting for user " + userId);
10031
10032        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10033            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10034            return false;
10035        }
10036
10037        long callingId = Binder.clearCallingIdentity();
10038        try {
10039            boolean sendAdded = false;
10040            boolean sendRemoved = false;
10041            // writer
10042            synchronized (mPackages) {
10043                pkgSetting = mSettings.mPackages.get(packageName);
10044                if (pkgSetting == null) {
10045                    return false;
10046                }
10047                if (pkgSetting.getHidden(userId) != hidden) {
10048                    pkgSetting.setHidden(hidden, userId);
10049                    mSettings.writePackageRestrictionsLPr(userId);
10050                    if (hidden) {
10051                        sendRemoved = true;
10052                    } else {
10053                        sendAdded = true;
10054                    }
10055                }
10056            }
10057            if (sendAdded) {
10058                sendPackageAddedForUser(packageName, pkgSetting, userId);
10059                return true;
10060            }
10061            if (sendRemoved) {
10062                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10063                        "hiding pkg");
10064                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10065                return true;
10066            }
10067        } finally {
10068            Binder.restoreCallingIdentity(callingId);
10069        }
10070        return false;
10071    }
10072
10073    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10074            int userId) {
10075        final PackageRemovedInfo info = new PackageRemovedInfo();
10076        info.removedPackage = packageName;
10077        info.removedUsers = new int[] {userId};
10078        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10079        info.sendBroadcast(false, false, false);
10080    }
10081
10082    /**
10083     * Returns true if application is not found or there was an error. Otherwise it returns
10084     * the hidden state of the package for the given user.
10085     */
10086    @Override
10087    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10088        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10089        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10090                false, "getApplicationHidden for user " + userId);
10091        PackageSetting pkgSetting;
10092        long callingId = Binder.clearCallingIdentity();
10093        try {
10094            // writer
10095            synchronized (mPackages) {
10096                pkgSetting = mSettings.mPackages.get(packageName);
10097                if (pkgSetting == null) {
10098                    return true;
10099                }
10100                return pkgSetting.getHidden(userId);
10101            }
10102        } finally {
10103            Binder.restoreCallingIdentity(callingId);
10104        }
10105    }
10106
10107    /**
10108     * @hide
10109     */
10110    @Override
10111    public int installExistingPackageAsUser(String packageName, int userId) {
10112        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10113                null);
10114        PackageSetting pkgSetting;
10115        final int uid = Binder.getCallingUid();
10116        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10117                + userId);
10118        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10119            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10120        }
10121
10122        long callingId = Binder.clearCallingIdentity();
10123        try {
10124            boolean installed = false;
10125
10126            // writer
10127            synchronized (mPackages) {
10128                pkgSetting = mSettings.mPackages.get(packageName);
10129                if (pkgSetting == null) {
10130                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10131                }
10132                if (!pkgSetting.getInstalled(userId)) {
10133                    pkgSetting.setInstalled(true, userId);
10134                    pkgSetting.setHidden(false, userId);
10135                    mSettings.writePackageRestrictionsLPr(userId);
10136                    if (pkgSetting.pkg != null) {
10137                        prepareAppDataAfterInstall(pkgSetting.pkg);
10138                    }
10139                    installed = true;
10140                }
10141            }
10142
10143            if (installed) {
10144                sendPackageAddedForUser(packageName, pkgSetting, userId);
10145            }
10146        } finally {
10147            Binder.restoreCallingIdentity(callingId);
10148        }
10149
10150        return PackageManager.INSTALL_SUCCEEDED;
10151    }
10152
10153    boolean isUserRestricted(int userId, String restrictionKey) {
10154        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10155        if (restrictions.getBoolean(restrictionKey, false)) {
10156            Log.w(TAG, "User is restricted: " + restrictionKey);
10157            return true;
10158        }
10159        return false;
10160    }
10161
10162    @Override
10163    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10164        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10165        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10166                "setPackageSuspended for user " + userId);
10167
10168        long callingId = Binder.clearCallingIdentity();
10169        try {
10170            synchronized (mPackages) {
10171                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10172                if (pkgSetting != null) {
10173                    if (pkgSetting.getSuspended(userId) != suspended) {
10174                        pkgSetting.setSuspended(suspended, userId);
10175                        mSettings.writePackageRestrictionsLPr(userId);
10176                    }
10177
10178                    // TODO:
10179                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10180                    // * remove app from recents (kill app it if it is running)
10181                    // * erase existing notifications for this app
10182                    return true;
10183                }
10184
10185                return false;
10186            }
10187        } finally {
10188            Binder.restoreCallingIdentity(callingId);
10189        }
10190    }
10191
10192    @Override
10193    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10194        mContext.enforceCallingOrSelfPermission(
10195                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10196                "Only package verification agents can verify applications");
10197
10198        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10199        final PackageVerificationResponse response = new PackageVerificationResponse(
10200                verificationCode, Binder.getCallingUid());
10201        msg.arg1 = id;
10202        msg.obj = response;
10203        mHandler.sendMessage(msg);
10204    }
10205
10206    @Override
10207    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10208            long millisecondsToDelay) {
10209        mContext.enforceCallingOrSelfPermission(
10210                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10211                "Only package verification agents can extend verification timeouts");
10212
10213        final PackageVerificationState state = mPendingVerification.get(id);
10214        final PackageVerificationResponse response = new PackageVerificationResponse(
10215                verificationCodeAtTimeout, Binder.getCallingUid());
10216
10217        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10218            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10219        }
10220        if (millisecondsToDelay < 0) {
10221            millisecondsToDelay = 0;
10222        }
10223        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10224                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10225            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10226        }
10227
10228        if ((state != null) && !state.timeoutExtended()) {
10229            state.extendTimeout();
10230
10231            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10232            msg.arg1 = id;
10233            msg.obj = response;
10234            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10235        }
10236    }
10237
10238    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10239            int verificationCode, UserHandle user) {
10240        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10241        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10242        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10243        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10244        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10245
10246        mContext.sendBroadcastAsUser(intent, user,
10247                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10248    }
10249
10250    private ComponentName matchComponentForVerifier(String packageName,
10251            List<ResolveInfo> receivers) {
10252        ActivityInfo targetReceiver = null;
10253
10254        final int NR = receivers.size();
10255        for (int i = 0; i < NR; i++) {
10256            final ResolveInfo info = receivers.get(i);
10257            if (info.activityInfo == null) {
10258                continue;
10259            }
10260
10261            if (packageName.equals(info.activityInfo.packageName)) {
10262                targetReceiver = info.activityInfo;
10263                break;
10264            }
10265        }
10266
10267        if (targetReceiver == null) {
10268            return null;
10269        }
10270
10271        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10272    }
10273
10274    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10275            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10276        if (pkgInfo.verifiers.length == 0) {
10277            return null;
10278        }
10279
10280        final int N = pkgInfo.verifiers.length;
10281        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10282        for (int i = 0; i < N; i++) {
10283            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10284
10285            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10286                    receivers);
10287            if (comp == null) {
10288                continue;
10289            }
10290
10291            final int verifierUid = getUidForVerifier(verifierInfo);
10292            if (verifierUid == -1) {
10293                continue;
10294            }
10295
10296            if (DEBUG_VERIFY) {
10297                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10298                        + " with the correct signature");
10299            }
10300            sufficientVerifiers.add(comp);
10301            verificationState.addSufficientVerifier(verifierUid);
10302        }
10303
10304        return sufficientVerifiers;
10305    }
10306
10307    private int getUidForVerifier(VerifierInfo verifierInfo) {
10308        synchronized (mPackages) {
10309            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10310            if (pkg == null) {
10311                return -1;
10312            } else if (pkg.mSignatures.length != 1) {
10313                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10314                        + " has more than one signature; ignoring");
10315                return -1;
10316            }
10317
10318            /*
10319             * If the public key of the package's signature does not match
10320             * our expected public key, then this is a different package and
10321             * we should skip.
10322             */
10323
10324            final byte[] expectedPublicKey;
10325            try {
10326                final Signature verifierSig = pkg.mSignatures[0];
10327                final PublicKey publicKey = verifierSig.getPublicKey();
10328                expectedPublicKey = publicKey.getEncoded();
10329            } catch (CertificateException e) {
10330                return -1;
10331            }
10332
10333            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10334
10335            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10336                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10337                        + " does not have the expected public key; ignoring");
10338                return -1;
10339            }
10340
10341            return pkg.applicationInfo.uid;
10342        }
10343    }
10344
10345    @Override
10346    public void finishPackageInstall(int token) {
10347        enforceSystemOrRoot("Only the system is allowed to finish installs");
10348
10349        if (DEBUG_INSTALL) {
10350            Slog.v(TAG, "BM finishing package install for " + token);
10351        }
10352        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10353
10354        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10355        mHandler.sendMessage(msg);
10356    }
10357
10358    /**
10359     * Get the verification agent timeout.
10360     *
10361     * @return verification timeout in milliseconds
10362     */
10363    private long getVerificationTimeout() {
10364        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10365                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10366                DEFAULT_VERIFICATION_TIMEOUT);
10367    }
10368
10369    /**
10370     * Get the default verification agent response code.
10371     *
10372     * @return default verification response code
10373     */
10374    private int getDefaultVerificationResponse() {
10375        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10376                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10377                DEFAULT_VERIFICATION_RESPONSE);
10378    }
10379
10380    /**
10381     * Check whether or not package verification has been enabled.
10382     *
10383     * @return true if verification should be performed
10384     */
10385    private boolean isVerificationEnabled(int userId, int installFlags) {
10386        if (!DEFAULT_VERIFY_ENABLE) {
10387            return false;
10388        }
10389        // Ephemeral apps don't get the full verification treatment
10390        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10391            if (DEBUG_EPHEMERAL) {
10392                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10393            }
10394            return false;
10395        }
10396
10397        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10398
10399        // Check if installing from ADB
10400        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10401            // Do not run verification in a test harness environment
10402            if (ActivityManager.isRunningInTestHarness()) {
10403                return false;
10404            }
10405            if (ensureVerifyAppsEnabled) {
10406                return true;
10407            }
10408            // Check if the developer does not want package verification for ADB installs
10409            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10410                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10411                return false;
10412            }
10413        }
10414
10415        if (ensureVerifyAppsEnabled) {
10416            return true;
10417        }
10418
10419        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10420                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10421    }
10422
10423    @Override
10424    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10425            throws RemoteException {
10426        mContext.enforceCallingOrSelfPermission(
10427                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10428                "Only intentfilter verification agents can verify applications");
10429
10430        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10431        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10432                Binder.getCallingUid(), verificationCode, failedDomains);
10433        msg.arg1 = id;
10434        msg.obj = response;
10435        mHandler.sendMessage(msg);
10436    }
10437
10438    @Override
10439    public int getIntentVerificationStatus(String packageName, int userId) {
10440        synchronized (mPackages) {
10441            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10442        }
10443    }
10444
10445    @Override
10446    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10447        mContext.enforceCallingOrSelfPermission(
10448                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10449
10450        boolean result = false;
10451        synchronized (mPackages) {
10452            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10453        }
10454        if (result) {
10455            scheduleWritePackageRestrictionsLocked(userId);
10456        }
10457        return result;
10458    }
10459
10460    @Override
10461    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10462        synchronized (mPackages) {
10463            return mSettings.getIntentFilterVerificationsLPr(packageName);
10464        }
10465    }
10466
10467    @Override
10468    public List<IntentFilter> getAllIntentFilters(String packageName) {
10469        if (TextUtils.isEmpty(packageName)) {
10470            return Collections.<IntentFilter>emptyList();
10471        }
10472        synchronized (mPackages) {
10473            PackageParser.Package pkg = mPackages.get(packageName);
10474            if (pkg == null || pkg.activities == null) {
10475                return Collections.<IntentFilter>emptyList();
10476            }
10477            final int count = pkg.activities.size();
10478            ArrayList<IntentFilter> result = new ArrayList<>();
10479            for (int n=0; n<count; n++) {
10480                PackageParser.Activity activity = pkg.activities.get(n);
10481                if (activity.intents != null && activity.intents.size() > 0) {
10482                    result.addAll(activity.intents);
10483                }
10484            }
10485            return result;
10486        }
10487    }
10488
10489    @Override
10490    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10491        mContext.enforceCallingOrSelfPermission(
10492                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10493
10494        synchronized (mPackages) {
10495            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10496            if (packageName != null) {
10497                result |= updateIntentVerificationStatus(packageName,
10498                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10499                        userId);
10500                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10501                        packageName, userId);
10502            }
10503            return result;
10504        }
10505    }
10506
10507    @Override
10508    public String getDefaultBrowserPackageName(int userId) {
10509        synchronized (mPackages) {
10510            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10511        }
10512    }
10513
10514    /**
10515     * Get the "allow unknown sources" setting.
10516     *
10517     * @return the current "allow unknown sources" setting
10518     */
10519    private int getUnknownSourcesSettings() {
10520        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10521                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10522                -1);
10523    }
10524
10525    @Override
10526    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10527        final int uid = Binder.getCallingUid();
10528        // writer
10529        synchronized (mPackages) {
10530            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10531            if (targetPackageSetting == null) {
10532                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10533            }
10534
10535            PackageSetting installerPackageSetting;
10536            if (installerPackageName != null) {
10537                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10538                if (installerPackageSetting == null) {
10539                    throw new IllegalArgumentException("Unknown installer package: "
10540                            + installerPackageName);
10541                }
10542            } else {
10543                installerPackageSetting = null;
10544            }
10545
10546            Signature[] callerSignature;
10547            Object obj = mSettings.getUserIdLPr(uid);
10548            if (obj != null) {
10549                if (obj instanceof SharedUserSetting) {
10550                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10551                } else if (obj instanceof PackageSetting) {
10552                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10553                } else {
10554                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10555                }
10556            } else {
10557                throw new SecurityException("Unknown calling UID: " + uid);
10558            }
10559
10560            // Verify: can't set installerPackageName to a package that is
10561            // not signed with the same cert as the caller.
10562            if (installerPackageSetting != null) {
10563                if (compareSignatures(callerSignature,
10564                        installerPackageSetting.signatures.mSignatures)
10565                        != PackageManager.SIGNATURE_MATCH) {
10566                    throw new SecurityException(
10567                            "Caller does not have same cert as new installer package "
10568                            + installerPackageName);
10569                }
10570            }
10571
10572            // Verify: if target already has an installer package, it must
10573            // be signed with the same cert as the caller.
10574            if (targetPackageSetting.installerPackageName != null) {
10575                PackageSetting setting = mSettings.mPackages.get(
10576                        targetPackageSetting.installerPackageName);
10577                // If the currently set package isn't valid, then it's always
10578                // okay to change it.
10579                if (setting != null) {
10580                    if (compareSignatures(callerSignature,
10581                            setting.signatures.mSignatures)
10582                            != PackageManager.SIGNATURE_MATCH) {
10583                        throw new SecurityException(
10584                                "Caller does not have same cert as old installer package "
10585                                + targetPackageSetting.installerPackageName);
10586                    }
10587                }
10588            }
10589
10590            // Okay!
10591            targetPackageSetting.installerPackageName = installerPackageName;
10592            scheduleWriteSettingsLocked();
10593        }
10594    }
10595
10596    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10597        // Queue up an async operation since the package installation may take a little while.
10598        mHandler.post(new Runnable() {
10599            public void run() {
10600                mHandler.removeCallbacks(this);
10601                 // Result object to be returned
10602                PackageInstalledInfo res = new PackageInstalledInfo();
10603                res.returnCode = currentStatus;
10604                res.uid = -1;
10605                res.pkg = null;
10606                res.removedInfo = new PackageRemovedInfo();
10607                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10608                    args.doPreInstall(res.returnCode);
10609                    synchronized (mInstallLock) {
10610                        installPackageTracedLI(args, res);
10611                    }
10612                    args.doPostInstall(res.returnCode, res.uid);
10613                }
10614
10615                // A restore should be performed at this point if (a) the install
10616                // succeeded, (b) the operation is not an update, and (c) the new
10617                // package has not opted out of backup participation.
10618                final boolean update = res.removedInfo.removedPackage != null;
10619                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10620                boolean doRestore = !update
10621                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10622
10623                // Set up the post-install work request bookkeeping.  This will be used
10624                // and cleaned up by the post-install event handling regardless of whether
10625                // there's a restore pass performed.  Token values are >= 1.
10626                int token;
10627                if (mNextInstallToken < 0) mNextInstallToken = 1;
10628                token = mNextInstallToken++;
10629
10630                PostInstallData data = new PostInstallData(args, res);
10631                mRunningInstalls.put(token, data);
10632                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10633
10634                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10635                    // Pass responsibility to the Backup Manager.  It will perform a
10636                    // restore if appropriate, then pass responsibility back to the
10637                    // Package Manager to run the post-install observer callbacks
10638                    // and broadcasts.
10639                    IBackupManager bm = IBackupManager.Stub.asInterface(
10640                            ServiceManager.getService(Context.BACKUP_SERVICE));
10641                    if (bm != null) {
10642                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10643                                + " to BM for possible restore");
10644                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10645                        try {
10646                            // TODO: http://b/22388012
10647                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10648                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10649                            } else {
10650                                doRestore = false;
10651                            }
10652                        } catch (RemoteException e) {
10653                            // can't happen; the backup manager is local
10654                        } catch (Exception e) {
10655                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10656                            doRestore = false;
10657                        }
10658                    } else {
10659                        Slog.e(TAG, "Backup Manager not found!");
10660                        doRestore = false;
10661                    }
10662                }
10663
10664                if (!doRestore) {
10665                    // No restore possible, or the Backup Manager was mysteriously not
10666                    // available -- just fire the post-install work request directly.
10667                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10668
10669                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10670
10671                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10672                    mHandler.sendMessage(msg);
10673                }
10674            }
10675        });
10676    }
10677
10678    private abstract class HandlerParams {
10679        private static final int MAX_RETRIES = 4;
10680
10681        /**
10682         * Number of times startCopy() has been attempted and had a non-fatal
10683         * error.
10684         */
10685        private int mRetries = 0;
10686
10687        /** User handle for the user requesting the information or installation. */
10688        private final UserHandle mUser;
10689        String traceMethod;
10690        int traceCookie;
10691
10692        HandlerParams(UserHandle user) {
10693            mUser = user;
10694        }
10695
10696        UserHandle getUser() {
10697            return mUser;
10698        }
10699
10700        HandlerParams setTraceMethod(String traceMethod) {
10701            this.traceMethod = traceMethod;
10702            return this;
10703        }
10704
10705        HandlerParams setTraceCookie(int traceCookie) {
10706            this.traceCookie = traceCookie;
10707            return this;
10708        }
10709
10710        final boolean startCopy() {
10711            boolean res;
10712            try {
10713                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10714
10715                if (++mRetries > MAX_RETRIES) {
10716                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10717                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10718                    handleServiceError();
10719                    return false;
10720                } else {
10721                    handleStartCopy();
10722                    res = true;
10723                }
10724            } catch (RemoteException e) {
10725                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10726                mHandler.sendEmptyMessage(MCS_RECONNECT);
10727                res = false;
10728            }
10729            handleReturnCode();
10730            return res;
10731        }
10732
10733        final void serviceError() {
10734            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10735            handleServiceError();
10736            handleReturnCode();
10737        }
10738
10739        abstract void handleStartCopy() throws RemoteException;
10740        abstract void handleServiceError();
10741        abstract void handleReturnCode();
10742    }
10743
10744    class MeasureParams extends HandlerParams {
10745        private final PackageStats mStats;
10746        private boolean mSuccess;
10747
10748        private final IPackageStatsObserver mObserver;
10749
10750        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10751            super(new UserHandle(stats.userHandle));
10752            mObserver = observer;
10753            mStats = stats;
10754        }
10755
10756        @Override
10757        public String toString() {
10758            return "MeasureParams{"
10759                + Integer.toHexString(System.identityHashCode(this))
10760                + " " + mStats.packageName + "}";
10761        }
10762
10763        @Override
10764        void handleStartCopy() throws RemoteException {
10765            synchronized (mInstallLock) {
10766                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10767            }
10768
10769            if (mSuccess) {
10770                final boolean mounted;
10771                if (Environment.isExternalStorageEmulated()) {
10772                    mounted = true;
10773                } else {
10774                    final String status = Environment.getExternalStorageState();
10775                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10776                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10777                }
10778
10779                if (mounted) {
10780                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10781
10782                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10783                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10784
10785                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10786                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10787
10788                    // Always subtract cache size, since it's a subdirectory
10789                    mStats.externalDataSize -= mStats.externalCacheSize;
10790
10791                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10792                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10793
10794                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10795                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10796                }
10797            }
10798        }
10799
10800        @Override
10801        void handleReturnCode() {
10802            if (mObserver != null) {
10803                try {
10804                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10805                } catch (RemoteException e) {
10806                    Slog.i(TAG, "Observer no longer exists.");
10807                }
10808            }
10809        }
10810
10811        @Override
10812        void handleServiceError() {
10813            Slog.e(TAG, "Could not measure application " + mStats.packageName
10814                            + " external storage");
10815        }
10816    }
10817
10818    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10819            throws RemoteException {
10820        long result = 0;
10821        for (File path : paths) {
10822            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10823        }
10824        return result;
10825    }
10826
10827    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10828        for (File path : paths) {
10829            try {
10830                mcs.clearDirectory(path.getAbsolutePath());
10831            } catch (RemoteException e) {
10832            }
10833        }
10834    }
10835
10836    static class OriginInfo {
10837        /**
10838         * Location where install is coming from, before it has been
10839         * copied/renamed into place. This could be a single monolithic APK
10840         * file, or a cluster directory. This location may be untrusted.
10841         */
10842        final File file;
10843        final String cid;
10844
10845        /**
10846         * Flag indicating that {@link #file} or {@link #cid} has already been
10847         * staged, meaning downstream users don't need to defensively copy the
10848         * contents.
10849         */
10850        final boolean staged;
10851
10852        /**
10853         * Flag indicating that {@link #file} or {@link #cid} is an already
10854         * installed app that is being moved.
10855         */
10856        final boolean existing;
10857
10858        final String resolvedPath;
10859        final File resolvedFile;
10860
10861        static OriginInfo fromNothing() {
10862            return new OriginInfo(null, null, false, false);
10863        }
10864
10865        static OriginInfo fromUntrustedFile(File file) {
10866            return new OriginInfo(file, null, false, false);
10867        }
10868
10869        static OriginInfo fromExistingFile(File file) {
10870            return new OriginInfo(file, null, false, true);
10871        }
10872
10873        static OriginInfo fromStagedFile(File file) {
10874            return new OriginInfo(file, null, true, false);
10875        }
10876
10877        static OriginInfo fromStagedContainer(String cid) {
10878            return new OriginInfo(null, cid, true, false);
10879        }
10880
10881        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10882            this.file = file;
10883            this.cid = cid;
10884            this.staged = staged;
10885            this.existing = existing;
10886
10887            if (cid != null) {
10888                resolvedPath = PackageHelper.getSdDir(cid);
10889                resolvedFile = new File(resolvedPath);
10890            } else if (file != null) {
10891                resolvedPath = file.getAbsolutePath();
10892                resolvedFile = file;
10893            } else {
10894                resolvedPath = null;
10895                resolvedFile = null;
10896            }
10897        }
10898    }
10899
10900    static class MoveInfo {
10901        final int moveId;
10902        final String fromUuid;
10903        final String toUuid;
10904        final String packageName;
10905        final String dataAppName;
10906        final int appId;
10907        final String seinfo;
10908        final int targetSdkVersion;
10909
10910        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10911                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
10912            this.moveId = moveId;
10913            this.fromUuid = fromUuid;
10914            this.toUuid = toUuid;
10915            this.packageName = packageName;
10916            this.dataAppName = dataAppName;
10917            this.appId = appId;
10918            this.seinfo = seinfo;
10919            this.targetSdkVersion = targetSdkVersion;
10920        }
10921    }
10922
10923    class InstallParams extends HandlerParams {
10924        final OriginInfo origin;
10925        final MoveInfo move;
10926        final IPackageInstallObserver2 observer;
10927        int installFlags;
10928        final String installerPackageName;
10929        final String volumeUuid;
10930        final VerificationParams verificationParams;
10931        private InstallArgs mArgs;
10932        private int mRet;
10933        final String packageAbiOverride;
10934        final String[] grantedRuntimePermissions;
10935
10936        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10937                int installFlags, String installerPackageName, String volumeUuid,
10938                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10939                String[] grantedPermissions) {
10940            super(user);
10941            this.origin = origin;
10942            this.move = move;
10943            this.observer = observer;
10944            this.installFlags = installFlags;
10945            this.installerPackageName = installerPackageName;
10946            this.volumeUuid = volumeUuid;
10947            this.verificationParams = verificationParams;
10948            this.packageAbiOverride = packageAbiOverride;
10949            this.grantedRuntimePermissions = grantedPermissions;
10950        }
10951
10952        @Override
10953        public String toString() {
10954            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10955                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10956        }
10957
10958        private int installLocationPolicy(PackageInfoLite pkgLite) {
10959            String packageName = pkgLite.packageName;
10960            int installLocation = pkgLite.installLocation;
10961            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10962            // reader
10963            synchronized (mPackages) {
10964                PackageParser.Package pkg = mPackages.get(packageName);
10965                if (pkg != null) {
10966                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10967                        // Check for downgrading.
10968                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10969                            try {
10970                                checkDowngrade(pkg, pkgLite);
10971                            } catch (PackageManagerException e) {
10972                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10973                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10974                            }
10975                        }
10976                        // Check for updated system application.
10977                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10978                            if (onSd) {
10979                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10980                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10981                            }
10982                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10983                        } else {
10984                            if (onSd) {
10985                                // Install flag overrides everything.
10986                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10987                            }
10988                            // If current upgrade specifies particular preference
10989                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10990                                // Application explicitly specified internal.
10991                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10992                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10993                                // App explictly prefers external. Let policy decide
10994                            } else {
10995                                // Prefer previous location
10996                                if (isExternal(pkg)) {
10997                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10998                                }
10999                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11000                            }
11001                        }
11002                    } else {
11003                        // Invalid install. Return error code
11004                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11005                    }
11006                }
11007            }
11008            // All the special cases have been taken care of.
11009            // Return result based on recommended install location.
11010            if (onSd) {
11011                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11012            }
11013            return pkgLite.recommendedInstallLocation;
11014        }
11015
11016        /*
11017         * Invoke remote method to get package information and install
11018         * location values. Override install location based on default
11019         * policy if needed and then create install arguments based
11020         * on the install location.
11021         */
11022        public void handleStartCopy() throws RemoteException {
11023            int ret = PackageManager.INSTALL_SUCCEEDED;
11024
11025            // If we're already staged, we've firmly committed to an install location
11026            if (origin.staged) {
11027                if (origin.file != null) {
11028                    installFlags |= PackageManager.INSTALL_INTERNAL;
11029                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11030                } else if (origin.cid != null) {
11031                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11032                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11033                } else {
11034                    throw new IllegalStateException("Invalid stage location");
11035                }
11036            }
11037
11038            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11039            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11040            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11041            PackageInfoLite pkgLite = null;
11042
11043            if (onInt && onSd) {
11044                // Check if both bits are set.
11045                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11046                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11047            } else if (onSd && ephemeral) {
11048                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11049                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11050            } else {
11051                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11052                        packageAbiOverride);
11053
11054                if (DEBUG_EPHEMERAL && ephemeral) {
11055                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11056                }
11057
11058                /*
11059                 * If we have too little free space, try to free cache
11060                 * before giving up.
11061                 */
11062                if (!origin.staged && pkgLite.recommendedInstallLocation
11063                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11064                    // TODO: focus freeing disk space on the target device
11065                    final StorageManager storage = StorageManager.from(mContext);
11066                    final long lowThreshold = storage.getStorageLowBytes(
11067                            Environment.getDataDirectory());
11068
11069                    final long sizeBytes = mContainerService.calculateInstalledSize(
11070                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11071
11072                    try {
11073                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11074                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11075                                installFlags, packageAbiOverride);
11076                    } catch (InstallerException e) {
11077                        Slog.w(TAG, "Failed to free cache", e);
11078                    }
11079
11080                    /*
11081                     * The cache free must have deleted the file we
11082                     * downloaded to install.
11083                     *
11084                     * TODO: fix the "freeCache" call to not delete
11085                     *       the file we care about.
11086                     */
11087                    if (pkgLite.recommendedInstallLocation
11088                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11089                        pkgLite.recommendedInstallLocation
11090                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11091                    }
11092                }
11093            }
11094
11095            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11096                int loc = pkgLite.recommendedInstallLocation;
11097                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11098                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11099                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11100                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11101                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11102                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11103                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11104                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11105                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11106                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11107                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11108                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11109                } else {
11110                    // Override with defaults if needed.
11111                    loc = installLocationPolicy(pkgLite);
11112                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11113                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11114                    } else if (!onSd && !onInt) {
11115                        // Override install location with flags
11116                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11117                            // Set the flag to install on external media.
11118                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11119                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11120                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11121                            if (DEBUG_EPHEMERAL) {
11122                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11123                            }
11124                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11125                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11126                                    |PackageManager.INSTALL_INTERNAL);
11127                        } else {
11128                            // Make sure the flag for installing on external
11129                            // media is unset
11130                            installFlags |= PackageManager.INSTALL_INTERNAL;
11131                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11132                        }
11133                    }
11134                }
11135            }
11136
11137            final InstallArgs args = createInstallArgs(this);
11138            mArgs = args;
11139
11140            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11141                // TODO: http://b/22976637
11142                // Apps installed for "all" users use the device owner to verify the app
11143                UserHandle verifierUser = getUser();
11144                if (verifierUser == UserHandle.ALL) {
11145                    verifierUser = UserHandle.SYSTEM;
11146                }
11147
11148                /*
11149                 * Determine if we have any installed package verifiers. If we
11150                 * do, then we'll defer to them to verify the packages.
11151                 */
11152                final int requiredUid = mRequiredVerifierPackage == null ? -1
11153                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11154                                verifierUser.getIdentifier());
11155                if (!origin.existing && requiredUid != -1
11156                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11157                    final Intent verification = new Intent(
11158                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11159                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11160                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11161                            PACKAGE_MIME_TYPE);
11162                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11163
11164                    // Query all live verifiers based on current user state
11165                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11166                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11167
11168                    if (DEBUG_VERIFY) {
11169                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11170                                + verification.toString() + " with " + pkgLite.verifiers.length
11171                                + " optional verifiers");
11172                    }
11173
11174                    final int verificationId = mPendingVerificationToken++;
11175
11176                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11177
11178                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11179                            installerPackageName);
11180
11181                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11182                            installFlags);
11183
11184                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11185                            pkgLite.packageName);
11186
11187                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11188                            pkgLite.versionCode);
11189
11190                    if (verificationParams != null) {
11191                        if (verificationParams.getVerificationURI() != null) {
11192                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11193                                 verificationParams.getVerificationURI());
11194                        }
11195                        if (verificationParams.getOriginatingURI() != null) {
11196                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11197                                  verificationParams.getOriginatingURI());
11198                        }
11199                        if (verificationParams.getReferrer() != null) {
11200                            verification.putExtra(Intent.EXTRA_REFERRER,
11201                                  verificationParams.getReferrer());
11202                        }
11203                        if (verificationParams.getOriginatingUid() >= 0) {
11204                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11205                                  verificationParams.getOriginatingUid());
11206                        }
11207                        if (verificationParams.getInstallerUid() >= 0) {
11208                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11209                                  verificationParams.getInstallerUid());
11210                        }
11211                    }
11212
11213                    final PackageVerificationState verificationState = new PackageVerificationState(
11214                            requiredUid, args);
11215
11216                    mPendingVerification.append(verificationId, verificationState);
11217
11218                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11219                            receivers, verificationState);
11220
11221                    /*
11222                     * If any sufficient verifiers were listed in the package
11223                     * manifest, attempt to ask them.
11224                     */
11225                    if (sufficientVerifiers != null) {
11226                        final int N = sufficientVerifiers.size();
11227                        if (N == 0) {
11228                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11229                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11230                        } else {
11231                            for (int i = 0; i < N; i++) {
11232                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11233
11234                                final Intent sufficientIntent = new Intent(verification);
11235                                sufficientIntent.setComponent(verifierComponent);
11236                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11237                            }
11238                        }
11239                    }
11240
11241                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11242                            mRequiredVerifierPackage, receivers);
11243                    if (ret == PackageManager.INSTALL_SUCCEEDED
11244                            && mRequiredVerifierPackage != null) {
11245                        Trace.asyncTraceBegin(
11246                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11247                        /*
11248                         * Send the intent to the required verification agent,
11249                         * but only start the verification timeout after the
11250                         * target BroadcastReceivers have run.
11251                         */
11252                        verification.setComponent(requiredVerifierComponent);
11253                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11254                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11255                                new BroadcastReceiver() {
11256                                    @Override
11257                                    public void onReceive(Context context, Intent intent) {
11258                                        final Message msg = mHandler
11259                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11260                                        msg.arg1 = verificationId;
11261                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11262                                    }
11263                                }, null, 0, null, null);
11264
11265                        /*
11266                         * We don't want the copy to proceed until verification
11267                         * succeeds, so null out this field.
11268                         */
11269                        mArgs = null;
11270                    }
11271                } else {
11272                    /*
11273                     * No package verification is enabled, so immediately start
11274                     * the remote call to initiate copy using temporary file.
11275                     */
11276                    ret = args.copyApk(mContainerService, true);
11277                }
11278            }
11279
11280            mRet = ret;
11281        }
11282
11283        @Override
11284        void handleReturnCode() {
11285            // If mArgs is null, then MCS couldn't be reached. When it
11286            // reconnects, it will try again to install. At that point, this
11287            // will succeed.
11288            if (mArgs != null) {
11289                processPendingInstall(mArgs, mRet);
11290            }
11291        }
11292
11293        @Override
11294        void handleServiceError() {
11295            mArgs = createInstallArgs(this);
11296            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11297        }
11298
11299        public boolean isForwardLocked() {
11300            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11301        }
11302    }
11303
11304    /**
11305     * Used during creation of InstallArgs
11306     *
11307     * @param installFlags package installation flags
11308     * @return true if should be installed on external storage
11309     */
11310    private static boolean installOnExternalAsec(int installFlags) {
11311        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11312            return false;
11313        }
11314        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11315            return true;
11316        }
11317        return false;
11318    }
11319
11320    /**
11321     * Used during creation of InstallArgs
11322     *
11323     * @param installFlags package installation flags
11324     * @return true if should be installed as forward locked
11325     */
11326    private static boolean installForwardLocked(int installFlags) {
11327        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11328    }
11329
11330    private InstallArgs createInstallArgs(InstallParams params) {
11331        if (params.move != null) {
11332            return new MoveInstallArgs(params);
11333        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11334            return new AsecInstallArgs(params);
11335        } else {
11336            return new FileInstallArgs(params);
11337        }
11338    }
11339
11340    /**
11341     * Create args that describe an existing installed package. Typically used
11342     * when cleaning up old installs, or used as a move source.
11343     */
11344    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11345            String resourcePath, String[] instructionSets) {
11346        final boolean isInAsec;
11347        if (installOnExternalAsec(installFlags)) {
11348            /* Apps on SD card are always in ASEC containers. */
11349            isInAsec = true;
11350        } else if (installForwardLocked(installFlags)
11351                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11352            /*
11353             * Forward-locked apps are only in ASEC containers if they're the
11354             * new style
11355             */
11356            isInAsec = true;
11357        } else {
11358            isInAsec = false;
11359        }
11360
11361        if (isInAsec) {
11362            return new AsecInstallArgs(codePath, instructionSets,
11363                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11364        } else {
11365            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11366        }
11367    }
11368
11369    static abstract class InstallArgs {
11370        /** @see InstallParams#origin */
11371        final OriginInfo origin;
11372        /** @see InstallParams#move */
11373        final MoveInfo move;
11374
11375        final IPackageInstallObserver2 observer;
11376        // Always refers to PackageManager flags only
11377        final int installFlags;
11378        final String installerPackageName;
11379        final String volumeUuid;
11380        final UserHandle user;
11381        final String abiOverride;
11382        final String[] installGrantPermissions;
11383        /** If non-null, drop an async trace when the install completes */
11384        final String traceMethod;
11385        final int traceCookie;
11386
11387        // The list of instruction sets supported by this app. This is currently
11388        // only used during the rmdex() phase to clean up resources. We can get rid of this
11389        // if we move dex files under the common app path.
11390        /* nullable */ String[] instructionSets;
11391
11392        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11393                int installFlags, String installerPackageName, String volumeUuid,
11394                UserHandle user, String[] instructionSets,
11395                String abiOverride, String[] installGrantPermissions,
11396                String traceMethod, int traceCookie) {
11397            this.origin = origin;
11398            this.move = move;
11399            this.installFlags = installFlags;
11400            this.observer = observer;
11401            this.installerPackageName = installerPackageName;
11402            this.volumeUuid = volumeUuid;
11403            this.user = user;
11404            this.instructionSets = instructionSets;
11405            this.abiOverride = abiOverride;
11406            this.installGrantPermissions = installGrantPermissions;
11407            this.traceMethod = traceMethod;
11408            this.traceCookie = traceCookie;
11409        }
11410
11411        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11412        abstract int doPreInstall(int status);
11413
11414        /**
11415         * Rename package into final resting place. All paths on the given
11416         * scanned package should be updated to reflect the rename.
11417         */
11418        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11419        abstract int doPostInstall(int status, int uid);
11420
11421        /** @see PackageSettingBase#codePathString */
11422        abstract String getCodePath();
11423        /** @see PackageSettingBase#resourcePathString */
11424        abstract String getResourcePath();
11425
11426        // Need installer lock especially for dex file removal.
11427        abstract void cleanUpResourcesLI();
11428        abstract boolean doPostDeleteLI(boolean delete);
11429
11430        /**
11431         * Called before the source arguments are copied. This is used mostly
11432         * for MoveParams when it needs to read the source file to put it in the
11433         * destination.
11434         */
11435        int doPreCopy() {
11436            return PackageManager.INSTALL_SUCCEEDED;
11437        }
11438
11439        /**
11440         * Called after the source arguments are copied. This is used mostly for
11441         * MoveParams when it needs to read the source file to put it in the
11442         * destination.
11443         *
11444         * @return
11445         */
11446        int doPostCopy(int uid) {
11447            return PackageManager.INSTALL_SUCCEEDED;
11448        }
11449
11450        protected boolean isFwdLocked() {
11451            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11452        }
11453
11454        protected boolean isExternalAsec() {
11455            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11456        }
11457
11458        protected boolean isEphemeral() {
11459            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11460        }
11461
11462        UserHandle getUser() {
11463            return user;
11464        }
11465    }
11466
11467    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11468        if (!allCodePaths.isEmpty()) {
11469            if (instructionSets == null) {
11470                throw new IllegalStateException("instructionSet == null");
11471            }
11472            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11473            for (String codePath : allCodePaths) {
11474                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11475                    try {
11476                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11477                    } catch (InstallerException ignored) {
11478                    }
11479                }
11480            }
11481        }
11482    }
11483
11484    /**
11485     * Logic to handle installation of non-ASEC applications, including copying
11486     * and renaming logic.
11487     */
11488    class FileInstallArgs extends InstallArgs {
11489        private File codeFile;
11490        private File resourceFile;
11491
11492        // Example topology:
11493        // /data/app/com.example/base.apk
11494        // /data/app/com.example/split_foo.apk
11495        // /data/app/com.example/lib/arm/libfoo.so
11496        // /data/app/com.example/lib/arm64/libfoo.so
11497        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11498
11499        /** New install */
11500        FileInstallArgs(InstallParams params) {
11501            super(params.origin, params.move, params.observer, params.installFlags,
11502                    params.installerPackageName, params.volumeUuid,
11503                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11504                    params.grantedRuntimePermissions,
11505                    params.traceMethod, params.traceCookie);
11506            if (isFwdLocked()) {
11507                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11508            }
11509        }
11510
11511        /** Existing install */
11512        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11513            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11514                    null, null, null, 0);
11515            this.codeFile = (codePath != null) ? new File(codePath) : null;
11516            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11517        }
11518
11519        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11520            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11521            try {
11522                return doCopyApk(imcs, temp);
11523            } finally {
11524                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11525            }
11526        }
11527
11528        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11529            if (origin.staged) {
11530                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11531                codeFile = origin.file;
11532                resourceFile = origin.file;
11533                return PackageManager.INSTALL_SUCCEEDED;
11534            }
11535
11536            try {
11537                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11538                final File tempDir =
11539                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11540                codeFile = tempDir;
11541                resourceFile = tempDir;
11542            } catch (IOException e) {
11543                Slog.w(TAG, "Failed to create copy file: " + e);
11544                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11545            }
11546
11547            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11548                @Override
11549                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11550                    if (!FileUtils.isValidExtFilename(name)) {
11551                        throw new IllegalArgumentException("Invalid filename: " + name);
11552                    }
11553                    try {
11554                        final File file = new File(codeFile, name);
11555                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11556                                O_RDWR | O_CREAT, 0644);
11557                        Os.chmod(file.getAbsolutePath(), 0644);
11558                        return new ParcelFileDescriptor(fd);
11559                    } catch (ErrnoException e) {
11560                        throw new RemoteException("Failed to open: " + e.getMessage());
11561                    }
11562                }
11563            };
11564
11565            int ret = PackageManager.INSTALL_SUCCEEDED;
11566            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11567            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11568                Slog.e(TAG, "Failed to copy package");
11569                return ret;
11570            }
11571
11572            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11573            NativeLibraryHelper.Handle handle = null;
11574            try {
11575                handle = NativeLibraryHelper.Handle.create(codeFile);
11576                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11577                        abiOverride);
11578            } catch (IOException e) {
11579                Slog.e(TAG, "Copying native libraries failed", e);
11580                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11581            } finally {
11582                IoUtils.closeQuietly(handle);
11583            }
11584
11585            return ret;
11586        }
11587
11588        int doPreInstall(int status) {
11589            if (status != PackageManager.INSTALL_SUCCEEDED) {
11590                cleanUp();
11591            }
11592            return status;
11593        }
11594
11595        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11596            if (status != PackageManager.INSTALL_SUCCEEDED) {
11597                cleanUp();
11598                return false;
11599            }
11600
11601            final File targetDir = codeFile.getParentFile();
11602            final File beforeCodeFile = codeFile;
11603            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11604
11605            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11606            try {
11607                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11608            } catch (ErrnoException e) {
11609                Slog.w(TAG, "Failed to rename", e);
11610                return false;
11611            }
11612
11613            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11614                Slog.w(TAG, "Failed to restorecon");
11615                return false;
11616            }
11617
11618            // Reflect the rename internally
11619            codeFile = afterCodeFile;
11620            resourceFile = afterCodeFile;
11621
11622            // Reflect the rename in scanned details
11623            pkg.codePath = afterCodeFile.getAbsolutePath();
11624            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11625                    pkg.baseCodePath);
11626            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11627                    pkg.splitCodePaths);
11628
11629            // Reflect the rename in app info
11630            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11631            pkg.applicationInfo.setCodePath(pkg.codePath);
11632            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11633            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11634            pkg.applicationInfo.setResourcePath(pkg.codePath);
11635            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11636            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11637
11638            return true;
11639        }
11640
11641        int doPostInstall(int status, int uid) {
11642            if (status != PackageManager.INSTALL_SUCCEEDED) {
11643                cleanUp();
11644            }
11645            return status;
11646        }
11647
11648        @Override
11649        String getCodePath() {
11650            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11651        }
11652
11653        @Override
11654        String getResourcePath() {
11655            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11656        }
11657
11658        private boolean cleanUp() {
11659            if (codeFile == null || !codeFile.exists()) {
11660                return false;
11661            }
11662
11663            removeCodePathLI(codeFile);
11664
11665            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11666                resourceFile.delete();
11667            }
11668
11669            return true;
11670        }
11671
11672        void cleanUpResourcesLI() {
11673            // Try enumerating all code paths before deleting
11674            List<String> allCodePaths = Collections.EMPTY_LIST;
11675            if (codeFile != null && codeFile.exists()) {
11676                try {
11677                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11678                    allCodePaths = pkg.getAllCodePaths();
11679                } catch (PackageParserException e) {
11680                    // Ignored; we tried our best
11681                }
11682            }
11683
11684            cleanUp();
11685            removeDexFiles(allCodePaths, instructionSets);
11686        }
11687
11688        boolean doPostDeleteLI(boolean delete) {
11689            // XXX err, shouldn't we respect the delete flag?
11690            cleanUpResourcesLI();
11691            return true;
11692        }
11693    }
11694
11695    private boolean isAsecExternal(String cid) {
11696        final String asecPath = PackageHelper.getSdFilesystem(cid);
11697        return !asecPath.startsWith(mAsecInternalPath);
11698    }
11699
11700    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11701            PackageManagerException {
11702        if (copyRet < 0) {
11703            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11704                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11705                throw new PackageManagerException(copyRet, message);
11706            }
11707        }
11708    }
11709
11710    /**
11711     * Extract the MountService "container ID" from the full code path of an
11712     * .apk.
11713     */
11714    static String cidFromCodePath(String fullCodePath) {
11715        int eidx = fullCodePath.lastIndexOf("/");
11716        String subStr1 = fullCodePath.substring(0, eidx);
11717        int sidx = subStr1.lastIndexOf("/");
11718        return subStr1.substring(sidx+1, eidx);
11719    }
11720
11721    /**
11722     * Logic to handle installation of ASEC applications, including copying and
11723     * renaming logic.
11724     */
11725    class AsecInstallArgs extends InstallArgs {
11726        static final String RES_FILE_NAME = "pkg.apk";
11727        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11728
11729        String cid;
11730        String packagePath;
11731        String resourcePath;
11732
11733        /** New install */
11734        AsecInstallArgs(InstallParams params) {
11735            super(params.origin, params.move, params.observer, params.installFlags,
11736                    params.installerPackageName, params.volumeUuid,
11737                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11738                    params.grantedRuntimePermissions,
11739                    params.traceMethod, params.traceCookie);
11740        }
11741
11742        /** Existing install */
11743        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11744                        boolean isExternal, boolean isForwardLocked) {
11745            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11746                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11747                    instructionSets, null, null, null, 0);
11748            // Hackily pretend we're still looking at a full code path
11749            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11750                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11751            }
11752
11753            // Extract cid from fullCodePath
11754            int eidx = fullCodePath.lastIndexOf("/");
11755            String subStr1 = fullCodePath.substring(0, eidx);
11756            int sidx = subStr1.lastIndexOf("/");
11757            cid = subStr1.substring(sidx+1, eidx);
11758            setMountPath(subStr1);
11759        }
11760
11761        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11762            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11763                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11764                    instructionSets, null, null, null, 0);
11765            this.cid = cid;
11766            setMountPath(PackageHelper.getSdDir(cid));
11767        }
11768
11769        void createCopyFile() {
11770            cid = mInstallerService.allocateExternalStageCidLegacy();
11771        }
11772
11773        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11774            if (origin.staged && origin.cid != null) {
11775                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11776                cid = origin.cid;
11777                setMountPath(PackageHelper.getSdDir(cid));
11778                return PackageManager.INSTALL_SUCCEEDED;
11779            }
11780
11781            if (temp) {
11782                createCopyFile();
11783            } else {
11784                /*
11785                 * Pre-emptively destroy the container since it's destroyed if
11786                 * copying fails due to it existing anyway.
11787                 */
11788                PackageHelper.destroySdDir(cid);
11789            }
11790
11791            final String newMountPath = imcs.copyPackageToContainer(
11792                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11793                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11794
11795            if (newMountPath != null) {
11796                setMountPath(newMountPath);
11797                return PackageManager.INSTALL_SUCCEEDED;
11798            } else {
11799                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11800            }
11801        }
11802
11803        @Override
11804        String getCodePath() {
11805            return packagePath;
11806        }
11807
11808        @Override
11809        String getResourcePath() {
11810            return resourcePath;
11811        }
11812
11813        int doPreInstall(int status) {
11814            if (status != PackageManager.INSTALL_SUCCEEDED) {
11815                // Destroy container
11816                PackageHelper.destroySdDir(cid);
11817            } else {
11818                boolean mounted = PackageHelper.isContainerMounted(cid);
11819                if (!mounted) {
11820                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11821                            Process.SYSTEM_UID);
11822                    if (newMountPath != null) {
11823                        setMountPath(newMountPath);
11824                    } else {
11825                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11826                    }
11827                }
11828            }
11829            return status;
11830        }
11831
11832        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11833            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11834            String newMountPath = null;
11835            if (PackageHelper.isContainerMounted(cid)) {
11836                // Unmount the container
11837                if (!PackageHelper.unMountSdDir(cid)) {
11838                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11839                    return false;
11840                }
11841            }
11842            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11843                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11844                        " which might be stale. Will try to clean up.");
11845                // Clean up the stale container and proceed to recreate.
11846                if (!PackageHelper.destroySdDir(newCacheId)) {
11847                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11848                    return false;
11849                }
11850                // Successfully cleaned up stale container. Try to rename again.
11851                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11852                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11853                            + " inspite of cleaning it up.");
11854                    return false;
11855                }
11856            }
11857            if (!PackageHelper.isContainerMounted(newCacheId)) {
11858                Slog.w(TAG, "Mounting container " + newCacheId);
11859                newMountPath = PackageHelper.mountSdDir(newCacheId,
11860                        getEncryptKey(), Process.SYSTEM_UID);
11861            } else {
11862                newMountPath = PackageHelper.getSdDir(newCacheId);
11863            }
11864            if (newMountPath == null) {
11865                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11866                return false;
11867            }
11868            Log.i(TAG, "Succesfully renamed " + cid +
11869                    " to " + newCacheId +
11870                    " at new path: " + newMountPath);
11871            cid = newCacheId;
11872
11873            final File beforeCodeFile = new File(packagePath);
11874            setMountPath(newMountPath);
11875            final File afterCodeFile = new File(packagePath);
11876
11877            // Reflect the rename in scanned details
11878            pkg.codePath = afterCodeFile.getAbsolutePath();
11879            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11880                    pkg.baseCodePath);
11881            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11882                    pkg.splitCodePaths);
11883
11884            // Reflect the rename in app info
11885            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11886            pkg.applicationInfo.setCodePath(pkg.codePath);
11887            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11888            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11889            pkg.applicationInfo.setResourcePath(pkg.codePath);
11890            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11891            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11892
11893            return true;
11894        }
11895
11896        private void setMountPath(String mountPath) {
11897            final File mountFile = new File(mountPath);
11898
11899            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11900            if (monolithicFile.exists()) {
11901                packagePath = monolithicFile.getAbsolutePath();
11902                if (isFwdLocked()) {
11903                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11904                } else {
11905                    resourcePath = packagePath;
11906                }
11907            } else {
11908                packagePath = mountFile.getAbsolutePath();
11909                resourcePath = packagePath;
11910            }
11911        }
11912
11913        int doPostInstall(int status, int uid) {
11914            if (status != PackageManager.INSTALL_SUCCEEDED) {
11915                cleanUp();
11916            } else {
11917                final int groupOwner;
11918                final String protectedFile;
11919                if (isFwdLocked()) {
11920                    groupOwner = UserHandle.getSharedAppGid(uid);
11921                    protectedFile = RES_FILE_NAME;
11922                } else {
11923                    groupOwner = -1;
11924                    protectedFile = null;
11925                }
11926
11927                if (uid < Process.FIRST_APPLICATION_UID
11928                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11929                    Slog.e(TAG, "Failed to finalize " + cid);
11930                    PackageHelper.destroySdDir(cid);
11931                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11932                }
11933
11934                boolean mounted = PackageHelper.isContainerMounted(cid);
11935                if (!mounted) {
11936                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11937                }
11938            }
11939            return status;
11940        }
11941
11942        private void cleanUp() {
11943            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11944
11945            // Destroy secure container
11946            PackageHelper.destroySdDir(cid);
11947        }
11948
11949        private List<String> getAllCodePaths() {
11950            final File codeFile = new File(getCodePath());
11951            if (codeFile != null && codeFile.exists()) {
11952                try {
11953                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11954                    return pkg.getAllCodePaths();
11955                } catch (PackageParserException e) {
11956                    // Ignored; we tried our best
11957                }
11958            }
11959            return Collections.EMPTY_LIST;
11960        }
11961
11962        void cleanUpResourcesLI() {
11963            // Enumerate all code paths before deleting
11964            cleanUpResourcesLI(getAllCodePaths());
11965        }
11966
11967        private void cleanUpResourcesLI(List<String> allCodePaths) {
11968            cleanUp();
11969            removeDexFiles(allCodePaths, instructionSets);
11970        }
11971
11972        String getPackageName() {
11973            return getAsecPackageName(cid);
11974        }
11975
11976        boolean doPostDeleteLI(boolean delete) {
11977            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11978            final List<String> allCodePaths = getAllCodePaths();
11979            boolean mounted = PackageHelper.isContainerMounted(cid);
11980            if (mounted) {
11981                // Unmount first
11982                if (PackageHelper.unMountSdDir(cid)) {
11983                    mounted = false;
11984                }
11985            }
11986            if (!mounted && delete) {
11987                cleanUpResourcesLI(allCodePaths);
11988            }
11989            return !mounted;
11990        }
11991
11992        @Override
11993        int doPreCopy() {
11994            if (isFwdLocked()) {
11995                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
11996                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
11997                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11998                }
11999            }
12000
12001            return PackageManager.INSTALL_SUCCEEDED;
12002        }
12003
12004        @Override
12005        int doPostCopy(int uid) {
12006            if (isFwdLocked()) {
12007                if (uid < Process.FIRST_APPLICATION_UID
12008                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12009                                RES_FILE_NAME)) {
12010                    Slog.e(TAG, "Failed to finalize " + cid);
12011                    PackageHelper.destroySdDir(cid);
12012                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12013                }
12014            }
12015
12016            return PackageManager.INSTALL_SUCCEEDED;
12017        }
12018    }
12019
12020    /**
12021     * Logic to handle movement of existing installed applications.
12022     */
12023    class MoveInstallArgs extends InstallArgs {
12024        private File codeFile;
12025        private File resourceFile;
12026
12027        /** New install */
12028        MoveInstallArgs(InstallParams params) {
12029            super(params.origin, params.move, params.observer, params.installFlags,
12030                    params.installerPackageName, params.volumeUuid,
12031                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12032                    params.grantedRuntimePermissions,
12033                    params.traceMethod, params.traceCookie);
12034        }
12035
12036        int copyApk(IMediaContainerService imcs, boolean temp) {
12037            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12038                    + move.fromUuid + " to " + move.toUuid);
12039            synchronized (mInstaller) {
12040                try {
12041                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12042                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12043                } catch (InstallerException e) {
12044                    Slog.w(TAG, "Failed to move app", e);
12045                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12046                }
12047            }
12048
12049            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12050            resourceFile = codeFile;
12051            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12052
12053            return PackageManager.INSTALL_SUCCEEDED;
12054        }
12055
12056        int doPreInstall(int status) {
12057            if (status != PackageManager.INSTALL_SUCCEEDED) {
12058                cleanUp(move.toUuid);
12059            }
12060            return status;
12061        }
12062
12063        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12064            if (status != PackageManager.INSTALL_SUCCEEDED) {
12065                cleanUp(move.toUuid);
12066                return false;
12067            }
12068
12069            // Reflect the move in app info
12070            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12071            pkg.applicationInfo.setCodePath(pkg.codePath);
12072            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12073            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12074            pkg.applicationInfo.setResourcePath(pkg.codePath);
12075            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12076            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12077
12078            return true;
12079        }
12080
12081        int doPostInstall(int status, int uid) {
12082            if (status == PackageManager.INSTALL_SUCCEEDED) {
12083                cleanUp(move.fromUuid);
12084            } else {
12085                cleanUp(move.toUuid);
12086            }
12087            return status;
12088        }
12089
12090        @Override
12091        String getCodePath() {
12092            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12093        }
12094
12095        @Override
12096        String getResourcePath() {
12097            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12098        }
12099
12100        private boolean cleanUp(String volumeUuid) {
12101            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12102                    move.dataAppName);
12103            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12104            synchronized (mInstallLock) {
12105                // Clean up both app data and code
12106                removeDataDirsLI(volumeUuid, move.packageName);
12107                removeCodePathLI(codeFile);
12108            }
12109            return true;
12110        }
12111
12112        void cleanUpResourcesLI() {
12113            throw new UnsupportedOperationException();
12114        }
12115
12116        boolean doPostDeleteLI(boolean delete) {
12117            throw new UnsupportedOperationException();
12118        }
12119    }
12120
12121    static String getAsecPackageName(String packageCid) {
12122        int idx = packageCid.lastIndexOf("-");
12123        if (idx == -1) {
12124            return packageCid;
12125        }
12126        return packageCid.substring(0, idx);
12127    }
12128
12129    // Utility method used to create code paths based on package name and available index.
12130    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12131        String idxStr = "";
12132        int idx = 1;
12133        // Fall back to default value of idx=1 if prefix is not
12134        // part of oldCodePath
12135        if (oldCodePath != null) {
12136            String subStr = oldCodePath;
12137            // Drop the suffix right away
12138            if (suffix != null && subStr.endsWith(suffix)) {
12139                subStr = subStr.substring(0, subStr.length() - suffix.length());
12140            }
12141            // If oldCodePath already contains prefix find out the
12142            // ending index to either increment or decrement.
12143            int sidx = subStr.lastIndexOf(prefix);
12144            if (sidx != -1) {
12145                subStr = subStr.substring(sidx + prefix.length());
12146                if (subStr != null) {
12147                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12148                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12149                    }
12150                    try {
12151                        idx = Integer.parseInt(subStr);
12152                        if (idx <= 1) {
12153                            idx++;
12154                        } else {
12155                            idx--;
12156                        }
12157                    } catch(NumberFormatException e) {
12158                    }
12159                }
12160            }
12161        }
12162        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12163        return prefix + idxStr;
12164    }
12165
12166    private File getNextCodePath(File targetDir, String packageName) {
12167        int suffix = 1;
12168        File result;
12169        do {
12170            result = new File(targetDir, packageName + "-" + suffix);
12171            suffix++;
12172        } while (result.exists());
12173        return result;
12174    }
12175
12176    // Utility method that returns the relative package path with respect
12177    // to the installation directory. Like say for /data/data/com.test-1.apk
12178    // string com.test-1 is returned.
12179    static String deriveCodePathName(String codePath) {
12180        if (codePath == null) {
12181            return null;
12182        }
12183        final File codeFile = new File(codePath);
12184        final String name = codeFile.getName();
12185        if (codeFile.isDirectory()) {
12186            return name;
12187        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12188            final int lastDot = name.lastIndexOf('.');
12189            return name.substring(0, lastDot);
12190        } else {
12191            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12192            return null;
12193        }
12194    }
12195
12196    static class PackageInstalledInfo {
12197        String name;
12198        int uid;
12199        // The set of users that originally had this package installed.
12200        int[] origUsers;
12201        // The set of users that now have this package installed.
12202        int[] newUsers;
12203        PackageParser.Package pkg;
12204        int returnCode;
12205        String returnMsg;
12206        PackageRemovedInfo removedInfo;
12207
12208        public void setError(int code, String msg) {
12209            returnCode = code;
12210            returnMsg = msg;
12211            Slog.w(TAG, msg);
12212        }
12213
12214        public void setError(String msg, PackageParserException e) {
12215            returnCode = e.error;
12216            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12217            Slog.w(TAG, msg, e);
12218        }
12219
12220        public void setError(String msg, PackageManagerException e) {
12221            returnCode = e.error;
12222            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12223            Slog.w(TAG, msg, e);
12224        }
12225
12226        // In some error cases we want to convey more info back to the observer
12227        String origPackage;
12228        String origPermission;
12229    }
12230
12231    /*
12232     * Install a non-existing package.
12233     */
12234    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12235            UserHandle user, String installerPackageName, String volumeUuid,
12236            PackageInstalledInfo res) {
12237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12238
12239        // Remember this for later, in case we need to rollback this install
12240        String pkgName = pkg.packageName;
12241
12242        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12243        // TODO: b/23350563
12244        final boolean dataDirExists = Environment
12245                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12246
12247        synchronized(mPackages) {
12248            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12249                // A package with the same name is already installed, though
12250                // it has been renamed to an older name.  The package we
12251                // are trying to install should be installed as an update to
12252                // the existing one, but that has not been requested, so bail.
12253                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12254                        + " without first uninstalling package running as "
12255                        + mSettings.mRenamedPackages.get(pkgName));
12256                return;
12257            }
12258            if (mPackages.containsKey(pkgName)) {
12259                // Don't allow installation over an existing package with the same name.
12260                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12261                        + " without first uninstalling.");
12262                return;
12263            }
12264        }
12265
12266        try {
12267            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12268                    System.currentTimeMillis(), user);
12269
12270            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12271            prepareAppDataAfterInstall(newPackage);
12272
12273            // delete the partially installed application. the data directory will have to be
12274            // restored if it was already existing
12275            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12276                // remove package from internal structures.  Note that we want deletePackageX to
12277                // delete the package data and cache directories that it created in
12278                // scanPackageLocked, unless those directories existed before we even tried to
12279                // install.
12280                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12281                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12282                                res.removedInfo, true);
12283            }
12284
12285        } catch (PackageManagerException e) {
12286            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12287        }
12288
12289        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12290    }
12291
12292    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12293        // Can't rotate keys during boot or if sharedUser.
12294        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12295                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12296            return false;
12297        }
12298        // app is using upgradeKeySets; make sure all are valid
12299        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12300        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12301        for (int i = 0; i < upgradeKeySets.length; i++) {
12302            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12303                Slog.wtf(TAG, "Package "
12304                         + (oldPs.name != null ? oldPs.name : "<null>")
12305                         + " contains upgrade-key-set reference to unknown key-set: "
12306                         + upgradeKeySets[i]
12307                         + " reverting to signatures check.");
12308                return false;
12309            }
12310        }
12311        return true;
12312    }
12313
12314    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12315        // Upgrade keysets are being used.  Determine if new package has a superset of the
12316        // required keys.
12317        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12318        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12319        for (int i = 0; i < upgradeKeySets.length; i++) {
12320            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12321            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12322                return true;
12323            }
12324        }
12325        return false;
12326    }
12327
12328    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12329            UserHandle user, String installerPackageName, String volumeUuid,
12330            PackageInstalledInfo res) {
12331        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12332
12333        final PackageParser.Package oldPackage;
12334        final String pkgName = pkg.packageName;
12335        final int[] allUsers;
12336        final boolean[] perUserInstalled;
12337
12338        // First find the old package info and check signatures
12339        synchronized(mPackages) {
12340            oldPackage = mPackages.get(pkgName);
12341            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12342            if (isEphemeral && !oldIsEphemeral) {
12343                // can't downgrade from full to ephemeral
12344                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12345                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12346                return;
12347            }
12348            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12349            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12350            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12351                if(!checkUpgradeKeySetLP(ps, pkg)) {
12352                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12353                            "New package not signed by keys specified by upgrade-keysets: "
12354                            + pkgName);
12355                    return;
12356                }
12357            } else {
12358                // default to original signature matching
12359                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12360                    != PackageManager.SIGNATURE_MATCH) {
12361                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12362                            "New package has a different signature: " + pkgName);
12363                    return;
12364                }
12365            }
12366
12367            // In case of rollback, remember per-user/profile install state
12368            allUsers = sUserManager.getUserIds();
12369            perUserInstalled = new boolean[allUsers.length];
12370            for (int i = 0; i < allUsers.length; i++) {
12371                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12372            }
12373        }
12374
12375        boolean sysPkg = (isSystemApp(oldPackage));
12376        if (sysPkg) {
12377            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12378                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12379        } else {
12380            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12381                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12382        }
12383    }
12384
12385    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12386            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12387            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12388            String volumeUuid, PackageInstalledInfo res) {
12389        String pkgName = deletedPackage.packageName;
12390        boolean deletedPkg = true;
12391        boolean updatedSettings = false;
12392
12393        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12394                + deletedPackage);
12395        long origUpdateTime;
12396        if (pkg.mExtras != null) {
12397            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12398        } else {
12399            origUpdateTime = 0;
12400        }
12401
12402        // First delete the existing package while retaining the data directory
12403        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12404                res.removedInfo, true)) {
12405            // If the existing package wasn't successfully deleted
12406            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12407            deletedPkg = false;
12408        } else {
12409            // Successfully deleted the old package; proceed with replace.
12410
12411            // If deleted package lived in a container, give users a chance to
12412            // relinquish resources before killing.
12413            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12414                if (DEBUG_INSTALL) {
12415                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12416                }
12417                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12418                final ArrayList<String> pkgList = new ArrayList<String>(1);
12419                pkgList.add(deletedPackage.applicationInfo.packageName);
12420                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12421            }
12422
12423            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12424            try {
12425                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12426                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12427                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12428                        perUserInstalled, res, user);
12429                prepareAppDataAfterInstall(newPackage);
12430                updatedSettings = true;
12431            } catch (PackageManagerException e) {
12432                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12433            }
12434        }
12435
12436        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12437            // remove package from internal structures.  Note that we want deletePackageX to
12438            // delete the package data and cache directories that it created in
12439            // scanPackageLocked, unless those directories existed before we even tried to
12440            // install.
12441            if(updatedSettings) {
12442                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12443                deletePackageLI(
12444                        pkgName, null, true, allUsers, perUserInstalled,
12445                        PackageManager.DELETE_KEEP_DATA,
12446                                res.removedInfo, true);
12447            }
12448            // Since we failed to install the new package we need to restore the old
12449            // package that we deleted.
12450            if (deletedPkg) {
12451                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12452                File restoreFile = new File(deletedPackage.codePath);
12453                // Parse old package
12454                boolean oldExternal = isExternal(deletedPackage);
12455                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12456                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12457                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12458                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12459                try {
12460                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12461                            null);
12462                } catch (PackageManagerException e) {
12463                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12464                            + e.getMessage());
12465                    return;
12466                }
12467                // Restore of old package succeeded. Update permissions.
12468                // writer
12469                synchronized (mPackages) {
12470                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12471                            UPDATE_PERMISSIONS_ALL);
12472                    // can downgrade to reader
12473                    mSettings.writeLPr();
12474                }
12475                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12476            }
12477        }
12478    }
12479
12480    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12481            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12482            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12483            String volumeUuid, PackageInstalledInfo res) {
12484        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12485                + ", old=" + deletedPackage);
12486        boolean disabledSystem = false;
12487        boolean updatedSettings = false;
12488        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12489        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12490                != 0) {
12491            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12492        }
12493        String packageName = deletedPackage.packageName;
12494        if (packageName == null) {
12495            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12496                    "Attempt to delete null packageName.");
12497            return;
12498        }
12499        PackageParser.Package oldPkg;
12500        PackageSetting oldPkgSetting;
12501        // reader
12502        synchronized (mPackages) {
12503            oldPkg = mPackages.get(packageName);
12504            oldPkgSetting = mSettings.mPackages.get(packageName);
12505            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12506                    (oldPkgSetting == null)) {
12507                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12508                        "Couldn't find package " + packageName + " information");
12509                return;
12510            }
12511        }
12512
12513        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12514
12515        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12516        res.removedInfo.removedPackage = packageName;
12517        // Remove existing system package
12518        removePackageLI(oldPkgSetting, true);
12519        // writer
12520        synchronized (mPackages) {
12521            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12522            if (!disabledSystem && deletedPackage != null) {
12523                // We didn't need to disable the .apk as a current system package,
12524                // which means we are replacing another update that is already
12525                // installed.  We need to make sure to delete the older one's .apk.
12526                res.removedInfo.args = createInstallArgsForExisting(0,
12527                        deletedPackage.applicationInfo.getCodePath(),
12528                        deletedPackage.applicationInfo.getResourcePath(),
12529                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12530            } else {
12531                res.removedInfo.args = null;
12532            }
12533        }
12534
12535        // Successfully disabled the old package. Now proceed with re-installation
12536        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12537
12538        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12539        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12540
12541        PackageParser.Package newPackage = null;
12542        try {
12543            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12544            if (newPackage.mExtras != null) {
12545                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12546                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12547                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12548
12549                // is the update attempting to change shared user? that isn't going to work...
12550                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12551                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12552                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12553                            + " to " + newPkgSetting.sharedUser);
12554                    updatedSettings = true;
12555                }
12556            }
12557
12558            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12559                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12560                        perUserInstalled, res, user);
12561                prepareAppDataAfterInstall(newPackage);
12562                updatedSettings = true;
12563            }
12564
12565        } catch (PackageManagerException e) {
12566            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12567        }
12568
12569        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12570            // Re installation failed. Restore old information
12571            // Remove new pkg information
12572            if (newPackage != null) {
12573                removeInstalledPackageLI(newPackage, true);
12574            }
12575            // Add back the old system package
12576            try {
12577                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12578            } catch (PackageManagerException e) {
12579                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12580            }
12581            // Restore the old system information in Settings
12582            synchronized (mPackages) {
12583                if (disabledSystem) {
12584                    mSettings.enableSystemPackageLPw(packageName);
12585                }
12586                if (updatedSettings) {
12587                    mSettings.setInstallerPackageName(packageName,
12588                            oldPkgSetting.installerPackageName);
12589                }
12590                mSettings.writeLPr();
12591            }
12592        }
12593    }
12594
12595    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12596        // Collect all used permissions in the UID
12597        ArraySet<String> usedPermissions = new ArraySet<>();
12598        final int packageCount = su.packages.size();
12599        for (int i = 0; i < packageCount; i++) {
12600            PackageSetting ps = su.packages.valueAt(i);
12601            if (ps.pkg == null) {
12602                continue;
12603            }
12604            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12605            for (int j = 0; j < requestedPermCount; j++) {
12606                String permission = ps.pkg.requestedPermissions.get(j);
12607                BasePermission bp = mSettings.mPermissions.get(permission);
12608                if (bp != null) {
12609                    usedPermissions.add(permission);
12610                }
12611            }
12612        }
12613
12614        PermissionsState permissionsState = su.getPermissionsState();
12615        // Prune install permissions
12616        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12617        final int installPermCount = installPermStates.size();
12618        for (int i = installPermCount - 1; i >= 0;  i--) {
12619            PermissionState permissionState = installPermStates.get(i);
12620            if (!usedPermissions.contains(permissionState.getName())) {
12621                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12622                if (bp != null) {
12623                    permissionsState.revokeInstallPermission(bp);
12624                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12625                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12626                }
12627            }
12628        }
12629
12630        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12631
12632        // Prune runtime permissions
12633        for (int userId : allUserIds) {
12634            List<PermissionState> runtimePermStates = permissionsState
12635                    .getRuntimePermissionStates(userId);
12636            final int runtimePermCount = runtimePermStates.size();
12637            for (int i = runtimePermCount - 1; i >= 0; i--) {
12638                PermissionState permissionState = runtimePermStates.get(i);
12639                if (!usedPermissions.contains(permissionState.getName())) {
12640                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12641                    if (bp != null) {
12642                        permissionsState.revokeRuntimePermission(bp, userId);
12643                        permissionsState.updatePermissionFlags(bp, userId,
12644                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12645                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12646                                runtimePermissionChangedUserIds, userId);
12647                    }
12648                }
12649            }
12650        }
12651
12652        return runtimePermissionChangedUserIds;
12653    }
12654
12655    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12656            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12657            UserHandle user) {
12658        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12659
12660        String pkgName = newPackage.packageName;
12661        synchronized (mPackages) {
12662            //write settings. the installStatus will be incomplete at this stage.
12663            //note that the new package setting would have already been
12664            //added to mPackages. It hasn't been persisted yet.
12665            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12666            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12667            mSettings.writeLPr();
12668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12669        }
12670
12671        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12672        synchronized (mPackages) {
12673            updatePermissionsLPw(newPackage.packageName, newPackage,
12674                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12675                            ? UPDATE_PERMISSIONS_ALL : 0));
12676            // For system-bundled packages, we assume that installing an upgraded version
12677            // of the package implies that the user actually wants to run that new code,
12678            // so we enable the package.
12679            PackageSetting ps = mSettings.mPackages.get(pkgName);
12680            if (ps != null) {
12681                if (isSystemApp(newPackage)) {
12682                    // NB: implicit assumption that system package upgrades apply to all users
12683                    if (DEBUG_INSTALL) {
12684                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12685                    }
12686                    if (res.origUsers != null) {
12687                        for (int userHandle : res.origUsers) {
12688                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12689                                    userHandle, installerPackageName);
12690                        }
12691                    }
12692                    // Also convey the prior install/uninstall state
12693                    if (allUsers != null && perUserInstalled != null) {
12694                        for (int i = 0; i < allUsers.length; i++) {
12695                            if (DEBUG_INSTALL) {
12696                                Slog.d(TAG, "    user " + allUsers[i]
12697                                        + " => " + perUserInstalled[i]);
12698                            }
12699                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12700                        }
12701                        // these install state changes will be persisted in the
12702                        // upcoming call to mSettings.writeLPr().
12703                    }
12704                }
12705                // It's implied that when a user requests installation, they want the app to be
12706                // installed and enabled.
12707                int userId = user.getIdentifier();
12708                if (userId != UserHandle.USER_ALL) {
12709                    ps.setInstalled(true, userId);
12710                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12711                }
12712            }
12713            res.name = pkgName;
12714            res.uid = newPackage.applicationInfo.uid;
12715            res.pkg = newPackage;
12716            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12717            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12718            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12719            //to update install status
12720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12721            mSettings.writeLPr();
12722            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12723        }
12724
12725        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12726    }
12727
12728    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12729        try {
12730            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12731            installPackageLI(args, res);
12732        } finally {
12733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12734        }
12735    }
12736
12737    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12738        final int installFlags = args.installFlags;
12739        final String installerPackageName = args.installerPackageName;
12740        final String volumeUuid = args.volumeUuid;
12741        final File tmpPackageFile = new File(args.getCodePath());
12742        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12743        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12744                || (args.volumeUuid != null));
12745        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12746        boolean replace = false;
12747        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12748        if (args.move != null) {
12749            // moving a complete application; perfom an initial scan on the new install location
12750            scanFlags |= SCAN_INITIAL;
12751        }
12752        // Result object to be returned
12753        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12754
12755        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12756
12757        // Sanity check
12758        if (ephemeral && (forwardLocked || onExternal)) {
12759            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12760                    + " external=" + onExternal);
12761            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12762            return;
12763        }
12764
12765        // Retrieve PackageSettings and parse package
12766        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12767                | PackageParser.PARSE_ENFORCE_CODE
12768                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12769                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12770                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12771        PackageParser pp = new PackageParser();
12772        pp.setSeparateProcesses(mSeparateProcesses);
12773        pp.setDisplayMetrics(mMetrics);
12774
12775        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12776        final PackageParser.Package pkg;
12777        try {
12778            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12779        } catch (PackageParserException e) {
12780            res.setError("Failed parse during installPackageLI", e);
12781            return;
12782        } finally {
12783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12784        }
12785
12786        // Mark that we have an install time CPU ABI override.
12787        pkg.cpuAbiOverride = args.abiOverride;
12788
12789        String pkgName = res.name = pkg.packageName;
12790        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12791            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12792                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12793                return;
12794            }
12795        }
12796
12797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12798        try {
12799            pp.collectCertificates(pkg, parseFlags);
12800        } catch (PackageParserException e) {
12801            res.setError("Failed collect during installPackageLI", e);
12802            return;
12803        } finally {
12804            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12805        }
12806
12807        // Get rid of all references to package scan path via parser.
12808        pp = null;
12809        String oldCodePath = null;
12810        boolean systemApp = false;
12811        synchronized (mPackages) {
12812            // Check if installing already existing package
12813            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12814                String oldName = mSettings.mRenamedPackages.get(pkgName);
12815                if (pkg.mOriginalPackages != null
12816                        && pkg.mOriginalPackages.contains(oldName)
12817                        && mPackages.containsKey(oldName)) {
12818                    // This package is derived from an original package,
12819                    // and this device has been updating from that original
12820                    // name.  We must continue using the original name, so
12821                    // rename the new package here.
12822                    pkg.setPackageName(oldName);
12823                    pkgName = pkg.packageName;
12824                    replace = true;
12825                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12826                            + oldName + " pkgName=" + pkgName);
12827                } else if (mPackages.containsKey(pkgName)) {
12828                    // This package, under its official name, already exists
12829                    // on the device; we should replace it.
12830                    replace = true;
12831                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12832                }
12833
12834                // Prevent apps opting out from runtime permissions
12835                if (replace) {
12836                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12837                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12838                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12839                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12840                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12841                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12842                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12843                                        + " doesn't support runtime permissions but the old"
12844                                        + " target SDK " + oldTargetSdk + " does.");
12845                        return;
12846                    }
12847                }
12848            }
12849
12850            PackageSetting ps = mSettings.mPackages.get(pkgName);
12851            if (ps != null) {
12852                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12853
12854                // Quick sanity check that we're signed correctly if updating;
12855                // we'll check this again later when scanning, but we want to
12856                // bail early here before tripping over redefined permissions.
12857                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12858                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12859                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12860                                + pkg.packageName + " upgrade keys do not match the "
12861                                + "previously installed version");
12862                        return;
12863                    }
12864                } else {
12865                    try {
12866                        verifySignaturesLP(ps, pkg);
12867                    } catch (PackageManagerException e) {
12868                        res.setError(e.error, e.getMessage());
12869                        return;
12870                    }
12871                }
12872
12873                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12874                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12875                    systemApp = (ps.pkg.applicationInfo.flags &
12876                            ApplicationInfo.FLAG_SYSTEM) != 0;
12877                }
12878                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12879            }
12880
12881            // Check whether the newly-scanned package wants to define an already-defined perm
12882            int N = pkg.permissions.size();
12883            for (int i = N-1; i >= 0; i--) {
12884                PackageParser.Permission perm = pkg.permissions.get(i);
12885                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12886                if (bp != null) {
12887                    // If the defining package is signed with our cert, it's okay.  This
12888                    // also includes the "updating the same package" case, of course.
12889                    // "updating same package" could also involve key-rotation.
12890                    final boolean sigsOk;
12891                    if (bp.sourcePackage.equals(pkg.packageName)
12892                            && (bp.packageSetting instanceof PackageSetting)
12893                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12894                                    scanFlags))) {
12895                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12896                    } else {
12897                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12898                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12899                    }
12900                    if (!sigsOk) {
12901                        // If the owning package is the system itself, we log but allow
12902                        // install to proceed; we fail the install on all other permission
12903                        // redefinitions.
12904                        if (!bp.sourcePackage.equals("android")) {
12905                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12906                                    + pkg.packageName + " attempting to redeclare permission "
12907                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12908                            res.origPermission = perm.info.name;
12909                            res.origPackage = bp.sourcePackage;
12910                            return;
12911                        } else {
12912                            Slog.w(TAG, "Package " + pkg.packageName
12913                                    + " attempting to redeclare system permission "
12914                                    + perm.info.name + "; ignoring new declaration");
12915                            pkg.permissions.remove(i);
12916                        }
12917                    }
12918                }
12919            }
12920
12921        }
12922
12923        if (systemApp) {
12924            if (onExternal) {
12925                // Abort update; system app can't be replaced with app on sdcard
12926                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12927                        "Cannot install updates to system apps on sdcard");
12928                return;
12929            } else if (ephemeral) {
12930                // Abort update; system app can't be replaced with an ephemeral app
12931                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12932                        "Cannot update a system app with an ephemeral app");
12933                return;
12934            }
12935        }
12936
12937        if (args.move != null) {
12938            // We did an in-place move, so dex is ready to roll
12939            scanFlags |= SCAN_NO_DEX;
12940            scanFlags |= SCAN_MOVE;
12941
12942            synchronized (mPackages) {
12943                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12944                if (ps == null) {
12945                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12946                            "Missing settings for moved package " + pkgName);
12947                }
12948
12949                // We moved the entire application as-is, so bring over the
12950                // previously derived ABI information.
12951                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12952                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12953            }
12954
12955        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12956            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12957            scanFlags |= SCAN_NO_DEX;
12958
12959            try {
12960                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12961                        true /* extract libs */);
12962            } catch (PackageManagerException pme) {
12963                Slog.e(TAG, "Error deriving application ABI", pme);
12964                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12965                return;
12966            }
12967        }
12968
12969        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12970            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12971            return;
12972        }
12973
12974        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12975
12976        if (replace) {
12977            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12978                    installerPackageName, volumeUuid, res);
12979        } else {
12980            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12981                    args.user, installerPackageName, volumeUuid, res);
12982        }
12983        synchronized (mPackages) {
12984            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12985            if (ps != null) {
12986                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12987            }
12988        }
12989    }
12990
12991    private void startIntentFilterVerifications(int userId, boolean replacing,
12992            PackageParser.Package pkg) {
12993        if (mIntentFilterVerifierComponent == null) {
12994            Slog.w(TAG, "No IntentFilter verification will not be done as "
12995                    + "there is no IntentFilterVerifier available!");
12996            return;
12997        }
12998
12999        final int verifierUid = getPackageUid(
13000                mIntentFilterVerifierComponent.getPackageName(),
13001                MATCH_DEBUG_TRIAGED_MISSING,
13002                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13003
13004        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13005        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13006        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13007        mHandler.sendMessage(msg);
13008    }
13009
13010    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13011            PackageParser.Package pkg) {
13012        int size = pkg.activities.size();
13013        if (size == 0) {
13014            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13015                    "No activity, so no need to verify any IntentFilter!");
13016            return;
13017        }
13018
13019        final boolean hasDomainURLs = hasDomainURLs(pkg);
13020        if (!hasDomainURLs) {
13021            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13022                    "No domain URLs, so no need to verify any IntentFilter!");
13023            return;
13024        }
13025
13026        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13027                + " if any IntentFilter from the " + size
13028                + " Activities needs verification ...");
13029
13030        int count = 0;
13031        final String packageName = pkg.packageName;
13032
13033        synchronized (mPackages) {
13034            // If this is a new install and we see that we've already run verification for this
13035            // package, we have nothing to do: it means the state was restored from backup.
13036            if (!replacing) {
13037                IntentFilterVerificationInfo ivi =
13038                        mSettings.getIntentFilterVerificationLPr(packageName);
13039                if (ivi != null) {
13040                    if (DEBUG_DOMAIN_VERIFICATION) {
13041                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13042                                + ivi.getStatusString());
13043                    }
13044                    return;
13045                }
13046            }
13047
13048            // If any filters need to be verified, then all need to be.
13049            boolean needToVerify = false;
13050            for (PackageParser.Activity a : pkg.activities) {
13051                for (ActivityIntentInfo filter : a.intents) {
13052                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13053                        if (DEBUG_DOMAIN_VERIFICATION) {
13054                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13055                        }
13056                        needToVerify = true;
13057                        break;
13058                    }
13059                }
13060            }
13061
13062            if (needToVerify) {
13063                final int verificationId = mIntentFilterVerificationToken++;
13064                for (PackageParser.Activity a : pkg.activities) {
13065                    for (ActivityIntentInfo filter : a.intents) {
13066                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13067                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13068                                    "Verification needed for IntentFilter:" + filter.toString());
13069                            mIntentFilterVerifier.addOneIntentFilterVerification(
13070                                    verifierUid, userId, verificationId, filter, packageName);
13071                            count++;
13072                        }
13073                    }
13074                }
13075            }
13076        }
13077
13078        if (count > 0) {
13079            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13080                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13081                    +  " for userId:" + userId);
13082            mIntentFilterVerifier.startVerifications(userId);
13083        } else {
13084            if (DEBUG_DOMAIN_VERIFICATION) {
13085                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13086            }
13087        }
13088    }
13089
13090    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13091        final ComponentName cn  = filter.activity.getComponentName();
13092        final String packageName = cn.getPackageName();
13093
13094        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13095                packageName);
13096        if (ivi == null) {
13097            return true;
13098        }
13099        int status = ivi.getStatus();
13100        switch (status) {
13101            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13102            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13103                return true;
13104
13105            default:
13106                // Nothing to do
13107                return false;
13108        }
13109    }
13110
13111    private static boolean isMultiArch(ApplicationInfo info) {
13112        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13113    }
13114
13115    private static boolean isExternal(PackageParser.Package pkg) {
13116        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13117    }
13118
13119    private static boolean isExternal(PackageSetting ps) {
13120        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13121    }
13122
13123    private static boolean isEphemeral(PackageParser.Package pkg) {
13124        return pkg.applicationInfo.isEphemeralApp();
13125    }
13126
13127    private static boolean isEphemeral(PackageSetting ps) {
13128        return ps.pkg != null && isEphemeral(ps.pkg);
13129    }
13130
13131    private static boolean isSystemApp(PackageParser.Package pkg) {
13132        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13133    }
13134
13135    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13136        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13137    }
13138
13139    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13140        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13141    }
13142
13143    private static boolean isSystemApp(PackageSetting ps) {
13144        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13145    }
13146
13147    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13148        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13149    }
13150
13151    private int packageFlagsToInstallFlags(PackageSetting ps) {
13152        int installFlags = 0;
13153        if (isEphemeral(ps)) {
13154            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13155        }
13156        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13157            // This existing package was an external ASEC install when we have
13158            // the external flag without a UUID
13159            installFlags |= PackageManager.INSTALL_EXTERNAL;
13160        }
13161        if (ps.isForwardLocked()) {
13162            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13163        }
13164        return installFlags;
13165    }
13166
13167    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13168        if (isExternal(pkg)) {
13169            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13170                return StorageManager.UUID_PRIMARY_PHYSICAL;
13171            } else {
13172                return pkg.volumeUuid;
13173            }
13174        } else {
13175            return StorageManager.UUID_PRIVATE_INTERNAL;
13176        }
13177    }
13178
13179    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13180        if (isExternal(pkg)) {
13181            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13182                return mSettings.getExternalVersion();
13183            } else {
13184                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13185            }
13186        } else {
13187            return mSettings.getInternalVersion();
13188        }
13189    }
13190
13191    private void deleteTempPackageFiles() {
13192        final FilenameFilter filter = new FilenameFilter() {
13193            public boolean accept(File dir, String name) {
13194                return name.startsWith("vmdl") && name.endsWith(".tmp");
13195            }
13196        };
13197        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13198            file.delete();
13199        }
13200    }
13201
13202    @Override
13203    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13204            int flags) {
13205        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13206                flags);
13207    }
13208
13209    @Override
13210    public void deletePackage(final String packageName,
13211            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13212        mContext.enforceCallingOrSelfPermission(
13213                android.Manifest.permission.DELETE_PACKAGES, null);
13214        Preconditions.checkNotNull(packageName);
13215        Preconditions.checkNotNull(observer);
13216        final int uid = Binder.getCallingUid();
13217        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13218        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13219        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13220            mContext.enforceCallingOrSelfPermission(
13221                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13222                    "deletePackage for user " + userId);
13223        }
13224
13225        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13226            try {
13227                observer.onPackageDeleted(packageName,
13228                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13229            } catch (RemoteException re) {
13230            }
13231            return;
13232        }
13233
13234        for (int currentUserId : users) {
13235            if (getBlockUninstallForUser(packageName, currentUserId)) {
13236                try {
13237                    observer.onPackageDeleted(packageName,
13238                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13239                } catch (RemoteException re) {
13240                }
13241                return;
13242            }
13243        }
13244
13245        if (DEBUG_REMOVE) {
13246            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13247        }
13248        // Queue up an async operation since the package deletion may take a little while.
13249        mHandler.post(new Runnable() {
13250            public void run() {
13251                mHandler.removeCallbacks(this);
13252                final int returnCode = deletePackageX(packageName, userId, flags);
13253                try {
13254                    observer.onPackageDeleted(packageName, returnCode, null);
13255                } catch (RemoteException e) {
13256                    Log.i(TAG, "Observer no longer exists.");
13257                } //end catch
13258            } //end run
13259        });
13260    }
13261
13262    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13263        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13264                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13265        try {
13266            if (dpm != null) {
13267                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13268                        /* callingUserOnly =*/ false);
13269                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13270                        : deviceOwnerComponentName.getPackageName();
13271                // Does the package contains the device owner?
13272                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13273                // this check is probably not needed, since DO should be registered as a device
13274                // admin on some user too. (Original bug for this: b/17657954)
13275                if (packageName.equals(deviceOwnerPackageName)) {
13276                    return true;
13277                }
13278                // Does it contain a device admin for any user?
13279                int[] users;
13280                if (userId == UserHandle.USER_ALL) {
13281                    users = sUserManager.getUserIds();
13282                } else {
13283                    users = new int[]{userId};
13284                }
13285                for (int i = 0; i < users.length; ++i) {
13286                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13287                        return true;
13288                    }
13289                }
13290            }
13291        } catch (RemoteException e) {
13292        }
13293        return false;
13294    }
13295
13296    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13297        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13298    }
13299
13300    /**
13301     *  This method is an internal method that could be get invoked either
13302     *  to delete an installed package or to clean up a failed installation.
13303     *  After deleting an installed package, a broadcast is sent to notify any
13304     *  listeners that the package has been installed. For cleaning up a failed
13305     *  installation, the broadcast is not necessary since the package's
13306     *  installation wouldn't have sent the initial broadcast either
13307     *  The key steps in deleting a package are
13308     *  deleting the package information in internal structures like mPackages,
13309     *  deleting the packages base directories through installd
13310     *  updating mSettings to reflect current status
13311     *  persisting settings for later use
13312     *  sending a broadcast if necessary
13313     */
13314    private int deletePackageX(String packageName, int userId, int flags) {
13315        final PackageRemovedInfo info = new PackageRemovedInfo();
13316        final boolean res;
13317
13318        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13319                ? UserHandle.ALL : new UserHandle(userId);
13320
13321        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13322            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13323            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13324        }
13325
13326        boolean removedForAllUsers = false;
13327        boolean systemUpdate = false;
13328
13329        PackageParser.Package uninstalledPkg;
13330
13331        // for the uninstall-updates case and restricted profiles, remember the per-
13332        // userhandle installed state
13333        int[] allUsers;
13334        boolean[] perUserInstalled;
13335        synchronized (mPackages) {
13336            uninstalledPkg = mPackages.get(packageName);
13337            PackageSetting ps = mSettings.mPackages.get(packageName);
13338            allUsers = sUserManager.getUserIds();
13339            perUserInstalled = new boolean[allUsers.length];
13340            for (int i = 0; i < allUsers.length; i++) {
13341                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13342            }
13343        }
13344
13345        synchronized (mInstallLock) {
13346            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13347            res = deletePackageLI(packageName, removeForUser,
13348                    true, allUsers, perUserInstalled,
13349                    flags | REMOVE_CHATTY, info, true);
13350            systemUpdate = info.isRemovedPackageSystemUpdate;
13351            synchronized (mPackages) {
13352                if (res) {
13353                    if (!systemUpdate && mPackages.get(packageName) == null) {
13354                        removedForAllUsers = true;
13355                    }
13356                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13357                }
13358            }
13359            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13360                    + " removedForAllUsers=" + removedForAllUsers);
13361        }
13362
13363        if (res) {
13364            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13365
13366            // If the removed package was a system update, the old system package
13367            // was re-enabled; we need to broadcast this information
13368            if (systemUpdate) {
13369                Bundle extras = new Bundle(1);
13370                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13371                        ? info.removedAppId : info.uid);
13372                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13373
13374                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13375                        extras, 0, null, null, null);
13376                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13377                        extras, 0, null, null, null);
13378                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13379                        null, 0, packageName, null, null);
13380            }
13381        }
13382        // Force a gc here.
13383        Runtime.getRuntime().gc();
13384        // Delete the resources here after sending the broadcast to let
13385        // other processes clean up before deleting resources.
13386        if (info.args != null) {
13387            synchronized (mInstallLock) {
13388                info.args.doPostDeleteLI(true);
13389            }
13390        }
13391
13392        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13393    }
13394
13395    class PackageRemovedInfo {
13396        String removedPackage;
13397        int uid = -1;
13398        int removedAppId = -1;
13399        int[] removedUsers = null;
13400        boolean isRemovedPackageSystemUpdate = false;
13401        // Clean up resources deleted packages.
13402        InstallArgs args = null;
13403
13404        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13405            Bundle extras = new Bundle(1);
13406            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13407            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13408            if (replacing) {
13409                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13410            }
13411            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13412            if (removedPackage != null) {
13413                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13414                        extras, 0, null, null, removedUsers);
13415                if (fullRemove && !replacing) {
13416                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13417                            extras, 0, null, null, removedUsers);
13418                }
13419            }
13420            if (removedAppId >= 0) {
13421                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13422                        removedUsers);
13423            }
13424        }
13425    }
13426
13427    /*
13428     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13429     * flag is not set, the data directory is removed as well.
13430     * make sure this flag is set for partially installed apps. If not its meaningless to
13431     * delete a partially installed application.
13432     */
13433    private void removePackageDataLI(PackageSetting ps,
13434            int[] allUserHandles, boolean[] perUserInstalled,
13435            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13436        String packageName = ps.name;
13437        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13438        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13439        // Retrieve object to delete permissions for shared user later on
13440        final PackageSetting deletedPs;
13441        // reader
13442        synchronized (mPackages) {
13443            deletedPs = mSettings.mPackages.get(packageName);
13444            if (outInfo != null) {
13445                outInfo.removedPackage = packageName;
13446                outInfo.removedUsers = deletedPs != null
13447                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13448                        : null;
13449            }
13450        }
13451        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13452            removeDataDirsLI(ps.volumeUuid, packageName);
13453            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13454        }
13455        // writer
13456        synchronized (mPackages) {
13457            if (deletedPs != null) {
13458                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13459                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13460                    clearDefaultBrowserIfNeeded(packageName);
13461                    if (outInfo != null) {
13462                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13463                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13464                    }
13465                    updatePermissionsLPw(deletedPs.name, null, 0);
13466                    if (deletedPs.sharedUser != null) {
13467                        // Remove permissions associated with package. Since runtime
13468                        // permissions are per user we have to kill the removed package
13469                        // or packages running under the shared user of the removed
13470                        // package if revoking the permissions requested only by the removed
13471                        // package is successful and this causes a change in gids.
13472                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13473                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13474                                    userId);
13475                            if (userIdToKill == UserHandle.USER_ALL
13476                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13477                                // If gids changed for this user, kill all affected packages.
13478                                mHandler.post(new Runnable() {
13479                                    @Override
13480                                    public void run() {
13481                                        // This has to happen with no lock held.
13482                                        killApplication(deletedPs.name, deletedPs.appId,
13483                                                KILL_APP_REASON_GIDS_CHANGED);
13484                                    }
13485                                });
13486                                break;
13487                            }
13488                        }
13489                    }
13490                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13491                }
13492                // make sure to preserve per-user disabled state if this removal was just
13493                // a downgrade of a system app to the factory package
13494                if (allUserHandles != null && perUserInstalled != null) {
13495                    if (DEBUG_REMOVE) {
13496                        Slog.d(TAG, "Propagating install state across downgrade");
13497                    }
13498                    for (int i = 0; i < allUserHandles.length; i++) {
13499                        if (DEBUG_REMOVE) {
13500                            Slog.d(TAG, "    user " + allUserHandles[i]
13501                                    + " => " + perUserInstalled[i]);
13502                        }
13503                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13504                    }
13505                }
13506            }
13507            // can downgrade to reader
13508            if (writeSettings) {
13509                // Save settings now
13510                mSettings.writeLPr();
13511            }
13512        }
13513        if (outInfo != null) {
13514            // A user ID was deleted here. Go through all users and remove it
13515            // from KeyStore.
13516            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13517        }
13518    }
13519
13520    static boolean locationIsPrivileged(File path) {
13521        try {
13522            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13523                    .getCanonicalPath();
13524            return path.getCanonicalPath().startsWith(privilegedAppDir);
13525        } catch (IOException e) {
13526            Slog.e(TAG, "Unable to access code path " + path);
13527        }
13528        return false;
13529    }
13530
13531    /*
13532     * Tries to delete system package.
13533     */
13534    private boolean deleteSystemPackageLI(PackageSetting newPs,
13535            int[] allUserHandles, boolean[] perUserInstalled,
13536            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13537        final boolean applyUserRestrictions
13538                = (allUserHandles != null) && (perUserInstalled != null);
13539        PackageSetting disabledPs = null;
13540        // Confirm if the system package has been updated
13541        // An updated system app can be deleted. This will also have to restore
13542        // the system pkg from system partition
13543        // reader
13544        synchronized (mPackages) {
13545            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13546        }
13547        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13548                + " disabledPs=" + disabledPs);
13549        if (disabledPs == null) {
13550            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13551            return false;
13552        } else if (DEBUG_REMOVE) {
13553            Slog.d(TAG, "Deleting system pkg from data partition");
13554        }
13555        if (DEBUG_REMOVE) {
13556            if (applyUserRestrictions) {
13557                Slog.d(TAG, "Remembering install states:");
13558                for (int i = 0; i < allUserHandles.length; i++) {
13559                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13560                }
13561            }
13562        }
13563        // Delete the updated package
13564        outInfo.isRemovedPackageSystemUpdate = true;
13565        if (disabledPs.versionCode < newPs.versionCode) {
13566            // Delete data for downgrades
13567            flags &= ~PackageManager.DELETE_KEEP_DATA;
13568        } else {
13569            // Preserve data by setting flag
13570            flags |= PackageManager.DELETE_KEEP_DATA;
13571        }
13572        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13573                allUserHandles, perUserInstalled, outInfo, writeSettings);
13574        if (!ret) {
13575            return false;
13576        }
13577        // writer
13578        synchronized (mPackages) {
13579            // Reinstate the old system package
13580            mSettings.enableSystemPackageLPw(newPs.name);
13581            // Remove any native libraries from the upgraded package.
13582            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13583        }
13584        // Install the system package
13585        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13586        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13587        if (locationIsPrivileged(disabledPs.codePath)) {
13588            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13589        }
13590
13591        final PackageParser.Package newPkg;
13592        try {
13593            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13594        } catch (PackageManagerException e) {
13595            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13596            return false;
13597        }
13598
13599        prepareAppDataAfterInstall(newPkg);
13600
13601        // writer
13602        synchronized (mPackages) {
13603            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13604
13605            // Propagate the permissions state as we do not want to drop on the floor
13606            // runtime permissions. The update permissions method below will take
13607            // care of removing obsolete permissions and grant install permissions.
13608            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13609            updatePermissionsLPw(newPkg.packageName, newPkg,
13610                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13611
13612            if (applyUserRestrictions) {
13613                if (DEBUG_REMOVE) {
13614                    Slog.d(TAG, "Propagating install state across reinstall");
13615                }
13616                for (int i = 0; i < allUserHandles.length; i++) {
13617                    if (DEBUG_REMOVE) {
13618                        Slog.d(TAG, "    user " + allUserHandles[i]
13619                                + " => " + perUserInstalled[i]);
13620                    }
13621                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13622
13623                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13624                }
13625                // Regardless of writeSettings we need to ensure that this restriction
13626                // state propagation is persisted
13627                mSettings.writeAllUsersPackageRestrictionsLPr();
13628            }
13629            // can downgrade to reader here
13630            if (writeSettings) {
13631                mSettings.writeLPr();
13632            }
13633        }
13634        return true;
13635    }
13636
13637    private boolean deleteInstalledPackageLI(PackageSetting ps,
13638            boolean deleteCodeAndResources, int flags,
13639            int[] allUserHandles, boolean[] perUserInstalled,
13640            PackageRemovedInfo outInfo, boolean writeSettings) {
13641        if (outInfo != null) {
13642            outInfo.uid = ps.appId;
13643        }
13644
13645        // Delete package data from internal structures and also remove data if flag is set
13646        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13647
13648        // Delete application code and resources
13649        if (deleteCodeAndResources && (outInfo != null)) {
13650            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13651                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13652            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13653        }
13654        return true;
13655    }
13656
13657    @Override
13658    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13659            int userId) {
13660        mContext.enforceCallingOrSelfPermission(
13661                android.Manifest.permission.DELETE_PACKAGES, null);
13662        synchronized (mPackages) {
13663            PackageSetting ps = mSettings.mPackages.get(packageName);
13664            if (ps == null) {
13665                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13666                return false;
13667            }
13668            if (!ps.getInstalled(userId)) {
13669                // Can't block uninstall for an app that is not installed or enabled.
13670                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13671                return false;
13672            }
13673            ps.setBlockUninstall(blockUninstall, userId);
13674            mSettings.writePackageRestrictionsLPr(userId);
13675        }
13676        return true;
13677    }
13678
13679    @Override
13680    public boolean getBlockUninstallForUser(String packageName, int userId) {
13681        synchronized (mPackages) {
13682            PackageSetting ps = mSettings.mPackages.get(packageName);
13683            if (ps == null) {
13684                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13685                return false;
13686            }
13687            return ps.getBlockUninstall(userId);
13688        }
13689    }
13690
13691    @Override
13692    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13693        int callingUid = Binder.getCallingUid();
13694        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13695            throw new SecurityException(
13696                    "setRequiredForSystemUser can only be run by the system or root");
13697        }
13698        synchronized (mPackages) {
13699            PackageSetting ps = mSettings.mPackages.get(packageName);
13700            if (ps == null) {
13701                Log.w(TAG, "Package doesn't exist: " + packageName);
13702                return false;
13703            }
13704            if (systemUserApp) {
13705                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13706            } else {
13707                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13708            }
13709            mSettings.writeLPr();
13710        }
13711        return true;
13712    }
13713
13714    /*
13715     * This method handles package deletion in general
13716     */
13717    private boolean deletePackageLI(String packageName, UserHandle user,
13718            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13719            int flags, PackageRemovedInfo outInfo,
13720            boolean writeSettings) {
13721        if (packageName == null) {
13722            Slog.w(TAG, "Attempt to delete null packageName.");
13723            return false;
13724        }
13725        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13726        PackageSetting ps;
13727        boolean dataOnly = false;
13728        int removeUser = -1;
13729        int appId = -1;
13730        synchronized (mPackages) {
13731            ps = mSettings.mPackages.get(packageName);
13732            if (ps == null) {
13733                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13734                return false;
13735            }
13736            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13737                    && user.getIdentifier() != UserHandle.USER_ALL) {
13738                // The caller is asking that the package only be deleted for a single
13739                // user.  To do this, we just mark its uninstalled state and delete
13740                // its data.  If this is a system app, we only allow this to happen if
13741                // they have set the special DELETE_SYSTEM_APP which requests different
13742                // semantics than normal for uninstalling system apps.
13743                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13744                final int userId = user.getIdentifier();
13745                ps.setUserState(userId,
13746                        COMPONENT_ENABLED_STATE_DEFAULT,
13747                        false, //installed
13748                        true,  //stopped
13749                        true,  //notLaunched
13750                        false, //hidden
13751                        false, //suspended
13752                        null, null, null,
13753                        false, // blockUninstall
13754                        ps.readUserState(userId).domainVerificationStatus, 0);
13755                if (!isSystemApp(ps)) {
13756                    // Do not uninstall the APK if an app should be cached
13757                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13758                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13759                        // Other user still have this package installed, so all
13760                        // we need to do is clear this user's data and save that
13761                        // it is uninstalled.
13762                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13763                        removeUser = user.getIdentifier();
13764                        appId = ps.appId;
13765                        scheduleWritePackageRestrictionsLocked(removeUser);
13766                    } else {
13767                        // We need to set it back to 'installed' so the uninstall
13768                        // broadcasts will be sent correctly.
13769                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13770                        ps.setInstalled(true, user.getIdentifier());
13771                    }
13772                } else {
13773                    // This is a system app, so we assume that the
13774                    // other users still have this package installed, so all
13775                    // we need to do is clear this user's data and save that
13776                    // it is uninstalled.
13777                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13778                    removeUser = user.getIdentifier();
13779                    appId = ps.appId;
13780                    scheduleWritePackageRestrictionsLocked(removeUser);
13781                }
13782            }
13783        }
13784
13785        if (removeUser >= 0) {
13786            // From above, we determined that we are deleting this only
13787            // for a single user.  Continue the work here.
13788            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13789            if (outInfo != null) {
13790                outInfo.removedPackage = packageName;
13791                outInfo.removedAppId = appId;
13792                outInfo.removedUsers = new int[] {removeUser};
13793            }
13794            // TODO: triage flags as part of 26466827
13795            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13796            try {
13797                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13798            } catch (InstallerException e) {
13799                Slog.w(TAG, "Failed to delete app data", e);
13800            }
13801            removeKeystoreDataIfNeeded(removeUser, appId);
13802            schedulePackageCleaning(packageName, removeUser, false);
13803            synchronized (mPackages) {
13804                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13805                    scheduleWritePackageRestrictionsLocked(removeUser);
13806                }
13807                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13808            }
13809            return true;
13810        }
13811
13812        if (dataOnly) {
13813            // Delete application data first
13814            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13815            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13816            return true;
13817        }
13818
13819        boolean ret = false;
13820        if (isSystemApp(ps)) {
13821            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13822            // When an updated system application is deleted we delete the existing resources as well and
13823            // fall back to existing code in system partition
13824            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13825                    flags, outInfo, writeSettings);
13826        } else {
13827            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13828            // Kill application pre-emptively especially for apps on sd.
13829            killApplication(packageName, ps.appId, "uninstall pkg");
13830            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13831                    allUserHandles, perUserInstalled,
13832                    outInfo, writeSettings);
13833        }
13834
13835        return ret;
13836    }
13837
13838    private final static class ClearStorageConnection implements ServiceConnection {
13839        IMediaContainerService mContainerService;
13840
13841        @Override
13842        public void onServiceConnected(ComponentName name, IBinder service) {
13843            synchronized (this) {
13844                mContainerService = IMediaContainerService.Stub.asInterface(service);
13845                notifyAll();
13846            }
13847        }
13848
13849        @Override
13850        public void onServiceDisconnected(ComponentName name) {
13851        }
13852    }
13853
13854    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13855        final boolean mounted;
13856        if (Environment.isExternalStorageEmulated()) {
13857            mounted = true;
13858        } else {
13859            final String status = Environment.getExternalStorageState();
13860
13861            mounted = status.equals(Environment.MEDIA_MOUNTED)
13862                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13863        }
13864
13865        if (!mounted) {
13866            return;
13867        }
13868
13869        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13870        int[] users;
13871        if (userId == UserHandle.USER_ALL) {
13872            users = sUserManager.getUserIds();
13873        } else {
13874            users = new int[] { userId };
13875        }
13876        final ClearStorageConnection conn = new ClearStorageConnection();
13877        if (mContext.bindServiceAsUser(
13878                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13879            try {
13880                for (int curUser : users) {
13881                    long timeout = SystemClock.uptimeMillis() + 5000;
13882                    synchronized (conn) {
13883                        long now = SystemClock.uptimeMillis();
13884                        while (conn.mContainerService == null && now < timeout) {
13885                            try {
13886                                conn.wait(timeout - now);
13887                            } catch (InterruptedException e) {
13888                            }
13889                        }
13890                    }
13891                    if (conn.mContainerService == null) {
13892                        return;
13893                    }
13894
13895                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13896                    clearDirectory(conn.mContainerService,
13897                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13898                    if (allData) {
13899                        clearDirectory(conn.mContainerService,
13900                                userEnv.buildExternalStorageAppDataDirs(packageName));
13901                        clearDirectory(conn.mContainerService,
13902                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13903                    }
13904                }
13905            } finally {
13906                mContext.unbindService(conn);
13907            }
13908        }
13909    }
13910
13911    @Override
13912    public void clearApplicationUserData(final String packageName,
13913            final IPackageDataObserver observer, final int userId) {
13914        mContext.enforceCallingOrSelfPermission(
13915                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13916        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13917        // Queue up an async operation since the package deletion may take a little while.
13918        mHandler.post(new Runnable() {
13919            public void run() {
13920                mHandler.removeCallbacks(this);
13921                final boolean succeeded;
13922                synchronized (mInstallLock) {
13923                    succeeded = clearApplicationUserDataLI(packageName, userId);
13924                }
13925                clearExternalStorageDataSync(packageName, userId, true);
13926                if (succeeded) {
13927                    // invoke DeviceStorageMonitor's update method to clear any notifications
13928                    DeviceStorageMonitorInternal
13929                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13930                    if (dsm != null) {
13931                        dsm.checkMemory();
13932                    }
13933                }
13934                if(observer != null) {
13935                    try {
13936                        observer.onRemoveCompleted(packageName, succeeded);
13937                    } catch (RemoteException e) {
13938                        Log.i(TAG, "Observer no longer exists.");
13939                    }
13940                } //end if observer
13941            } //end run
13942        });
13943    }
13944
13945    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13946        if (packageName == null) {
13947            Slog.w(TAG, "Attempt to delete null packageName.");
13948            return false;
13949        }
13950
13951        // Try finding details about the requested package
13952        PackageParser.Package pkg;
13953        synchronized (mPackages) {
13954            pkg = mPackages.get(packageName);
13955            if (pkg == null) {
13956                final PackageSetting ps = mSettings.mPackages.get(packageName);
13957                if (ps != null) {
13958                    pkg = ps.pkg;
13959                }
13960            }
13961
13962            if (pkg == null) {
13963                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13964                return false;
13965            }
13966
13967            PackageSetting ps = (PackageSetting) pkg.mExtras;
13968            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13969        }
13970
13971        // Always delete data directories for package, even if we found no other
13972        // record of app. This helps users recover from UID mismatches without
13973        // resorting to a full data wipe.
13974        // TODO: triage flags as part of 26466827
13975        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13976        try {
13977            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
13978        } catch (InstallerException e) {
13979            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
13980            return false;
13981        }
13982
13983        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
13984        removeKeystoreDataIfNeeded(userId, appId);
13985
13986        // Create a native library symlink only if we have native libraries
13987        // and if the native libraries are 32 bit libraries. We do not provide
13988        // this symlink for 64 bit libraries.
13989        if (pkg.applicationInfo.primaryCpuAbi != null &&
13990                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13991            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13992            try {
13993                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13994                        nativeLibPath, userId);
13995            } catch (InstallerException e) {
13996                Slog.w(TAG, "Failed linking native library dir", e);
13997                return false;
13998            }
13999        }
14000
14001        return true;
14002    }
14003
14004    /**
14005     * Reverts user permission state changes (permissions and flags) in
14006     * all packages for a given user.
14007     *
14008     * @param userId The device user for which to do a reset.
14009     */
14010    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14011        final int packageCount = mPackages.size();
14012        for (int i = 0; i < packageCount; i++) {
14013            PackageParser.Package pkg = mPackages.valueAt(i);
14014            PackageSetting ps = (PackageSetting) pkg.mExtras;
14015            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14016        }
14017    }
14018
14019    /**
14020     * Reverts user permission state changes (permissions and flags).
14021     *
14022     * @param ps The package for which to reset.
14023     * @param userId The device user for which to do a reset.
14024     */
14025    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14026            final PackageSetting ps, final int userId) {
14027        if (ps.pkg == null) {
14028            return;
14029        }
14030
14031        // These are flags that can change base on user actions.
14032        final int userSettableMask = FLAG_PERMISSION_USER_SET
14033                | FLAG_PERMISSION_USER_FIXED
14034                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14035                | FLAG_PERMISSION_REVIEW_REQUIRED;
14036
14037        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14038                | FLAG_PERMISSION_POLICY_FIXED;
14039
14040        boolean writeInstallPermissions = false;
14041        boolean writeRuntimePermissions = false;
14042
14043        final int permissionCount = ps.pkg.requestedPermissions.size();
14044        for (int i = 0; i < permissionCount; i++) {
14045            String permission = ps.pkg.requestedPermissions.get(i);
14046
14047            BasePermission bp = mSettings.mPermissions.get(permission);
14048            if (bp == null) {
14049                continue;
14050            }
14051
14052            // If shared user we just reset the state to which only this app contributed.
14053            if (ps.sharedUser != null) {
14054                boolean used = false;
14055                final int packageCount = ps.sharedUser.packages.size();
14056                for (int j = 0; j < packageCount; j++) {
14057                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14058                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14059                            && pkg.pkg.requestedPermissions.contains(permission)) {
14060                        used = true;
14061                        break;
14062                    }
14063                }
14064                if (used) {
14065                    continue;
14066                }
14067            }
14068
14069            PermissionsState permissionsState = ps.getPermissionsState();
14070
14071            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14072
14073            // Always clear the user settable flags.
14074            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14075                    bp.name) != null;
14076            // If permission review is enabled and this is a legacy app, mark the
14077            // permission as requiring a review as this is the initial state.
14078            int flags = 0;
14079            if (Build.PERMISSIONS_REVIEW_REQUIRED
14080                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14081                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14082            }
14083            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14084                if (hasInstallState) {
14085                    writeInstallPermissions = true;
14086                } else {
14087                    writeRuntimePermissions = true;
14088                }
14089            }
14090
14091            // Below is only runtime permission handling.
14092            if (!bp.isRuntime()) {
14093                continue;
14094            }
14095
14096            // Never clobber system or policy.
14097            if ((oldFlags & policyOrSystemFlags) != 0) {
14098                continue;
14099            }
14100
14101            // If this permission was granted by default, make sure it is.
14102            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14103                if (permissionsState.grantRuntimePermission(bp, userId)
14104                        != PERMISSION_OPERATION_FAILURE) {
14105                    writeRuntimePermissions = true;
14106                }
14107            // If permission review is enabled the permissions for a legacy apps
14108            // are represented as constantly granted runtime ones, so don't revoke.
14109            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14110                // Otherwise, reset the permission.
14111                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14112                switch (revokeResult) {
14113                    case PERMISSION_OPERATION_SUCCESS: {
14114                        writeRuntimePermissions = true;
14115                    } break;
14116
14117                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14118                        writeRuntimePermissions = true;
14119                        final int appId = ps.appId;
14120                        mHandler.post(new Runnable() {
14121                            @Override
14122                            public void run() {
14123                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14124                            }
14125                        });
14126                    } break;
14127                }
14128            }
14129        }
14130
14131        // Synchronously write as we are taking permissions away.
14132        if (writeRuntimePermissions) {
14133            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14134        }
14135
14136        // Synchronously write as we are taking permissions away.
14137        if (writeInstallPermissions) {
14138            mSettings.writeLPr();
14139        }
14140    }
14141
14142    /**
14143     * Remove entries from the keystore daemon. Will only remove it if the
14144     * {@code appId} is valid.
14145     */
14146    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14147        if (appId < 0) {
14148            return;
14149        }
14150
14151        final KeyStore keyStore = KeyStore.getInstance();
14152        if (keyStore != null) {
14153            if (userId == UserHandle.USER_ALL) {
14154                for (final int individual : sUserManager.getUserIds()) {
14155                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14156                }
14157            } else {
14158                keyStore.clearUid(UserHandle.getUid(userId, appId));
14159            }
14160        } else {
14161            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14162        }
14163    }
14164
14165    @Override
14166    public void deleteApplicationCacheFiles(final String packageName,
14167            final IPackageDataObserver observer) {
14168        mContext.enforceCallingOrSelfPermission(
14169                android.Manifest.permission.DELETE_CACHE_FILES, null);
14170        // Queue up an async operation since the package deletion may take a little while.
14171        final int userId = UserHandle.getCallingUserId();
14172        mHandler.post(new Runnable() {
14173            public void run() {
14174                mHandler.removeCallbacks(this);
14175                final boolean succeded;
14176                synchronized (mInstallLock) {
14177                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14178                }
14179                clearExternalStorageDataSync(packageName, userId, false);
14180                if (observer != null) {
14181                    try {
14182                        observer.onRemoveCompleted(packageName, succeded);
14183                    } catch (RemoteException e) {
14184                        Log.i(TAG, "Observer no longer exists.");
14185                    }
14186                } //end if observer
14187            } //end run
14188        });
14189    }
14190
14191    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14192        if (packageName == null) {
14193            Slog.w(TAG, "Attempt to delete null packageName.");
14194            return false;
14195        }
14196        PackageParser.Package p;
14197        synchronized (mPackages) {
14198            p = mPackages.get(packageName);
14199        }
14200        if (p == null) {
14201            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14202            return false;
14203        }
14204        final ApplicationInfo applicationInfo = p.applicationInfo;
14205        if (applicationInfo == null) {
14206            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14207            return false;
14208        }
14209        // TODO: triage flags as part of 26466827
14210        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14211        try {
14212            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14213                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14214        } catch (InstallerException e) {
14215            Slog.w(TAG, "Couldn't remove cache files for package "
14216                    + packageName + " u" + userId, e);
14217            return false;
14218        }
14219        return true;
14220    }
14221
14222    @Override
14223    public void getPackageSizeInfo(final String packageName, int userHandle,
14224            final IPackageStatsObserver observer) {
14225        mContext.enforceCallingOrSelfPermission(
14226                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14227        if (packageName == null) {
14228            throw new IllegalArgumentException("Attempt to get size of null packageName");
14229        }
14230
14231        PackageStats stats = new PackageStats(packageName, userHandle);
14232
14233        /*
14234         * Queue up an async operation since the package measurement may take a
14235         * little while.
14236         */
14237        Message msg = mHandler.obtainMessage(INIT_COPY);
14238        msg.obj = new MeasureParams(stats, observer);
14239        mHandler.sendMessage(msg);
14240    }
14241
14242    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14243            PackageStats pStats) {
14244        if (packageName == null) {
14245            Slog.w(TAG, "Attempt to get size of null packageName.");
14246            return false;
14247        }
14248        PackageParser.Package p;
14249        boolean dataOnly = false;
14250        String libDirRoot = null;
14251        String asecPath = null;
14252        PackageSetting ps = null;
14253        synchronized (mPackages) {
14254            p = mPackages.get(packageName);
14255            ps = mSettings.mPackages.get(packageName);
14256            if(p == null) {
14257                dataOnly = true;
14258                if((ps == null) || (ps.pkg == null)) {
14259                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14260                    return false;
14261                }
14262                p = ps.pkg;
14263            }
14264            if (ps != null) {
14265                libDirRoot = ps.legacyNativeLibraryPathString;
14266            }
14267            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14268                final long token = Binder.clearCallingIdentity();
14269                try {
14270                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14271                    if (secureContainerId != null) {
14272                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14273                    }
14274                } finally {
14275                    Binder.restoreCallingIdentity(token);
14276                }
14277            }
14278        }
14279        String publicSrcDir = null;
14280        if(!dataOnly) {
14281            final ApplicationInfo applicationInfo = p.applicationInfo;
14282            if (applicationInfo == null) {
14283                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14284                return false;
14285            }
14286            if (p.isForwardLocked()) {
14287                publicSrcDir = applicationInfo.getBaseResourcePath();
14288            }
14289        }
14290        // TODO: extend to measure size of split APKs
14291        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14292        // not just the first level.
14293        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14294        // just the primary.
14295        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14296
14297        String apkPath;
14298        File packageDir = new File(p.codePath);
14299
14300        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14301            apkPath = packageDir.getAbsolutePath();
14302            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14303            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14304                libDirRoot = null;
14305            }
14306        } else {
14307            apkPath = p.baseCodePath;
14308        }
14309
14310        // TODO: triage flags as part of 26466827
14311        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14312        try {
14313            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14314                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14315        } catch (InstallerException e) {
14316            return false;
14317        }
14318
14319        // Fix-up for forward-locked applications in ASEC containers.
14320        if (!isExternal(p)) {
14321            pStats.codeSize += pStats.externalCodeSize;
14322            pStats.externalCodeSize = 0L;
14323        }
14324
14325        return true;
14326    }
14327
14328
14329    @Override
14330    public void addPackageToPreferred(String packageName) {
14331        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14332    }
14333
14334    @Override
14335    public void removePackageFromPreferred(String packageName) {
14336        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14337    }
14338
14339    @Override
14340    public List<PackageInfo> getPreferredPackages(int flags) {
14341        return new ArrayList<PackageInfo>();
14342    }
14343
14344    private int getUidTargetSdkVersionLockedLPr(int uid) {
14345        Object obj = mSettings.getUserIdLPr(uid);
14346        if (obj instanceof SharedUserSetting) {
14347            final SharedUserSetting sus = (SharedUserSetting) obj;
14348            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14349            final Iterator<PackageSetting> it = sus.packages.iterator();
14350            while (it.hasNext()) {
14351                final PackageSetting ps = it.next();
14352                if (ps.pkg != null) {
14353                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14354                    if (v < vers) vers = v;
14355                }
14356            }
14357            return vers;
14358        } else if (obj instanceof PackageSetting) {
14359            final PackageSetting ps = (PackageSetting) obj;
14360            if (ps.pkg != null) {
14361                return ps.pkg.applicationInfo.targetSdkVersion;
14362            }
14363        }
14364        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14365    }
14366
14367    @Override
14368    public void addPreferredActivity(IntentFilter filter, int match,
14369            ComponentName[] set, ComponentName activity, int userId) {
14370        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14371                "Adding preferred");
14372    }
14373
14374    private void addPreferredActivityInternal(IntentFilter filter, int match,
14375            ComponentName[] set, ComponentName activity, boolean always, int userId,
14376            String opname) {
14377        // writer
14378        int callingUid = Binder.getCallingUid();
14379        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14380        if (filter.countActions() == 0) {
14381            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14382            return;
14383        }
14384        synchronized (mPackages) {
14385            if (mContext.checkCallingOrSelfPermission(
14386                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14387                    != PackageManager.PERMISSION_GRANTED) {
14388                if (getUidTargetSdkVersionLockedLPr(callingUid)
14389                        < Build.VERSION_CODES.FROYO) {
14390                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14391                            + callingUid);
14392                    return;
14393                }
14394                mContext.enforceCallingOrSelfPermission(
14395                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14396            }
14397
14398            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14399            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14400                    + userId + ":");
14401            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14402            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14403            scheduleWritePackageRestrictionsLocked(userId);
14404        }
14405    }
14406
14407    @Override
14408    public void replacePreferredActivity(IntentFilter filter, int match,
14409            ComponentName[] set, ComponentName activity, int userId) {
14410        if (filter.countActions() != 1) {
14411            throw new IllegalArgumentException(
14412                    "replacePreferredActivity expects filter to have only 1 action.");
14413        }
14414        if (filter.countDataAuthorities() != 0
14415                || filter.countDataPaths() != 0
14416                || filter.countDataSchemes() > 1
14417                || filter.countDataTypes() != 0) {
14418            throw new IllegalArgumentException(
14419                    "replacePreferredActivity expects filter to have no data authorities, " +
14420                    "paths, or types; and at most one scheme.");
14421        }
14422
14423        final int callingUid = Binder.getCallingUid();
14424        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14425        synchronized (mPackages) {
14426            if (mContext.checkCallingOrSelfPermission(
14427                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14428                    != PackageManager.PERMISSION_GRANTED) {
14429                if (getUidTargetSdkVersionLockedLPr(callingUid)
14430                        < Build.VERSION_CODES.FROYO) {
14431                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14432                            + Binder.getCallingUid());
14433                    return;
14434                }
14435                mContext.enforceCallingOrSelfPermission(
14436                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14437            }
14438
14439            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14440            if (pir != null) {
14441                // Get all of the existing entries that exactly match this filter.
14442                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14443                if (existing != null && existing.size() == 1) {
14444                    PreferredActivity cur = existing.get(0);
14445                    if (DEBUG_PREFERRED) {
14446                        Slog.i(TAG, "Checking replace of preferred:");
14447                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14448                        if (!cur.mPref.mAlways) {
14449                            Slog.i(TAG, "  -- CUR; not mAlways!");
14450                        } else {
14451                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14452                            Slog.i(TAG, "  -- CUR: mSet="
14453                                    + Arrays.toString(cur.mPref.mSetComponents));
14454                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14455                            Slog.i(TAG, "  -- NEW: mMatch="
14456                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14457                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14458                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14459                        }
14460                    }
14461                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14462                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14463                            && cur.mPref.sameSet(set)) {
14464                        // Setting the preferred activity to what it happens to be already
14465                        if (DEBUG_PREFERRED) {
14466                            Slog.i(TAG, "Replacing with same preferred activity "
14467                                    + cur.mPref.mShortComponent + " for user "
14468                                    + userId + ":");
14469                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14470                        }
14471                        return;
14472                    }
14473                }
14474
14475                if (existing != null) {
14476                    if (DEBUG_PREFERRED) {
14477                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14478                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14479                    }
14480                    for (int i = 0; i < existing.size(); i++) {
14481                        PreferredActivity pa = existing.get(i);
14482                        if (DEBUG_PREFERRED) {
14483                            Slog.i(TAG, "Removing existing preferred activity "
14484                                    + pa.mPref.mComponent + ":");
14485                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14486                        }
14487                        pir.removeFilter(pa);
14488                    }
14489                }
14490            }
14491            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14492                    "Replacing preferred");
14493        }
14494    }
14495
14496    @Override
14497    public void clearPackagePreferredActivities(String packageName) {
14498        final int uid = Binder.getCallingUid();
14499        // writer
14500        synchronized (mPackages) {
14501            PackageParser.Package pkg = mPackages.get(packageName);
14502            if (pkg == null || pkg.applicationInfo.uid != uid) {
14503                if (mContext.checkCallingOrSelfPermission(
14504                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14505                        != PackageManager.PERMISSION_GRANTED) {
14506                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14507                            < Build.VERSION_CODES.FROYO) {
14508                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14509                                + Binder.getCallingUid());
14510                        return;
14511                    }
14512                    mContext.enforceCallingOrSelfPermission(
14513                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14514                }
14515            }
14516
14517            int user = UserHandle.getCallingUserId();
14518            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14519                scheduleWritePackageRestrictionsLocked(user);
14520            }
14521        }
14522    }
14523
14524    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14525    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14526        ArrayList<PreferredActivity> removed = null;
14527        boolean changed = false;
14528        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14529            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14530            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14531            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14532                continue;
14533            }
14534            Iterator<PreferredActivity> it = pir.filterIterator();
14535            while (it.hasNext()) {
14536                PreferredActivity pa = it.next();
14537                // Mark entry for removal only if it matches the package name
14538                // and the entry is of type "always".
14539                if (packageName == null ||
14540                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14541                                && pa.mPref.mAlways)) {
14542                    if (removed == null) {
14543                        removed = new ArrayList<PreferredActivity>();
14544                    }
14545                    removed.add(pa);
14546                }
14547            }
14548            if (removed != null) {
14549                for (int j=0; j<removed.size(); j++) {
14550                    PreferredActivity pa = removed.get(j);
14551                    pir.removeFilter(pa);
14552                }
14553                changed = true;
14554            }
14555        }
14556        return changed;
14557    }
14558
14559    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14560    private void clearIntentFilterVerificationsLPw(int userId) {
14561        final int packageCount = mPackages.size();
14562        for (int i = 0; i < packageCount; i++) {
14563            PackageParser.Package pkg = mPackages.valueAt(i);
14564            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14565        }
14566    }
14567
14568    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14569    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14570        if (userId == UserHandle.USER_ALL) {
14571            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14572                    sUserManager.getUserIds())) {
14573                for (int oneUserId : sUserManager.getUserIds()) {
14574                    scheduleWritePackageRestrictionsLocked(oneUserId);
14575                }
14576            }
14577        } else {
14578            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14579                scheduleWritePackageRestrictionsLocked(userId);
14580            }
14581        }
14582    }
14583
14584    void clearDefaultBrowserIfNeeded(String packageName) {
14585        for (int oneUserId : sUserManager.getUserIds()) {
14586            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14587            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14588            if (packageName.equals(defaultBrowserPackageName)) {
14589                setDefaultBrowserPackageName(null, oneUserId);
14590            }
14591        }
14592    }
14593
14594    @Override
14595    public void resetApplicationPreferences(int userId) {
14596        mContext.enforceCallingOrSelfPermission(
14597                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14598        // writer
14599        synchronized (mPackages) {
14600            final long identity = Binder.clearCallingIdentity();
14601            try {
14602                clearPackagePreferredActivitiesLPw(null, userId);
14603                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14604                // TODO: We have to reset the default SMS and Phone. This requires
14605                // significant refactoring to keep all default apps in the package
14606                // manager (cleaner but more work) or have the services provide
14607                // callbacks to the package manager to request a default app reset.
14608                applyFactoryDefaultBrowserLPw(userId);
14609                clearIntentFilterVerificationsLPw(userId);
14610                primeDomainVerificationsLPw(userId);
14611                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14612                scheduleWritePackageRestrictionsLocked(userId);
14613            } finally {
14614                Binder.restoreCallingIdentity(identity);
14615            }
14616        }
14617    }
14618
14619    @Override
14620    public int getPreferredActivities(List<IntentFilter> outFilters,
14621            List<ComponentName> outActivities, String packageName) {
14622
14623        int num = 0;
14624        final int userId = UserHandle.getCallingUserId();
14625        // reader
14626        synchronized (mPackages) {
14627            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14628            if (pir != null) {
14629                final Iterator<PreferredActivity> it = pir.filterIterator();
14630                while (it.hasNext()) {
14631                    final PreferredActivity pa = it.next();
14632                    if (packageName == null
14633                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14634                                    && pa.mPref.mAlways)) {
14635                        if (outFilters != null) {
14636                            outFilters.add(new IntentFilter(pa));
14637                        }
14638                        if (outActivities != null) {
14639                            outActivities.add(pa.mPref.mComponent);
14640                        }
14641                    }
14642                }
14643            }
14644        }
14645
14646        return num;
14647    }
14648
14649    @Override
14650    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14651            int userId) {
14652        int callingUid = Binder.getCallingUid();
14653        if (callingUid != Process.SYSTEM_UID) {
14654            throw new SecurityException(
14655                    "addPersistentPreferredActivity can only be run by the system");
14656        }
14657        if (filter.countActions() == 0) {
14658            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14659            return;
14660        }
14661        synchronized (mPackages) {
14662            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14663                    ":");
14664            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14665            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14666                    new PersistentPreferredActivity(filter, activity));
14667            scheduleWritePackageRestrictionsLocked(userId);
14668        }
14669    }
14670
14671    @Override
14672    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14673        int callingUid = Binder.getCallingUid();
14674        if (callingUid != Process.SYSTEM_UID) {
14675            throw new SecurityException(
14676                    "clearPackagePersistentPreferredActivities can only be run by the system");
14677        }
14678        ArrayList<PersistentPreferredActivity> removed = null;
14679        boolean changed = false;
14680        synchronized (mPackages) {
14681            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14682                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14683                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14684                        .valueAt(i);
14685                if (userId != thisUserId) {
14686                    continue;
14687                }
14688                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14689                while (it.hasNext()) {
14690                    PersistentPreferredActivity ppa = it.next();
14691                    // Mark entry for removal only if it matches the package name.
14692                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14693                        if (removed == null) {
14694                            removed = new ArrayList<PersistentPreferredActivity>();
14695                        }
14696                        removed.add(ppa);
14697                    }
14698                }
14699                if (removed != null) {
14700                    for (int j=0; j<removed.size(); j++) {
14701                        PersistentPreferredActivity ppa = removed.get(j);
14702                        ppir.removeFilter(ppa);
14703                    }
14704                    changed = true;
14705                }
14706            }
14707
14708            if (changed) {
14709                scheduleWritePackageRestrictionsLocked(userId);
14710            }
14711        }
14712    }
14713
14714    /**
14715     * Common machinery for picking apart a restored XML blob and passing
14716     * it to a caller-supplied functor to be applied to the running system.
14717     */
14718    private void restoreFromXml(XmlPullParser parser, int userId,
14719            String expectedStartTag, BlobXmlRestorer functor)
14720            throws IOException, XmlPullParserException {
14721        int type;
14722        while ((type = parser.next()) != XmlPullParser.START_TAG
14723                && type != XmlPullParser.END_DOCUMENT) {
14724        }
14725        if (type != XmlPullParser.START_TAG) {
14726            // oops didn't find a start tag?!
14727            if (DEBUG_BACKUP) {
14728                Slog.e(TAG, "Didn't find start tag during restore");
14729            }
14730            return;
14731        }
14732Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14733        // this is supposed to be TAG_PREFERRED_BACKUP
14734        if (!expectedStartTag.equals(parser.getName())) {
14735            if (DEBUG_BACKUP) {
14736                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14737            }
14738            return;
14739        }
14740
14741        // skip interfering stuff, then we're aligned with the backing implementation
14742        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14743Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14744        functor.apply(parser, userId);
14745    }
14746
14747    private interface BlobXmlRestorer {
14748        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14749    }
14750
14751    /**
14752     * Non-Binder method, support for the backup/restore mechanism: write the
14753     * full set of preferred activities in its canonical XML format.  Returns the
14754     * XML output as a byte array, or null if there is none.
14755     */
14756    @Override
14757    public byte[] getPreferredActivityBackup(int userId) {
14758        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14759            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14760        }
14761
14762        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14763        try {
14764            final XmlSerializer serializer = new FastXmlSerializer();
14765            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14766            serializer.startDocument(null, true);
14767            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14768
14769            synchronized (mPackages) {
14770                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14771            }
14772
14773            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14774            serializer.endDocument();
14775            serializer.flush();
14776        } catch (Exception e) {
14777            if (DEBUG_BACKUP) {
14778                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14779            }
14780            return null;
14781        }
14782
14783        return dataStream.toByteArray();
14784    }
14785
14786    @Override
14787    public void restorePreferredActivities(byte[] backup, int userId) {
14788        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14789            throw new SecurityException("Only the system may call restorePreferredActivities()");
14790        }
14791
14792        try {
14793            final XmlPullParser parser = Xml.newPullParser();
14794            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14795            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14796                    new BlobXmlRestorer() {
14797                        @Override
14798                        public void apply(XmlPullParser parser, int userId)
14799                                throws XmlPullParserException, IOException {
14800                            synchronized (mPackages) {
14801                                mSettings.readPreferredActivitiesLPw(parser, userId);
14802                            }
14803                        }
14804                    } );
14805        } catch (Exception e) {
14806            if (DEBUG_BACKUP) {
14807                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14808            }
14809        }
14810    }
14811
14812    /**
14813     * Non-Binder method, support for the backup/restore mechanism: write the
14814     * default browser (etc) settings in its canonical XML format.  Returns the default
14815     * browser XML representation as a byte array, or null if there is none.
14816     */
14817    @Override
14818    public byte[] getDefaultAppsBackup(int userId) {
14819        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14820            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14821        }
14822
14823        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14824        try {
14825            final XmlSerializer serializer = new FastXmlSerializer();
14826            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14827            serializer.startDocument(null, true);
14828            serializer.startTag(null, TAG_DEFAULT_APPS);
14829
14830            synchronized (mPackages) {
14831                mSettings.writeDefaultAppsLPr(serializer, userId);
14832            }
14833
14834            serializer.endTag(null, TAG_DEFAULT_APPS);
14835            serializer.endDocument();
14836            serializer.flush();
14837        } catch (Exception e) {
14838            if (DEBUG_BACKUP) {
14839                Slog.e(TAG, "Unable to write default apps for backup", e);
14840            }
14841            return null;
14842        }
14843
14844        return dataStream.toByteArray();
14845    }
14846
14847    @Override
14848    public void restoreDefaultApps(byte[] backup, int userId) {
14849        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14850            throw new SecurityException("Only the system may call restoreDefaultApps()");
14851        }
14852
14853        try {
14854            final XmlPullParser parser = Xml.newPullParser();
14855            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14856            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14857                    new BlobXmlRestorer() {
14858                        @Override
14859                        public void apply(XmlPullParser parser, int userId)
14860                                throws XmlPullParserException, IOException {
14861                            synchronized (mPackages) {
14862                                mSettings.readDefaultAppsLPw(parser, userId);
14863                            }
14864                        }
14865                    } );
14866        } catch (Exception e) {
14867            if (DEBUG_BACKUP) {
14868                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14869            }
14870        }
14871    }
14872
14873    @Override
14874    public byte[] getIntentFilterVerificationBackup(int userId) {
14875        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14876            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14877        }
14878
14879        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14880        try {
14881            final XmlSerializer serializer = new FastXmlSerializer();
14882            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14883            serializer.startDocument(null, true);
14884            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14885
14886            synchronized (mPackages) {
14887                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14888            }
14889
14890            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14891            serializer.endDocument();
14892            serializer.flush();
14893        } catch (Exception e) {
14894            if (DEBUG_BACKUP) {
14895                Slog.e(TAG, "Unable to write default apps for backup", e);
14896            }
14897            return null;
14898        }
14899
14900        return dataStream.toByteArray();
14901    }
14902
14903    @Override
14904    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14905        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14906            throw new SecurityException("Only the system may call restorePreferredActivities()");
14907        }
14908
14909        try {
14910            final XmlPullParser parser = Xml.newPullParser();
14911            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14912            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14913                    new BlobXmlRestorer() {
14914                        @Override
14915                        public void apply(XmlPullParser parser, int userId)
14916                                throws XmlPullParserException, IOException {
14917                            synchronized (mPackages) {
14918                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14919                                mSettings.writeLPr();
14920                            }
14921                        }
14922                    } );
14923        } catch (Exception e) {
14924            if (DEBUG_BACKUP) {
14925                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14926            }
14927        }
14928    }
14929
14930    @Override
14931    public byte[] getPermissionGrantBackup(int userId) {
14932        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14933            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
14934        }
14935
14936        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14937        try {
14938            final XmlSerializer serializer = new FastXmlSerializer();
14939            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14940            serializer.startDocument(null, true);
14941            serializer.startTag(null, TAG_PERMISSION_BACKUP);
14942
14943            synchronized (mPackages) {
14944                serializeRuntimePermissionGrantsLPr(serializer, userId);
14945            }
14946
14947            serializer.endTag(null, TAG_PERMISSION_BACKUP);
14948            serializer.endDocument();
14949            serializer.flush();
14950        } catch (Exception e) {
14951            if (DEBUG_BACKUP) {
14952                Slog.e(TAG, "Unable to write default apps for backup", e);
14953            }
14954            return null;
14955        }
14956
14957        return dataStream.toByteArray();
14958    }
14959
14960    @Override
14961    public void restorePermissionGrants(byte[] backup, int userId) {
14962        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14963            throw new SecurityException("Only the system may call restorePermissionGrants()");
14964        }
14965
14966        try {
14967            final XmlPullParser parser = Xml.newPullParser();
14968            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14969            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
14970                    new BlobXmlRestorer() {
14971                        @Override
14972                        public void apply(XmlPullParser parser, int userId)
14973                                throws XmlPullParserException, IOException {
14974                            synchronized (mPackages) {
14975                                processRestoredPermissionGrantsLPr(parser, userId);
14976                            }
14977                        }
14978                    } );
14979        } catch (Exception e) {
14980            if (DEBUG_BACKUP) {
14981                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14982            }
14983        }
14984    }
14985
14986    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
14987            throws IOException {
14988        serializer.startTag(null, TAG_ALL_GRANTS);
14989
14990        final int N = mSettings.mPackages.size();
14991        for (int i = 0; i < N; i++) {
14992            final PackageSetting ps = mSettings.mPackages.valueAt(i);
14993            boolean pkgGrantsKnown = false;
14994
14995            PermissionsState packagePerms = ps.getPermissionsState();
14996
14997            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
14998                final int grantFlags = state.getFlags();
14999                // only look at grants that are not system/policy fixed
15000                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15001                    final boolean isGranted = state.isGranted();
15002                    // And only back up the user-twiddled state bits
15003                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15004                        final String packageName = mSettings.mPackages.keyAt(i);
15005                        if (!pkgGrantsKnown) {
15006                            serializer.startTag(null, TAG_GRANT);
15007                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15008                            pkgGrantsKnown = true;
15009                        }
15010
15011                        final boolean userSet =
15012                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15013                        final boolean userFixed =
15014                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15015                        final boolean revoke =
15016                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15017
15018                        serializer.startTag(null, TAG_PERMISSION);
15019                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15020                        if (isGranted) {
15021                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15022                        }
15023                        if (userSet) {
15024                            serializer.attribute(null, ATTR_USER_SET, "true");
15025                        }
15026                        if (userFixed) {
15027                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15028                        }
15029                        if (revoke) {
15030                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15031                        }
15032                        serializer.endTag(null, TAG_PERMISSION);
15033                    }
15034                }
15035            }
15036
15037            if (pkgGrantsKnown) {
15038                serializer.endTag(null, TAG_GRANT);
15039            }
15040        }
15041
15042        serializer.endTag(null, TAG_ALL_GRANTS);
15043    }
15044
15045    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15046            throws XmlPullParserException, IOException {
15047        String pkgName = null;
15048        int outerDepth = parser.getDepth();
15049        int type;
15050        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15051                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15052            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15053                continue;
15054            }
15055
15056            final String tagName = parser.getName();
15057            if (tagName.equals(TAG_GRANT)) {
15058                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15059                if (DEBUG_BACKUP) {
15060                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15061                }
15062            } else if (tagName.equals(TAG_PERMISSION)) {
15063
15064                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15065                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15066
15067                int newFlagSet = 0;
15068                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15069                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15070                }
15071                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15072                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15073                }
15074                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15075                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15076                }
15077                if (DEBUG_BACKUP) {
15078                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15079                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15080                }
15081                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15082                if (ps != null) {
15083                    // Already installed so we apply the grant immediately
15084                    if (DEBUG_BACKUP) {
15085                        Slog.v(TAG, "        + already installed; applying");
15086                    }
15087                    PermissionsState perms = ps.getPermissionsState();
15088                    BasePermission bp = mSettings.mPermissions.get(permName);
15089                    if (bp != null) {
15090                        if (isGranted) {
15091                            perms.grantRuntimePermission(bp, userId);
15092                        }
15093                        if (newFlagSet != 0) {
15094                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15095                        }
15096                    }
15097                } else {
15098                    // Need to wait for post-restore install to apply the grant
15099                    if (DEBUG_BACKUP) {
15100                        Slog.v(TAG, "        - not yet installed; saving for later");
15101                    }
15102                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15103                            isGranted, newFlagSet, userId);
15104                }
15105            } else {
15106                PackageManagerService.reportSettingsProblem(Log.WARN,
15107                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15108                XmlUtils.skipCurrentTag(parser);
15109            }
15110        }
15111
15112        scheduleWriteSettingsLocked();
15113        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15114    }
15115
15116    @Override
15117    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15118            int sourceUserId, int targetUserId, int flags) {
15119        mContext.enforceCallingOrSelfPermission(
15120                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15121        int callingUid = Binder.getCallingUid();
15122        enforceOwnerRights(ownerPackage, callingUid);
15123        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15124        if (intentFilter.countActions() == 0) {
15125            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15126            return;
15127        }
15128        synchronized (mPackages) {
15129            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15130                    ownerPackage, targetUserId, flags);
15131            CrossProfileIntentResolver resolver =
15132                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15133            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15134            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15135            if (existing != null) {
15136                int size = existing.size();
15137                for (int i = 0; i < size; i++) {
15138                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15139                        return;
15140                    }
15141                }
15142            }
15143            resolver.addFilter(newFilter);
15144            scheduleWritePackageRestrictionsLocked(sourceUserId);
15145        }
15146    }
15147
15148    @Override
15149    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15150        mContext.enforceCallingOrSelfPermission(
15151                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15152        int callingUid = Binder.getCallingUid();
15153        enforceOwnerRights(ownerPackage, callingUid);
15154        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15155        synchronized (mPackages) {
15156            CrossProfileIntentResolver resolver =
15157                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15158            ArraySet<CrossProfileIntentFilter> set =
15159                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15160            for (CrossProfileIntentFilter filter : set) {
15161                if (filter.getOwnerPackage().equals(ownerPackage)) {
15162                    resolver.removeFilter(filter);
15163                }
15164            }
15165            scheduleWritePackageRestrictionsLocked(sourceUserId);
15166        }
15167    }
15168
15169    // Enforcing that callingUid is owning pkg on userId
15170    private void enforceOwnerRights(String pkg, int callingUid) {
15171        // The system owns everything.
15172        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15173            return;
15174        }
15175        int callingUserId = UserHandle.getUserId(callingUid);
15176        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15177        if (pi == null) {
15178            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15179                    + callingUserId);
15180        }
15181        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15182            throw new SecurityException("Calling uid " + callingUid
15183                    + " does not own package " + pkg);
15184        }
15185    }
15186
15187    @Override
15188    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15189        Intent intent = new Intent(Intent.ACTION_MAIN);
15190        intent.addCategory(Intent.CATEGORY_HOME);
15191
15192        final int callingUserId = UserHandle.getCallingUserId();
15193        List<ResolveInfo> list = queryIntentActivities(intent, null,
15194                PackageManager.GET_META_DATA, callingUserId);
15195        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15196                true, false, false, callingUserId);
15197
15198        allHomeCandidates.clear();
15199        if (list != null) {
15200            for (ResolveInfo ri : list) {
15201                allHomeCandidates.add(ri);
15202            }
15203        }
15204        return (preferred == null || preferred.activityInfo == null)
15205                ? null
15206                : new ComponentName(preferred.activityInfo.packageName,
15207                        preferred.activityInfo.name);
15208    }
15209
15210    @Override
15211    public void setApplicationEnabledSetting(String appPackageName,
15212            int newState, int flags, int userId, String callingPackage) {
15213        if (!sUserManager.exists(userId)) return;
15214        if (callingPackage == null) {
15215            callingPackage = Integer.toString(Binder.getCallingUid());
15216        }
15217        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15218    }
15219
15220    @Override
15221    public void setComponentEnabledSetting(ComponentName componentName,
15222            int newState, int flags, int userId) {
15223        if (!sUserManager.exists(userId)) return;
15224        setEnabledSetting(componentName.getPackageName(),
15225                componentName.getClassName(), newState, flags, userId, null);
15226    }
15227
15228    private void setEnabledSetting(final String packageName, String className, int newState,
15229            final int flags, int userId, String callingPackage) {
15230        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15231              || newState == COMPONENT_ENABLED_STATE_ENABLED
15232              || newState == COMPONENT_ENABLED_STATE_DISABLED
15233              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15234              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15235            throw new IllegalArgumentException("Invalid new component state: "
15236                    + newState);
15237        }
15238        PackageSetting pkgSetting;
15239        final int uid = Binder.getCallingUid();
15240        final int permission = mContext.checkCallingOrSelfPermission(
15241                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15242        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15243        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15244        boolean sendNow = false;
15245        boolean isApp = (className == null);
15246        String componentName = isApp ? packageName : className;
15247        int packageUid = -1;
15248        ArrayList<String> components;
15249
15250        // writer
15251        synchronized (mPackages) {
15252            pkgSetting = mSettings.mPackages.get(packageName);
15253            if (pkgSetting == null) {
15254                if (className == null) {
15255                    throw new IllegalArgumentException("Unknown package: " + packageName);
15256                }
15257                throw new IllegalArgumentException(
15258                        "Unknown component: " + packageName + "/" + className);
15259            }
15260            // Allow root and verify that userId is not being specified by a different user
15261            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15262                throw new SecurityException(
15263                        "Permission Denial: attempt to change component state from pid="
15264                        + Binder.getCallingPid()
15265                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15266            }
15267            if (className == null) {
15268                // We're dealing with an application/package level state change
15269                if (pkgSetting.getEnabled(userId) == newState) {
15270                    // Nothing to do
15271                    return;
15272                }
15273                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15274                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15275                    // Don't care about who enables an app.
15276                    callingPackage = null;
15277                }
15278                pkgSetting.setEnabled(newState, userId, callingPackage);
15279                // pkgSetting.pkg.mSetEnabled = newState;
15280            } else {
15281                // We're dealing with a component level state change
15282                // First, verify that this is a valid class name.
15283                PackageParser.Package pkg = pkgSetting.pkg;
15284                if (pkg == null || !pkg.hasComponentClassName(className)) {
15285                    if (pkg != null &&
15286                            pkg.applicationInfo.targetSdkVersion >=
15287                                    Build.VERSION_CODES.JELLY_BEAN) {
15288                        throw new IllegalArgumentException("Component class " + className
15289                                + " does not exist in " + packageName);
15290                    } else {
15291                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15292                                + className + " does not exist in " + packageName);
15293                    }
15294                }
15295                switch (newState) {
15296                case COMPONENT_ENABLED_STATE_ENABLED:
15297                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15298                        return;
15299                    }
15300                    break;
15301                case COMPONENT_ENABLED_STATE_DISABLED:
15302                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15303                        return;
15304                    }
15305                    break;
15306                case COMPONENT_ENABLED_STATE_DEFAULT:
15307                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15308                        return;
15309                    }
15310                    break;
15311                default:
15312                    Slog.e(TAG, "Invalid new component state: " + newState);
15313                    return;
15314                }
15315            }
15316            scheduleWritePackageRestrictionsLocked(userId);
15317            components = mPendingBroadcasts.get(userId, packageName);
15318            final boolean newPackage = components == null;
15319            if (newPackage) {
15320                components = new ArrayList<String>();
15321            }
15322            if (!components.contains(componentName)) {
15323                components.add(componentName);
15324            }
15325            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15326                sendNow = true;
15327                // Purge entry from pending broadcast list if another one exists already
15328                // since we are sending one right away.
15329                mPendingBroadcasts.remove(userId, packageName);
15330            } else {
15331                if (newPackage) {
15332                    mPendingBroadcasts.put(userId, packageName, components);
15333                }
15334                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15335                    // Schedule a message
15336                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15337                }
15338            }
15339        }
15340
15341        long callingId = Binder.clearCallingIdentity();
15342        try {
15343            if (sendNow) {
15344                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15345                sendPackageChangedBroadcast(packageName,
15346                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15347            }
15348        } finally {
15349            Binder.restoreCallingIdentity(callingId);
15350        }
15351    }
15352
15353    private void sendPackageChangedBroadcast(String packageName,
15354            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15355        if (DEBUG_INSTALL)
15356            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15357                    + componentNames);
15358        Bundle extras = new Bundle(4);
15359        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15360        String nameList[] = new String[componentNames.size()];
15361        componentNames.toArray(nameList);
15362        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15363        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15364        extras.putInt(Intent.EXTRA_UID, packageUid);
15365        // If this is not reporting a change of the overall package, then only send it
15366        // to registered receivers.  We don't want to launch a swath of apps for every
15367        // little component state change.
15368        final int flags = !componentNames.contains(packageName)
15369                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15370        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15371                new int[] {UserHandle.getUserId(packageUid)});
15372    }
15373
15374    @Override
15375    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15376        if (!sUserManager.exists(userId)) return;
15377        final int uid = Binder.getCallingUid();
15378        final int permission = mContext.checkCallingOrSelfPermission(
15379                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15380        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15381        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15382        // writer
15383        synchronized (mPackages) {
15384            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15385                    allowedByPermission, uid, userId)) {
15386                scheduleWritePackageRestrictionsLocked(userId);
15387            }
15388        }
15389    }
15390
15391    @Override
15392    public String getInstallerPackageName(String packageName) {
15393        // reader
15394        synchronized (mPackages) {
15395            return mSettings.getInstallerPackageNameLPr(packageName);
15396        }
15397    }
15398
15399    @Override
15400    public int getApplicationEnabledSetting(String packageName, int userId) {
15401        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15402        int uid = Binder.getCallingUid();
15403        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15404        // reader
15405        synchronized (mPackages) {
15406            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15407        }
15408    }
15409
15410    @Override
15411    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15412        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15413        int uid = Binder.getCallingUid();
15414        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15415        // reader
15416        synchronized (mPackages) {
15417            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15418        }
15419    }
15420
15421    @Override
15422    public void enterSafeMode() {
15423        enforceSystemOrRoot("Only the system can request entering safe mode");
15424
15425        if (!mSystemReady) {
15426            mSafeMode = true;
15427        }
15428    }
15429
15430    @Override
15431    public void systemReady() {
15432        mSystemReady = true;
15433
15434        // Read the compatibilty setting when the system is ready.
15435        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15436                mContext.getContentResolver(),
15437                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15438        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15439        if (DEBUG_SETTINGS) {
15440            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15441        }
15442
15443        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15444
15445        synchronized (mPackages) {
15446            // Verify that all of the preferred activity components actually
15447            // exist.  It is possible for applications to be updated and at
15448            // that point remove a previously declared activity component that
15449            // had been set as a preferred activity.  We try to clean this up
15450            // the next time we encounter that preferred activity, but it is
15451            // possible for the user flow to never be able to return to that
15452            // situation so here we do a sanity check to make sure we haven't
15453            // left any junk around.
15454            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15455            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15456                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15457                removed.clear();
15458                for (PreferredActivity pa : pir.filterSet()) {
15459                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15460                        removed.add(pa);
15461                    }
15462                }
15463                if (removed.size() > 0) {
15464                    for (int r=0; r<removed.size(); r++) {
15465                        PreferredActivity pa = removed.get(r);
15466                        Slog.w(TAG, "Removing dangling preferred activity: "
15467                                + pa.mPref.mComponent);
15468                        pir.removeFilter(pa);
15469                    }
15470                    mSettings.writePackageRestrictionsLPr(
15471                            mSettings.mPreferredActivities.keyAt(i));
15472                }
15473            }
15474
15475            for (int userId : UserManagerService.getInstance().getUserIds()) {
15476                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15477                    grantPermissionsUserIds = ArrayUtils.appendInt(
15478                            grantPermissionsUserIds, userId);
15479                }
15480            }
15481        }
15482        sUserManager.systemReady();
15483
15484        // If we upgraded grant all default permissions before kicking off.
15485        for (int userId : grantPermissionsUserIds) {
15486            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15487        }
15488
15489        // Kick off any messages waiting for system ready
15490        if (mPostSystemReadyMessages != null) {
15491            for (Message msg : mPostSystemReadyMessages) {
15492                msg.sendToTarget();
15493            }
15494            mPostSystemReadyMessages = null;
15495        }
15496
15497        // Watch for external volumes that come and go over time
15498        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15499        storage.registerListener(mStorageListener);
15500
15501        mInstallerService.systemReady();
15502        mPackageDexOptimizer.systemReady();
15503
15504        MountServiceInternal mountServiceInternal = LocalServices.getService(
15505                MountServiceInternal.class);
15506        mountServiceInternal.addExternalStoragePolicy(
15507                new MountServiceInternal.ExternalStorageMountPolicy() {
15508            @Override
15509            public int getMountMode(int uid, String packageName) {
15510                if (Process.isIsolated(uid)) {
15511                    return Zygote.MOUNT_EXTERNAL_NONE;
15512                }
15513                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15514                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15515                }
15516                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15517                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15518                }
15519                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15520                    return Zygote.MOUNT_EXTERNAL_READ;
15521                }
15522                return Zygote.MOUNT_EXTERNAL_WRITE;
15523            }
15524
15525            @Override
15526            public boolean hasExternalStorage(int uid, String packageName) {
15527                return true;
15528            }
15529        });
15530    }
15531
15532    @Override
15533    public boolean isSafeMode() {
15534        return mSafeMode;
15535    }
15536
15537    @Override
15538    public boolean hasSystemUidErrors() {
15539        return mHasSystemUidErrors;
15540    }
15541
15542    static String arrayToString(int[] array) {
15543        StringBuffer buf = new StringBuffer(128);
15544        buf.append('[');
15545        if (array != null) {
15546            for (int i=0; i<array.length; i++) {
15547                if (i > 0) buf.append(", ");
15548                buf.append(array[i]);
15549            }
15550        }
15551        buf.append(']');
15552        return buf.toString();
15553    }
15554
15555    static class DumpState {
15556        public static final int DUMP_LIBS = 1 << 0;
15557        public static final int DUMP_FEATURES = 1 << 1;
15558        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15559        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15560        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15561        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15562        public static final int DUMP_PERMISSIONS = 1 << 6;
15563        public static final int DUMP_PACKAGES = 1 << 7;
15564        public static final int DUMP_SHARED_USERS = 1 << 8;
15565        public static final int DUMP_MESSAGES = 1 << 9;
15566        public static final int DUMP_PROVIDERS = 1 << 10;
15567        public static final int DUMP_VERIFIERS = 1 << 11;
15568        public static final int DUMP_PREFERRED = 1 << 12;
15569        public static final int DUMP_PREFERRED_XML = 1 << 13;
15570        public static final int DUMP_KEYSETS = 1 << 14;
15571        public static final int DUMP_VERSION = 1 << 15;
15572        public static final int DUMP_INSTALLS = 1 << 16;
15573        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15574        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15575
15576        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15577
15578        private int mTypes;
15579
15580        private int mOptions;
15581
15582        private boolean mTitlePrinted;
15583
15584        private SharedUserSetting mSharedUser;
15585
15586        public boolean isDumping(int type) {
15587            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15588                return true;
15589            }
15590
15591            return (mTypes & type) != 0;
15592        }
15593
15594        public void setDump(int type) {
15595            mTypes |= type;
15596        }
15597
15598        public boolean isOptionEnabled(int option) {
15599            return (mOptions & option) != 0;
15600        }
15601
15602        public void setOptionEnabled(int option) {
15603            mOptions |= option;
15604        }
15605
15606        public boolean onTitlePrinted() {
15607            final boolean printed = mTitlePrinted;
15608            mTitlePrinted = true;
15609            return printed;
15610        }
15611
15612        public boolean getTitlePrinted() {
15613            return mTitlePrinted;
15614        }
15615
15616        public void setTitlePrinted(boolean enabled) {
15617            mTitlePrinted = enabled;
15618        }
15619
15620        public SharedUserSetting getSharedUser() {
15621            return mSharedUser;
15622        }
15623
15624        public void setSharedUser(SharedUserSetting user) {
15625            mSharedUser = user;
15626        }
15627    }
15628
15629    @Override
15630    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15631            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15632        (new PackageManagerShellCommand(this)).exec(
15633                this, in, out, err, args, resultReceiver);
15634    }
15635
15636    @Override
15637    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15638        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15639                != PackageManager.PERMISSION_GRANTED) {
15640            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15641                    + Binder.getCallingPid()
15642                    + ", uid=" + Binder.getCallingUid()
15643                    + " without permission "
15644                    + android.Manifest.permission.DUMP);
15645            return;
15646        }
15647
15648        DumpState dumpState = new DumpState();
15649        boolean fullPreferred = false;
15650        boolean checkin = false;
15651
15652        String packageName = null;
15653        ArraySet<String> permissionNames = null;
15654
15655        int opti = 0;
15656        while (opti < args.length) {
15657            String opt = args[opti];
15658            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15659                break;
15660            }
15661            opti++;
15662
15663            if ("-a".equals(opt)) {
15664                // Right now we only know how to print all.
15665            } else if ("-h".equals(opt)) {
15666                pw.println("Package manager dump options:");
15667                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15668                pw.println("    --checkin: dump for a checkin");
15669                pw.println("    -f: print details of intent filters");
15670                pw.println("    -h: print this help");
15671                pw.println("  cmd may be one of:");
15672                pw.println("    l[ibraries]: list known shared libraries");
15673                pw.println("    f[eatures]: list device features");
15674                pw.println("    k[eysets]: print known keysets");
15675                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15676                pw.println("    perm[issions]: dump permissions");
15677                pw.println("    permission [name ...]: dump declaration and use of given permission");
15678                pw.println("    pref[erred]: print preferred package settings");
15679                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15680                pw.println("    prov[iders]: dump content providers");
15681                pw.println("    p[ackages]: dump installed packages");
15682                pw.println("    s[hared-users]: dump shared user IDs");
15683                pw.println("    m[essages]: print collected runtime messages");
15684                pw.println("    v[erifiers]: print package verifier info");
15685                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15686                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15687                pw.println("    version: print database version info");
15688                pw.println("    write: write current settings now");
15689                pw.println("    installs: details about install sessions");
15690                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15691                pw.println("    <package.name>: info about given package");
15692                return;
15693            } else if ("--checkin".equals(opt)) {
15694                checkin = true;
15695            } else if ("-f".equals(opt)) {
15696                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15697            } else {
15698                pw.println("Unknown argument: " + opt + "; use -h for help");
15699            }
15700        }
15701
15702        // Is the caller requesting to dump a particular piece of data?
15703        if (opti < args.length) {
15704            String cmd = args[opti];
15705            opti++;
15706            // Is this a package name?
15707            if ("android".equals(cmd) || cmd.contains(".")) {
15708                packageName = cmd;
15709                // When dumping a single package, we always dump all of its
15710                // filter information since the amount of data will be reasonable.
15711                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15712            } else if ("check-permission".equals(cmd)) {
15713                if (opti >= args.length) {
15714                    pw.println("Error: check-permission missing permission argument");
15715                    return;
15716                }
15717                String perm = args[opti];
15718                opti++;
15719                if (opti >= args.length) {
15720                    pw.println("Error: check-permission missing package argument");
15721                    return;
15722                }
15723                String pkg = args[opti];
15724                opti++;
15725                int user = UserHandle.getUserId(Binder.getCallingUid());
15726                if (opti < args.length) {
15727                    try {
15728                        user = Integer.parseInt(args[opti]);
15729                    } catch (NumberFormatException e) {
15730                        pw.println("Error: check-permission user argument is not a number: "
15731                                + args[opti]);
15732                        return;
15733                    }
15734                }
15735                pw.println(checkPermission(perm, pkg, user));
15736                return;
15737            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15738                dumpState.setDump(DumpState.DUMP_LIBS);
15739            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15740                dumpState.setDump(DumpState.DUMP_FEATURES);
15741            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15742                if (opti >= args.length) {
15743                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15744                            | DumpState.DUMP_SERVICE_RESOLVERS
15745                            | DumpState.DUMP_RECEIVER_RESOLVERS
15746                            | DumpState.DUMP_CONTENT_RESOLVERS);
15747                } else {
15748                    while (opti < args.length) {
15749                        String name = args[opti];
15750                        if ("a".equals(name) || "activity".equals(name)) {
15751                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15752                        } else if ("s".equals(name) || "service".equals(name)) {
15753                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15754                        } else if ("r".equals(name) || "receiver".equals(name)) {
15755                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15756                        } else if ("c".equals(name) || "content".equals(name)) {
15757                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15758                        } else {
15759                            pw.println("Error: unknown resolver table type: " + name);
15760                            return;
15761                        }
15762                        opti++;
15763                    }
15764                }
15765            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15766                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15767            } else if ("permission".equals(cmd)) {
15768                if (opti >= args.length) {
15769                    pw.println("Error: permission requires permission name");
15770                    return;
15771                }
15772                permissionNames = new ArraySet<>();
15773                while (opti < args.length) {
15774                    permissionNames.add(args[opti]);
15775                    opti++;
15776                }
15777                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15778                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15779            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15780                dumpState.setDump(DumpState.DUMP_PREFERRED);
15781            } else if ("preferred-xml".equals(cmd)) {
15782                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15783                if (opti < args.length && "--full".equals(args[opti])) {
15784                    fullPreferred = true;
15785                    opti++;
15786                }
15787            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15788                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15789            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15790                dumpState.setDump(DumpState.DUMP_PACKAGES);
15791            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15792                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15793            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15794                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15795            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15796                dumpState.setDump(DumpState.DUMP_MESSAGES);
15797            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15798                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15799            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15800                    || "intent-filter-verifiers".equals(cmd)) {
15801                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15802            } else if ("version".equals(cmd)) {
15803                dumpState.setDump(DumpState.DUMP_VERSION);
15804            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15805                dumpState.setDump(DumpState.DUMP_KEYSETS);
15806            } else if ("installs".equals(cmd)) {
15807                dumpState.setDump(DumpState.DUMP_INSTALLS);
15808            } else if ("write".equals(cmd)) {
15809                synchronized (mPackages) {
15810                    mSettings.writeLPr();
15811                    pw.println("Settings written.");
15812                    return;
15813                }
15814            }
15815        }
15816
15817        if (checkin) {
15818            pw.println("vers,1");
15819        }
15820
15821        // reader
15822        synchronized (mPackages) {
15823            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15824                if (!checkin) {
15825                    if (dumpState.onTitlePrinted())
15826                        pw.println();
15827                    pw.println("Database versions:");
15828                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15829                }
15830            }
15831
15832            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15833                if (!checkin) {
15834                    if (dumpState.onTitlePrinted())
15835                        pw.println();
15836                    pw.println("Verifiers:");
15837                    pw.print("  Required: ");
15838                    pw.print(mRequiredVerifierPackage);
15839                    pw.print(" (uid=");
15840                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15841                            UserHandle.USER_SYSTEM));
15842                    pw.println(")");
15843                } else if (mRequiredVerifierPackage != null) {
15844                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15845                    pw.print(",");
15846                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15847                            UserHandle.USER_SYSTEM));
15848                }
15849            }
15850
15851            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15852                    packageName == null) {
15853                if (mIntentFilterVerifierComponent != null) {
15854                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15855                    if (!checkin) {
15856                        if (dumpState.onTitlePrinted())
15857                            pw.println();
15858                        pw.println("Intent Filter Verifier:");
15859                        pw.print("  Using: ");
15860                        pw.print(verifierPackageName);
15861                        pw.print(" (uid=");
15862                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15863                                UserHandle.USER_SYSTEM));
15864                        pw.println(")");
15865                    } else if (verifierPackageName != null) {
15866                        pw.print("ifv,"); pw.print(verifierPackageName);
15867                        pw.print(",");
15868                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15869                                UserHandle.USER_SYSTEM));
15870                    }
15871                } else {
15872                    pw.println();
15873                    pw.println("No Intent Filter Verifier available!");
15874                }
15875            }
15876
15877            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15878                boolean printedHeader = false;
15879                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15880                while (it.hasNext()) {
15881                    String name = it.next();
15882                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15883                    if (!checkin) {
15884                        if (!printedHeader) {
15885                            if (dumpState.onTitlePrinted())
15886                                pw.println();
15887                            pw.println("Libraries:");
15888                            printedHeader = true;
15889                        }
15890                        pw.print("  ");
15891                    } else {
15892                        pw.print("lib,");
15893                    }
15894                    pw.print(name);
15895                    if (!checkin) {
15896                        pw.print(" -> ");
15897                    }
15898                    if (ent.path != null) {
15899                        if (!checkin) {
15900                            pw.print("(jar) ");
15901                            pw.print(ent.path);
15902                        } else {
15903                            pw.print(",jar,");
15904                            pw.print(ent.path);
15905                        }
15906                    } else {
15907                        if (!checkin) {
15908                            pw.print("(apk) ");
15909                            pw.print(ent.apk);
15910                        } else {
15911                            pw.print(",apk,");
15912                            pw.print(ent.apk);
15913                        }
15914                    }
15915                    pw.println();
15916                }
15917            }
15918
15919            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15920                if (dumpState.onTitlePrinted())
15921                    pw.println();
15922                if (!checkin) {
15923                    pw.println("Features:");
15924                }
15925                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15926                while (it.hasNext()) {
15927                    String name = it.next();
15928                    if (!checkin) {
15929                        pw.print("  ");
15930                    } else {
15931                        pw.print("feat,");
15932                    }
15933                    pw.println(name);
15934                }
15935            }
15936
15937            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15938                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15939                        : "Activity Resolver Table:", "  ", packageName,
15940                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15941                    dumpState.setTitlePrinted(true);
15942                }
15943            }
15944            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15945                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15946                        : "Receiver Resolver Table:", "  ", packageName,
15947                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15948                    dumpState.setTitlePrinted(true);
15949                }
15950            }
15951            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15952                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15953                        : "Service Resolver Table:", "  ", packageName,
15954                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15955                    dumpState.setTitlePrinted(true);
15956                }
15957            }
15958            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15959                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15960                        : "Provider Resolver Table:", "  ", packageName,
15961                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15962                    dumpState.setTitlePrinted(true);
15963                }
15964            }
15965
15966            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15967                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15968                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15969                    int user = mSettings.mPreferredActivities.keyAt(i);
15970                    if (pir.dump(pw,
15971                            dumpState.getTitlePrinted()
15972                                ? "\nPreferred Activities User " + user + ":"
15973                                : "Preferred Activities User " + user + ":", "  ",
15974                            packageName, true, false)) {
15975                        dumpState.setTitlePrinted(true);
15976                    }
15977                }
15978            }
15979
15980            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15981                pw.flush();
15982                FileOutputStream fout = new FileOutputStream(fd);
15983                BufferedOutputStream str = new BufferedOutputStream(fout);
15984                XmlSerializer serializer = new FastXmlSerializer();
15985                try {
15986                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15987                    serializer.startDocument(null, true);
15988                    serializer.setFeature(
15989                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15990                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15991                    serializer.endDocument();
15992                    serializer.flush();
15993                } catch (IllegalArgumentException e) {
15994                    pw.println("Failed writing: " + e);
15995                } catch (IllegalStateException e) {
15996                    pw.println("Failed writing: " + e);
15997                } catch (IOException e) {
15998                    pw.println("Failed writing: " + e);
15999                }
16000            }
16001
16002            if (!checkin
16003                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16004                    && packageName == null) {
16005                pw.println();
16006                int count = mSettings.mPackages.size();
16007                if (count == 0) {
16008                    pw.println("No applications!");
16009                    pw.println();
16010                } else {
16011                    final String prefix = "  ";
16012                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16013                    if (allPackageSettings.size() == 0) {
16014                        pw.println("No domain preferred apps!");
16015                        pw.println();
16016                    } else {
16017                        pw.println("App verification status:");
16018                        pw.println();
16019                        count = 0;
16020                        for (PackageSetting ps : allPackageSettings) {
16021                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16022                            if (ivi == null || ivi.getPackageName() == null) continue;
16023                            pw.println(prefix + "Package: " + ivi.getPackageName());
16024                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16025                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16026                            pw.println();
16027                            count++;
16028                        }
16029                        if (count == 0) {
16030                            pw.println(prefix + "No app verification established.");
16031                            pw.println();
16032                        }
16033                        for (int userId : sUserManager.getUserIds()) {
16034                            pw.println("App linkages for user " + userId + ":");
16035                            pw.println();
16036                            count = 0;
16037                            for (PackageSetting ps : allPackageSettings) {
16038                                final long status = ps.getDomainVerificationStatusForUser(userId);
16039                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16040                                    continue;
16041                                }
16042                                pw.println(prefix + "Package: " + ps.name);
16043                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16044                                String statusStr = IntentFilterVerificationInfo.
16045                                        getStatusStringFromValue(status);
16046                                pw.println(prefix + "Status:  " + statusStr);
16047                                pw.println();
16048                                count++;
16049                            }
16050                            if (count == 0) {
16051                                pw.println(prefix + "No configured app linkages.");
16052                                pw.println();
16053                            }
16054                        }
16055                    }
16056                }
16057            }
16058
16059            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16060                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16061                if (packageName == null && permissionNames == null) {
16062                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16063                        if (iperm == 0) {
16064                            if (dumpState.onTitlePrinted())
16065                                pw.println();
16066                            pw.println("AppOp Permissions:");
16067                        }
16068                        pw.print("  AppOp Permission ");
16069                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16070                        pw.println(":");
16071                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16072                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16073                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16074                        }
16075                    }
16076                }
16077            }
16078
16079            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16080                boolean printedSomething = false;
16081                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16082                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16083                        continue;
16084                    }
16085                    if (!printedSomething) {
16086                        if (dumpState.onTitlePrinted())
16087                            pw.println();
16088                        pw.println("Registered ContentProviders:");
16089                        printedSomething = true;
16090                    }
16091                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16092                    pw.print("    "); pw.println(p.toString());
16093                }
16094                printedSomething = false;
16095                for (Map.Entry<String, PackageParser.Provider> entry :
16096                        mProvidersByAuthority.entrySet()) {
16097                    PackageParser.Provider p = entry.getValue();
16098                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16099                        continue;
16100                    }
16101                    if (!printedSomething) {
16102                        if (dumpState.onTitlePrinted())
16103                            pw.println();
16104                        pw.println("ContentProvider Authorities:");
16105                        printedSomething = true;
16106                    }
16107                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16108                    pw.print("    "); pw.println(p.toString());
16109                    if (p.info != null && p.info.applicationInfo != null) {
16110                        final String appInfo = p.info.applicationInfo.toString();
16111                        pw.print("      applicationInfo="); pw.println(appInfo);
16112                    }
16113                }
16114            }
16115
16116            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16117                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16118            }
16119
16120            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16121                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16122            }
16123
16124            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16125                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16126            }
16127
16128            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16129                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16130            }
16131
16132            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16133                // XXX should handle packageName != null by dumping only install data that
16134                // the given package is involved with.
16135                if (dumpState.onTitlePrinted()) pw.println();
16136                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16137            }
16138
16139            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16140                if (dumpState.onTitlePrinted()) pw.println();
16141                mSettings.dumpReadMessagesLPr(pw, dumpState);
16142
16143                pw.println();
16144                pw.println("Package warning messages:");
16145                BufferedReader in = null;
16146                String line = null;
16147                try {
16148                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16149                    while ((line = in.readLine()) != null) {
16150                        if (line.contains("ignored: updated version")) continue;
16151                        pw.println(line);
16152                    }
16153                } catch (IOException ignored) {
16154                } finally {
16155                    IoUtils.closeQuietly(in);
16156                }
16157            }
16158
16159            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16160                BufferedReader in = null;
16161                String line = null;
16162                try {
16163                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16164                    while ((line = in.readLine()) != null) {
16165                        if (line.contains("ignored: updated version")) continue;
16166                        pw.print("msg,");
16167                        pw.println(line);
16168                    }
16169                } catch (IOException ignored) {
16170                } finally {
16171                    IoUtils.closeQuietly(in);
16172                }
16173            }
16174        }
16175    }
16176
16177    private String dumpDomainString(String packageName) {
16178        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16179        List<IntentFilter> filters = getAllIntentFilters(packageName);
16180
16181        ArraySet<String> result = new ArraySet<>();
16182        if (iviList.size() > 0) {
16183            for (IntentFilterVerificationInfo ivi : iviList) {
16184                for (String host : ivi.getDomains()) {
16185                    result.add(host);
16186                }
16187            }
16188        }
16189        if (filters != null && filters.size() > 0) {
16190            for (IntentFilter filter : filters) {
16191                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16192                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16193                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16194                    result.addAll(filter.getHostsList());
16195                }
16196            }
16197        }
16198
16199        StringBuilder sb = new StringBuilder(result.size() * 16);
16200        for (String domain : result) {
16201            if (sb.length() > 0) sb.append(" ");
16202            sb.append(domain);
16203        }
16204        return sb.toString();
16205    }
16206
16207    // ------- apps on sdcard specific code -------
16208    static final boolean DEBUG_SD_INSTALL = false;
16209
16210    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16211
16212    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16213
16214    private boolean mMediaMounted = false;
16215
16216    static String getEncryptKey() {
16217        try {
16218            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16219                    SD_ENCRYPTION_KEYSTORE_NAME);
16220            if (sdEncKey == null) {
16221                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16222                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16223                if (sdEncKey == null) {
16224                    Slog.e(TAG, "Failed to create encryption keys");
16225                    return null;
16226                }
16227            }
16228            return sdEncKey;
16229        } catch (NoSuchAlgorithmException nsae) {
16230            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16231            return null;
16232        } catch (IOException ioe) {
16233            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16234            return null;
16235        }
16236    }
16237
16238    /*
16239     * Update media status on PackageManager.
16240     */
16241    @Override
16242    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16243        int callingUid = Binder.getCallingUid();
16244        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16245            throw new SecurityException("Media status can only be updated by the system");
16246        }
16247        // reader; this apparently protects mMediaMounted, but should probably
16248        // be a different lock in that case.
16249        synchronized (mPackages) {
16250            Log.i(TAG, "Updating external media status from "
16251                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16252                    + (mediaStatus ? "mounted" : "unmounted"));
16253            if (DEBUG_SD_INSTALL)
16254                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16255                        + ", mMediaMounted=" + mMediaMounted);
16256            if (mediaStatus == mMediaMounted) {
16257                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16258                        : 0, -1);
16259                mHandler.sendMessage(msg);
16260                return;
16261            }
16262            mMediaMounted = mediaStatus;
16263        }
16264        // Queue up an async operation since the package installation may take a
16265        // little while.
16266        mHandler.post(new Runnable() {
16267            public void run() {
16268                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16269            }
16270        });
16271    }
16272
16273    /**
16274     * Called by MountService when the initial ASECs to scan are available.
16275     * Should block until all the ASEC containers are finished being scanned.
16276     */
16277    public void scanAvailableAsecs() {
16278        updateExternalMediaStatusInner(true, false, false);
16279    }
16280
16281    /*
16282     * Collect information of applications on external media, map them against
16283     * existing containers and update information based on current mount status.
16284     * Please note that we always have to report status if reportStatus has been
16285     * set to true especially when unloading packages.
16286     */
16287    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16288            boolean externalStorage) {
16289        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16290        int[] uidArr = EmptyArray.INT;
16291
16292        final String[] list = PackageHelper.getSecureContainerList();
16293        if (ArrayUtils.isEmpty(list)) {
16294            Log.i(TAG, "No secure containers found");
16295        } else {
16296            // Process list of secure containers and categorize them
16297            // as active or stale based on their package internal state.
16298
16299            // reader
16300            synchronized (mPackages) {
16301                for (String cid : list) {
16302                    // Leave stages untouched for now; installer service owns them
16303                    if (PackageInstallerService.isStageName(cid)) continue;
16304
16305                    if (DEBUG_SD_INSTALL)
16306                        Log.i(TAG, "Processing container " + cid);
16307                    String pkgName = getAsecPackageName(cid);
16308                    if (pkgName == null) {
16309                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16310                        continue;
16311                    }
16312                    if (DEBUG_SD_INSTALL)
16313                        Log.i(TAG, "Looking for pkg : " + pkgName);
16314
16315                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16316                    if (ps == null) {
16317                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16318                        continue;
16319                    }
16320
16321                    /*
16322                     * Skip packages that are not external if we're unmounting
16323                     * external storage.
16324                     */
16325                    if (externalStorage && !isMounted && !isExternal(ps)) {
16326                        continue;
16327                    }
16328
16329                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16330                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16331                    // The package status is changed only if the code path
16332                    // matches between settings and the container id.
16333                    if (ps.codePathString != null
16334                            && ps.codePathString.startsWith(args.getCodePath())) {
16335                        if (DEBUG_SD_INSTALL) {
16336                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16337                                    + " at code path: " + ps.codePathString);
16338                        }
16339
16340                        // We do have a valid package installed on sdcard
16341                        processCids.put(args, ps.codePathString);
16342                        final int uid = ps.appId;
16343                        if (uid != -1) {
16344                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16345                        }
16346                    } else {
16347                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16348                                + ps.codePathString);
16349                    }
16350                }
16351            }
16352
16353            Arrays.sort(uidArr);
16354        }
16355
16356        // Process packages with valid entries.
16357        if (isMounted) {
16358            if (DEBUG_SD_INSTALL)
16359                Log.i(TAG, "Loading packages");
16360            loadMediaPackages(processCids, uidArr, externalStorage);
16361            startCleaningPackages();
16362            mInstallerService.onSecureContainersAvailable();
16363        } else {
16364            if (DEBUG_SD_INSTALL)
16365                Log.i(TAG, "Unloading packages");
16366            unloadMediaPackages(processCids, uidArr, reportStatus);
16367        }
16368    }
16369
16370    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16371            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16372        final int size = infos.size();
16373        final String[] packageNames = new String[size];
16374        final int[] packageUids = new int[size];
16375        for (int i = 0; i < size; i++) {
16376            final ApplicationInfo info = infos.get(i);
16377            packageNames[i] = info.packageName;
16378            packageUids[i] = info.uid;
16379        }
16380        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16381                finishedReceiver);
16382    }
16383
16384    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16385            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16386        sendResourcesChangedBroadcast(mediaStatus, replacing,
16387                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16388    }
16389
16390    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16391            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16392        int size = pkgList.length;
16393        if (size > 0) {
16394            // Send broadcasts here
16395            Bundle extras = new Bundle();
16396            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16397            if (uidArr != null) {
16398                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16399            }
16400            if (replacing) {
16401                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16402            }
16403            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16404                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16405            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16406        }
16407    }
16408
16409   /*
16410     * Look at potentially valid container ids from processCids If package
16411     * information doesn't match the one on record or package scanning fails,
16412     * the cid is added to list of removeCids. We currently don't delete stale
16413     * containers.
16414     */
16415    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16416            boolean externalStorage) {
16417        ArrayList<String> pkgList = new ArrayList<String>();
16418        Set<AsecInstallArgs> keys = processCids.keySet();
16419
16420        for (AsecInstallArgs args : keys) {
16421            String codePath = processCids.get(args);
16422            if (DEBUG_SD_INSTALL)
16423                Log.i(TAG, "Loading container : " + args.cid);
16424            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16425            try {
16426                // Make sure there are no container errors first.
16427                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16428                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16429                            + " when installing from sdcard");
16430                    continue;
16431                }
16432                // Check code path here.
16433                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16434                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16435                            + " does not match one in settings " + codePath);
16436                    continue;
16437                }
16438                // Parse package
16439                int parseFlags = mDefParseFlags;
16440                if (args.isExternalAsec()) {
16441                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16442                }
16443                if (args.isFwdLocked()) {
16444                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16445                }
16446
16447                synchronized (mInstallLock) {
16448                    PackageParser.Package pkg = null;
16449                    try {
16450                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16451                    } catch (PackageManagerException e) {
16452                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16453                    }
16454                    // Scan the package
16455                    if (pkg != null) {
16456                        /*
16457                         * TODO why is the lock being held? doPostInstall is
16458                         * called in other places without the lock. This needs
16459                         * to be straightened out.
16460                         */
16461                        // writer
16462                        synchronized (mPackages) {
16463                            retCode = PackageManager.INSTALL_SUCCEEDED;
16464                            pkgList.add(pkg.packageName);
16465                            // Post process args
16466                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16467                                    pkg.applicationInfo.uid);
16468                        }
16469                    } else {
16470                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16471                    }
16472                }
16473
16474            } finally {
16475                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16476                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16477                }
16478            }
16479        }
16480        // writer
16481        synchronized (mPackages) {
16482            // If the platform SDK has changed since the last time we booted,
16483            // we need to re-grant app permission to catch any new ones that
16484            // appear. This is really a hack, and means that apps can in some
16485            // cases get permissions that the user didn't initially explicitly
16486            // allow... it would be nice to have some better way to handle
16487            // this situation.
16488            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16489                    : mSettings.getInternalVersion();
16490            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16491                    : StorageManager.UUID_PRIVATE_INTERNAL;
16492
16493            int updateFlags = UPDATE_PERMISSIONS_ALL;
16494            if (ver.sdkVersion != mSdkVersion) {
16495                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16496                        + mSdkVersion + "; regranting permissions for external");
16497                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16498            }
16499            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16500
16501            // Yay, everything is now upgraded
16502            ver.forceCurrent();
16503
16504            // can downgrade to reader
16505            // Persist settings
16506            mSettings.writeLPr();
16507        }
16508        // Send a broadcast to let everyone know we are done processing
16509        if (pkgList.size() > 0) {
16510            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16511        }
16512    }
16513
16514   /*
16515     * Utility method to unload a list of specified containers
16516     */
16517    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16518        // Just unmount all valid containers.
16519        for (AsecInstallArgs arg : cidArgs) {
16520            synchronized (mInstallLock) {
16521                arg.doPostDeleteLI(false);
16522           }
16523       }
16524   }
16525
16526    /*
16527     * Unload packages mounted on external media. This involves deleting package
16528     * data from internal structures, sending broadcasts about diabled packages,
16529     * gc'ing to free up references, unmounting all secure containers
16530     * corresponding to packages on external media, and posting a
16531     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16532     * that we always have to post this message if status has been requested no
16533     * matter what.
16534     */
16535    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16536            final boolean reportStatus) {
16537        if (DEBUG_SD_INSTALL)
16538            Log.i(TAG, "unloading media packages");
16539        ArrayList<String> pkgList = new ArrayList<String>();
16540        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16541        final Set<AsecInstallArgs> keys = processCids.keySet();
16542        for (AsecInstallArgs args : keys) {
16543            String pkgName = args.getPackageName();
16544            if (DEBUG_SD_INSTALL)
16545                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16546            // Delete package internally
16547            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16548            synchronized (mInstallLock) {
16549                boolean res = deletePackageLI(pkgName, null, false, null, null,
16550                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16551                if (res) {
16552                    pkgList.add(pkgName);
16553                } else {
16554                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16555                    failedList.add(args);
16556                }
16557            }
16558        }
16559
16560        // reader
16561        synchronized (mPackages) {
16562            // We didn't update the settings after removing each package;
16563            // write them now for all packages.
16564            mSettings.writeLPr();
16565        }
16566
16567        // We have to absolutely send UPDATED_MEDIA_STATUS only
16568        // after confirming that all the receivers processed the ordered
16569        // broadcast when packages get disabled, force a gc to clean things up.
16570        // and unload all the containers.
16571        if (pkgList.size() > 0) {
16572            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16573                    new IIntentReceiver.Stub() {
16574                public void performReceive(Intent intent, int resultCode, String data,
16575                        Bundle extras, boolean ordered, boolean sticky,
16576                        int sendingUser) throws RemoteException {
16577                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16578                            reportStatus ? 1 : 0, 1, keys);
16579                    mHandler.sendMessage(msg);
16580                }
16581            });
16582        } else {
16583            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16584                    keys);
16585            mHandler.sendMessage(msg);
16586        }
16587    }
16588
16589    private void loadPrivatePackages(final VolumeInfo vol) {
16590        mHandler.post(new Runnable() {
16591            @Override
16592            public void run() {
16593                loadPrivatePackagesInner(vol);
16594            }
16595        });
16596    }
16597
16598    private void loadPrivatePackagesInner(VolumeInfo vol) {
16599        final String volumeUuid = vol.fsUuid;
16600        if (TextUtils.isEmpty(volumeUuid)) {
16601            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16602            return;
16603        }
16604
16605        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16606        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16607
16608        final VersionInfo ver;
16609        final List<PackageSetting> packages;
16610        synchronized (mPackages) {
16611            ver = mSettings.findOrCreateVersion(volumeUuid);
16612            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16613        }
16614
16615        // TODO: introduce a new concept similar to "frozen" to prevent these
16616        // apps from being launched until after data has been fully reconciled
16617        for (PackageSetting ps : packages) {
16618            synchronized (mInstallLock) {
16619                final PackageParser.Package pkg;
16620                try {
16621                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16622                    loaded.add(pkg.applicationInfo);
16623
16624                } catch (PackageManagerException e) {
16625                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16626                }
16627
16628                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16629                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16630                }
16631            }
16632        }
16633
16634        // Reconcile app data for all started/unlocked users
16635        final UserManager um = mContext.getSystemService(UserManager.class);
16636        for (UserInfo user : um.getUsers()) {
16637            if (um.isUserUnlocked(user.id)) {
16638                reconcileAppsData(volumeUuid, user.id,
16639                        Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE);
16640            } else if (um.isUserRunning(user.id)) {
16641                reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE);
16642            } else {
16643                continue;
16644            }
16645        }
16646
16647        synchronized (mPackages) {
16648            int updateFlags = UPDATE_PERMISSIONS_ALL;
16649            if (ver.sdkVersion != mSdkVersion) {
16650                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16651                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16652                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16653            }
16654            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16655
16656            // Yay, everything is now upgraded
16657            ver.forceCurrent();
16658
16659            mSettings.writeLPr();
16660        }
16661
16662        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16663        sendResourcesChangedBroadcast(true, false, loaded, null);
16664    }
16665
16666    private void unloadPrivatePackages(final VolumeInfo vol) {
16667        mHandler.post(new Runnable() {
16668            @Override
16669            public void run() {
16670                unloadPrivatePackagesInner(vol);
16671            }
16672        });
16673    }
16674
16675    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16676        final String volumeUuid = vol.fsUuid;
16677        if (TextUtils.isEmpty(volumeUuid)) {
16678            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16679            return;
16680        }
16681
16682        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16683        synchronized (mInstallLock) {
16684        synchronized (mPackages) {
16685            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16686            for (PackageSetting ps : packages) {
16687                if (ps.pkg == null) continue;
16688
16689                final ApplicationInfo info = ps.pkg.applicationInfo;
16690                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16691                if (deletePackageLI(ps.name, null, false, null, null,
16692                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16693                    unloaded.add(info);
16694                } else {
16695                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16696                }
16697            }
16698
16699            mSettings.writeLPr();
16700        }
16701        }
16702
16703        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16704        sendResourcesChangedBroadcast(false, false, unloaded, null);
16705    }
16706
16707    /**
16708     * Examine all users present on given mounted volume, and destroy data
16709     * belonging to users that are no longer valid, or whose user ID has been
16710     * recycled.
16711     */
16712    private void reconcileUsers(String volumeUuid) {
16713        final File[] files = FileUtils
16714                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16715        for (File file : files) {
16716            if (!file.isDirectory()) continue;
16717
16718            final int userId;
16719            final UserInfo info;
16720            try {
16721                userId = Integer.parseInt(file.getName());
16722                info = sUserManager.getUserInfo(userId);
16723            } catch (NumberFormatException e) {
16724                Slog.w(TAG, "Invalid user directory " + file);
16725                continue;
16726            }
16727
16728            boolean destroyUser = false;
16729            if (info == null) {
16730                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16731                        + " because no matching user was found");
16732                destroyUser = true;
16733            } else {
16734                try {
16735                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16736                } catch (IOException e) {
16737                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16738                            + " because we failed to enforce serial number: " + e);
16739                    destroyUser = true;
16740                }
16741            }
16742
16743            if (destroyUser) {
16744                synchronized (mInstallLock) {
16745                    try {
16746                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16747                    } catch (InstallerException e) {
16748                        Slog.w(TAG, "Failed to clean up user dirs", e);
16749                    }
16750                }
16751            }
16752        }
16753
16754        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16755        final UserManager um = mContext.getSystemService(UserManager.class);
16756        for (UserInfo user : um.getUsers()) {
16757            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16758            if (userDir.exists()) continue;
16759
16760            try {
16761                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16762                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16763            } catch (IOException e) {
16764                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16765            }
16766        }
16767    }
16768
16769    private void assertPackageKnown(String volumeUuid, String packageName)
16770            throws PackageManagerException {
16771        synchronized (mPackages) {
16772            final PackageSetting ps = mSettings.mPackages.get(packageName);
16773            if (ps == null) {
16774                throw new PackageManagerException("Package " + packageName + " is unknown");
16775            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16776                throw new PackageManagerException(
16777                        "Package " + packageName + " found on unknown volume " + volumeUuid
16778                                + "; expected volume " + ps.volumeUuid);
16779            }
16780        }
16781    }
16782
16783    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16784            throws PackageManagerException {
16785        synchronized (mPackages) {
16786            final PackageSetting ps = mSettings.mPackages.get(packageName);
16787            if (ps == null) {
16788                throw new PackageManagerException("Package " + packageName + " is unknown");
16789            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16790                throw new PackageManagerException(
16791                        "Package " + packageName + " found on unknown volume " + volumeUuid
16792                                + "; expected volume " + ps.volumeUuid);
16793            } else if (!ps.getInstalled(userId)) {
16794                throw new PackageManagerException(
16795                        "Package " + packageName + " not installed for user " + userId);
16796            }
16797        }
16798    }
16799
16800    /**
16801     * Examine all apps present on given mounted volume, and destroy apps that
16802     * aren't expected, either due to uninstallation or reinstallation on
16803     * another volume.
16804     */
16805    private void reconcileApps(String volumeUuid) {
16806        final File[] files = FileUtils
16807                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16808        for (File file : files) {
16809            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16810                    && !PackageInstallerService.isStageName(file.getName());
16811            if (!isPackage) {
16812                // Ignore entries which are not packages
16813                continue;
16814            }
16815
16816            try {
16817                final PackageLite pkg = PackageParser.parsePackageLite(file,
16818                        PackageParser.PARSE_MUST_BE_APK);
16819                assertPackageKnown(volumeUuid, pkg.packageName);
16820
16821            } catch (PackageParserException | PackageManagerException e) {
16822                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16823                synchronized (mInstallLock) {
16824                    removeCodePathLI(file);
16825                }
16826            }
16827        }
16828    }
16829
16830    /**
16831     * Reconcile all app data for the given user.
16832     * <p>
16833     * Verifies that directories exist and that ownership and labeling is
16834     * correct for all installed apps on all mounted volumes.
16835     */
16836    void reconcileAppsData(int userId, @StorageFlags int flags) {
16837        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16838        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16839            final String volumeUuid = vol.getFsUuid();
16840            reconcileAppsData(volumeUuid, userId, flags);
16841        }
16842    }
16843
16844    /**
16845     * Reconcile all app data on given mounted volume.
16846     * <p>
16847     * Destroys app data that isn't expected, either due to uninstallation or
16848     * reinstallation on another volume.
16849     * <p>
16850     * Verifies that directories exist and that ownership and labeling is
16851     * correct for all installed apps.
16852     */
16853    private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) {
16854        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
16855                + Integer.toHexString(flags));
16856
16857        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
16858        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
16859
16860        boolean restoreconNeeded = false;
16861
16862        // First look for stale data that doesn't belong, and check if things
16863        // have changed since we did our last restorecon
16864        if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16865            if (!isUserKeyUnlocked(userId)) {
16866                throw new RuntimeException(
16867                        "Yikes, someone asked us to reconcile CE storage while " + userId
16868                                + " was still locked; this would have caused massive data loss!");
16869            }
16870
16871            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
16872
16873            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
16874            for (File file : files) {
16875                final String packageName = file.getName();
16876                try {
16877                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16878                } catch (PackageManagerException e) {
16879                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16880                    synchronized (mInstallLock) {
16881                        destroyAppDataLI(volumeUuid, packageName, userId,
16882                                Installer.FLAG_CE_STORAGE);
16883                    }
16884                }
16885            }
16886        }
16887        if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16888            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
16889
16890            final File[] files = FileUtils.listFilesOrEmpty(deDir);
16891            for (File file : files) {
16892                final String packageName = file.getName();
16893                try {
16894                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16895                } catch (PackageManagerException e) {
16896                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16897                    synchronized (mInstallLock) {
16898                        destroyAppDataLI(volumeUuid, packageName, userId,
16899                                Installer.FLAG_DE_STORAGE);
16900                    }
16901                }
16902            }
16903        }
16904
16905        // Ensure that data directories are ready to roll for all packages
16906        // installed for this volume and user
16907        final List<PackageSetting> packages;
16908        synchronized (mPackages) {
16909            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16910        }
16911        int preparedCount = 0;
16912        for (PackageSetting ps : packages) {
16913            final String packageName = ps.name;
16914            if (ps.pkg == null) {
16915                Slog.w(TAG, "Odd, missing scanned package " + packageName);
16916                // TODO: might be due to legacy ASEC apps; we should circle back
16917                // and reconcile again once they're scanned
16918                continue;
16919            }
16920
16921            if (ps.getInstalled(userId)) {
16922                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
16923                preparedCount++;
16924            }
16925        }
16926
16927        if (restoreconNeeded) {
16928            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16929                SELinuxMMAC.setRestoreconDone(ceDir);
16930            }
16931            if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16932                SELinuxMMAC.setRestoreconDone(deDir);
16933            }
16934        }
16935
16936        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
16937                + " packages; restoreconNeeded was " + restoreconNeeded);
16938    }
16939
16940    /**
16941     * Prepare app data for the given app just after it was installed or
16942     * upgraded. This method carefully only touches users that it's installed
16943     * for, and it forces a restorecon to handle any seinfo changes.
16944     * <p>
16945     * Verifies that directories exist and that ownership and labeling is
16946     * correct for all installed apps. If there is an ownership mismatch, it
16947     * will try recovering system apps by wiping data; third-party app data is
16948     * left intact.
16949     */
16950    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
16951        final PackageSetting ps;
16952        synchronized (mPackages) {
16953            ps = mSettings.mPackages.get(pkg.packageName);
16954        }
16955
16956        final UserManager um = mContext.getSystemService(UserManager.class);
16957        for (UserInfo user : um.getUsers()) {
16958            final int flags;
16959            if (um.isUserUnlocked(user.id)) {
16960                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
16961            } else if (um.isUserRunning(user.id)) {
16962                flags = Installer.FLAG_DE_STORAGE;
16963            } else {
16964                continue;
16965            }
16966
16967            if (ps.getInstalled(user.id)) {
16968                // Whenever an app changes, force a restorecon of its data
16969                // TODO: when user data is locked, mark that we're still dirty
16970                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
16971            }
16972        }
16973    }
16974
16975    /**
16976     * Prepare app data for the given app.
16977     * <p>
16978     * Verifies that directories exist and that ownership and labeling is
16979     * correct for all installed apps. If there is an ownership mismatch, this
16980     * will try recovering system apps by wiping data; third-party app data is
16981     * left intact.
16982     */
16983    private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags,
16984            PackageParser.Package pkg, boolean restoreconNeeded) {
16985        if (DEBUG_APP_DATA) {
16986            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
16987                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
16988        }
16989
16990        final String packageName = pkg.packageName;
16991        final ApplicationInfo app = pkg.applicationInfo;
16992        final int appId = UserHandle.getAppId(app.uid);
16993
16994        Preconditions.checkNotNull(app.seinfo);
16995
16996        synchronized (mInstallLock) {
16997            try {
16998                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
16999                        appId, app.seinfo, app.targetSdkVersion);
17000            } catch (InstallerException e) {
17001                if (app.isSystemApp()) {
17002                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17003                            + ", but trying to recover: " + e);
17004                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17005                    try {
17006                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17007                                appId, app.seinfo, app.targetSdkVersion);
17008                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17009                    } catch (InstallerException e2) {
17010                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17011                    }
17012                } else {
17013                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17014                }
17015            }
17016
17017            if (restoreconNeeded) {
17018                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17019            }
17020
17021            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17022                // Create a native library symlink only if we have native libraries
17023                // and if the native libraries are 32 bit libraries. We do not provide
17024                // this symlink for 64 bit libraries.
17025                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17026                    final String nativeLibPath = app.nativeLibraryDir;
17027                    try {
17028                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17029                                nativeLibPath, userId);
17030                    } catch (InstallerException e) {
17031                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17032                    }
17033                }
17034            }
17035        }
17036    }
17037
17038    private void unfreezePackage(String packageName) {
17039        synchronized (mPackages) {
17040            final PackageSetting ps = mSettings.mPackages.get(packageName);
17041            if (ps != null) {
17042                ps.frozen = false;
17043            }
17044        }
17045    }
17046
17047    @Override
17048    public int movePackage(final String packageName, final String volumeUuid) {
17049        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17050
17051        final int moveId = mNextMoveId.getAndIncrement();
17052        mHandler.post(new Runnable() {
17053            @Override
17054            public void run() {
17055                try {
17056                    movePackageInternal(packageName, volumeUuid, moveId);
17057                } catch (PackageManagerException e) {
17058                    Slog.w(TAG, "Failed to move " + packageName, e);
17059                    mMoveCallbacks.notifyStatusChanged(moveId,
17060                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17061                }
17062            }
17063        });
17064        return moveId;
17065    }
17066
17067    private void movePackageInternal(final String packageName, final String volumeUuid,
17068            final int moveId) throws PackageManagerException {
17069        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17070        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17071        final PackageManager pm = mContext.getPackageManager();
17072
17073        final boolean currentAsec;
17074        final String currentVolumeUuid;
17075        final File codeFile;
17076        final String installerPackageName;
17077        final String packageAbiOverride;
17078        final int appId;
17079        final String seinfo;
17080        final String label;
17081        final int targetSdkVersion;
17082
17083        // reader
17084        synchronized (mPackages) {
17085            final PackageParser.Package pkg = mPackages.get(packageName);
17086            final PackageSetting ps = mSettings.mPackages.get(packageName);
17087            if (pkg == null || ps == null) {
17088                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17089            }
17090
17091            if (pkg.applicationInfo.isSystemApp()) {
17092                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17093                        "Cannot move system application");
17094            }
17095
17096            if (pkg.applicationInfo.isExternalAsec()) {
17097                currentAsec = true;
17098                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17099            } else if (pkg.applicationInfo.isForwardLocked()) {
17100                currentAsec = true;
17101                currentVolumeUuid = "forward_locked";
17102            } else {
17103                currentAsec = false;
17104                currentVolumeUuid = ps.volumeUuid;
17105
17106                final File probe = new File(pkg.codePath);
17107                final File probeOat = new File(probe, "oat");
17108                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17109                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17110                            "Move only supported for modern cluster style installs");
17111                }
17112            }
17113
17114            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17115                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17116                        "Package already moved to " + volumeUuid);
17117            }
17118
17119            if (ps.frozen) {
17120                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17121                        "Failed to move already frozen package");
17122            }
17123            ps.frozen = true;
17124
17125            codeFile = new File(pkg.codePath);
17126            installerPackageName = ps.installerPackageName;
17127            packageAbiOverride = ps.cpuAbiOverrideString;
17128            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17129            seinfo = pkg.applicationInfo.seinfo;
17130            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17131            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17132        }
17133
17134        // Now that we're guarded by frozen state, kill app during move
17135        final long token = Binder.clearCallingIdentity();
17136        try {
17137            killApplication(packageName, appId, "move pkg");
17138        } finally {
17139            Binder.restoreCallingIdentity(token);
17140        }
17141
17142        final Bundle extras = new Bundle();
17143        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17144        extras.putString(Intent.EXTRA_TITLE, label);
17145        mMoveCallbacks.notifyCreated(moveId, extras);
17146
17147        int installFlags;
17148        final boolean moveCompleteApp;
17149        final File measurePath;
17150
17151        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17152            installFlags = INSTALL_INTERNAL;
17153            moveCompleteApp = !currentAsec;
17154            measurePath = Environment.getDataAppDirectory(volumeUuid);
17155        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17156            installFlags = INSTALL_EXTERNAL;
17157            moveCompleteApp = false;
17158            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17159        } else {
17160            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17161            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17162                    || !volume.isMountedWritable()) {
17163                unfreezePackage(packageName);
17164                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17165                        "Move location not mounted private volume");
17166            }
17167
17168            Preconditions.checkState(!currentAsec);
17169
17170            installFlags = INSTALL_INTERNAL;
17171            moveCompleteApp = true;
17172            measurePath = Environment.getDataAppDirectory(volumeUuid);
17173        }
17174
17175        final PackageStats stats = new PackageStats(null, -1);
17176        synchronized (mInstaller) {
17177            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17178                unfreezePackage(packageName);
17179                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17180                        "Failed to measure package size");
17181            }
17182        }
17183
17184        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17185                + stats.dataSize);
17186
17187        final long startFreeBytes = measurePath.getFreeSpace();
17188        final long sizeBytes;
17189        if (moveCompleteApp) {
17190            sizeBytes = stats.codeSize + stats.dataSize;
17191        } else {
17192            sizeBytes = stats.codeSize;
17193        }
17194
17195        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17196            unfreezePackage(packageName);
17197            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17198                    "Not enough free space to move");
17199        }
17200
17201        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17202
17203        final CountDownLatch installedLatch = new CountDownLatch(1);
17204        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17205            @Override
17206            public void onUserActionRequired(Intent intent) throws RemoteException {
17207                throw new IllegalStateException();
17208            }
17209
17210            @Override
17211            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17212                    Bundle extras) throws RemoteException {
17213                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17214                        + PackageManager.installStatusToString(returnCode, msg));
17215
17216                installedLatch.countDown();
17217
17218                // Regardless of success or failure of the move operation,
17219                // always unfreeze the package
17220                unfreezePackage(packageName);
17221
17222                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17223                switch (status) {
17224                    case PackageInstaller.STATUS_SUCCESS:
17225                        mMoveCallbacks.notifyStatusChanged(moveId,
17226                                PackageManager.MOVE_SUCCEEDED);
17227                        break;
17228                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17229                        mMoveCallbacks.notifyStatusChanged(moveId,
17230                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17231                        break;
17232                    default:
17233                        mMoveCallbacks.notifyStatusChanged(moveId,
17234                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17235                        break;
17236                }
17237            }
17238        };
17239
17240        final MoveInfo move;
17241        if (moveCompleteApp) {
17242            // Kick off a thread to report progress estimates
17243            new Thread() {
17244                @Override
17245                public void run() {
17246                    while (true) {
17247                        try {
17248                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17249                                break;
17250                            }
17251                        } catch (InterruptedException ignored) {
17252                        }
17253
17254                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17255                        final int progress = 10 + (int) MathUtils.constrain(
17256                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17257                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17258                    }
17259                }
17260            }.start();
17261
17262            final String dataAppName = codeFile.getName();
17263            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17264                    dataAppName, appId, seinfo, targetSdkVersion);
17265        } else {
17266            move = null;
17267        }
17268
17269        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17270
17271        final Message msg = mHandler.obtainMessage(INIT_COPY);
17272        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17273        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17274                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17275        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17276        msg.obj = params;
17277
17278        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17279                System.identityHashCode(msg.obj));
17280        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17281                System.identityHashCode(msg.obj));
17282
17283        mHandler.sendMessage(msg);
17284    }
17285
17286    @Override
17287    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17288        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17289
17290        final int realMoveId = mNextMoveId.getAndIncrement();
17291        final Bundle extras = new Bundle();
17292        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17293        mMoveCallbacks.notifyCreated(realMoveId, extras);
17294
17295        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17296            @Override
17297            public void onCreated(int moveId, Bundle extras) {
17298                // Ignored
17299            }
17300
17301            @Override
17302            public void onStatusChanged(int moveId, int status, long estMillis) {
17303                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17304            }
17305        };
17306
17307        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17308        storage.setPrimaryStorageUuid(volumeUuid, callback);
17309        return realMoveId;
17310    }
17311
17312    @Override
17313    public int getMoveStatus(int moveId) {
17314        mContext.enforceCallingOrSelfPermission(
17315                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17316        return mMoveCallbacks.mLastStatus.get(moveId);
17317    }
17318
17319    @Override
17320    public void registerMoveCallback(IPackageMoveObserver callback) {
17321        mContext.enforceCallingOrSelfPermission(
17322                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17323        mMoveCallbacks.register(callback);
17324    }
17325
17326    @Override
17327    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17328        mContext.enforceCallingOrSelfPermission(
17329                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17330        mMoveCallbacks.unregister(callback);
17331    }
17332
17333    @Override
17334    public boolean setInstallLocation(int loc) {
17335        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17336                null);
17337        if (getInstallLocation() == loc) {
17338            return true;
17339        }
17340        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17341                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17342            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17343                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17344            return true;
17345        }
17346        return false;
17347   }
17348
17349    @Override
17350    public int getInstallLocation() {
17351        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17352                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17353                PackageHelper.APP_INSTALL_AUTO);
17354    }
17355
17356    /** Called by UserManagerService */
17357    void cleanUpUser(UserManagerService userManager, int userHandle) {
17358        synchronized (mPackages) {
17359            mDirtyUsers.remove(userHandle);
17360            mUserNeedsBadging.delete(userHandle);
17361            mSettings.removeUserLPw(userHandle);
17362            mPendingBroadcasts.remove(userHandle);
17363            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17364        }
17365        synchronized (mInstallLock) {
17366            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17367            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17368                final String volumeUuid = vol.getFsUuid();
17369                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17370                try {
17371                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17372                } catch (InstallerException e) {
17373                    Slog.w(TAG, "Failed to remove user data", e);
17374                }
17375            }
17376            synchronized (mPackages) {
17377                removeUnusedPackagesLILPw(userManager, userHandle);
17378            }
17379        }
17380    }
17381
17382    /**
17383     * We're removing userHandle and would like to remove any downloaded packages
17384     * that are no longer in use by any other user.
17385     * @param userHandle the user being removed
17386     */
17387    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17388        final boolean DEBUG_CLEAN_APKS = false;
17389        int [] users = userManager.getUserIds();
17390        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17391        while (psit.hasNext()) {
17392            PackageSetting ps = psit.next();
17393            if (ps.pkg == null) {
17394                continue;
17395            }
17396            final String packageName = ps.pkg.packageName;
17397            // Skip over if system app
17398            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17399                continue;
17400            }
17401            if (DEBUG_CLEAN_APKS) {
17402                Slog.i(TAG, "Checking package " + packageName);
17403            }
17404            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17405            if (keep) {
17406                if (DEBUG_CLEAN_APKS) {
17407                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17408                }
17409            } else {
17410                for (int i = 0; i < users.length; i++) {
17411                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17412                        keep = true;
17413                        if (DEBUG_CLEAN_APKS) {
17414                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17415                                    + users[i]);
17416                        }
17417                        break;
17418                    }
17419                }
17420            }
17421            if (!keep) {
17422                if (DEBUG_CLEAN_APKS) {
17423                    Slog.i(TAG, "  Removing package " + packageName);
17424                }
17425                mHandler.post(new Runnable() {
17426                    public void run() {
17427                        deletePackageX(packageName, userHandle, 0);
17428                    } //end run
17429                });
17430            }
17431        }
17432    }
17433
17434    /** Called by UserManagerService */
17435    void createNewUser(int userHandle) {
17436        synchronized (mInstallLock) {
17437            try {
17438                mInstaller.createUserConfig(userHandle);
17439            } catch (InstallerException e) {
17440                Slog.w(TAG, "Failed to create user config", e);
17441            }
17442            mSettings.createNewUserLI(this, mInstaller, userHandle);
17443        }
17444        synchronized (mPackages) {
17445            applyFactoryDefaultBrowserLPw(userHandle);
17446            primeDomainVerificationsLPw(userHandle);
17447        }
17448    }
17449
17450    void newUserCreated(final int userHandle) {
17451        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17452        // If permission review for legacy apps is required, we represent
17453        // dagerous permissions for such apps as always granted runtime
17454        // permissions to keep per user flag state whether review is needed.
17455        // Hence, if a new user is added we have to propagate dangerous
17456        // permission grants for these legacy apps.
17457        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17458            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17459                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17460        }
17461    }
17462
17463    @Override
17464    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17465        mContext.enforceCallingOrSelfPermission(
17466                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17467                "Only package verification agents can read the verifier device identity");
17468
17469        synchronized (mPackages) {
17470            return mSettings.getVerifierDeviceIdentityLPw();
17471        }
17472    }
17473
17474    @Override
17475    public void setPermissionEnforced(String permission, boolean enforced) {
17476        // TODO: Now that we no longer change GID for storage, this should to away.
17477        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17478                "setPermissionEnforced");
17479        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17480            synchronized (mPackages) {
17481                if (mSettings.mReadExternalStorageEnforced == null
17482                        || mSettings.mReadExternalStorageEnforced != enforced) {
17483                    mSettings.mReadExternalStorageEnforced = enforced;
17484                    mSettings.writeLPr();
17485                }
17486            }
17487            // kill any non-foreground processes so we restart them and
17488            // grant/revoke the GID.
17489            final IActivityManager am = ActivityManagerNative.getDefault();
17490            if (am != null) {
17491                final long token = Binder.clearCallingIdentity();
17492                try {
17493                    am.killProcessesBelowForeground("setPermissionEnforcement");
17494                } catch (RemoteException e) {
17495                } finally {
17496                    Binder.restoreCallingIdentity(token);
17497                }
17498            }
17499        } else {
17500            throw new IllegalArgumentException("No selective enforcement for " + permission);
17501        }
17502    }
17503
17504    @Override
17505    @Deprecated
17506    public boolean isPermissionEnforced(String permission) {
17507        return true;
17508    }
17509
17510    @Override
17511    public boolean isStorageLow() {
17512        final long token = Binder.clearCallingIdentity();
17513        try {
17514            final DeviceStorageMonitorInternal
17515                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17516            if (dsm != null) {
17517                return dsm.isMemoryLow();
17518            } else {
17519                return false;
17520            }
17521        } finally {
17522            Binder.restoreCallingIdentity(token);
17523        }
17524    }
17525
17526    @Override
17527    public IPackageInstaller getPackageInstaller() {
17528        return mInstallerService;
17529    }
17530
17531    private boolean userNeedsBadging(int userId) {
17532        int index = mUserNeedsBadging.indexOfKey(userId);
17533        if (index < 0) {
17534            final UserInfo userInfo;
17535            final long token = Binder.clearCallingIdentity();
17536            try {
17537                userInfo = sUserManager.getUserInfo(userId);
17538            } finally {
17539                Binder.restoreCallingIdentity(token);
17540            }
17541            final boolean b;
17542            if (userInfo != null && userInfo.isManagedProfile()) {
17543                b = true;
17544            } else {
17545                b = false;
17546            }
17547            mUserNeedsBadging.put(userId, b);
17548            return b;
17549        }
17550        return mUserNeedsBadging.valueAt(index);
17551    }
17552
17553    @Override
17554    public KeySet getKeySetByAlias(String packageName, String alias) {
17555        if (packageName == null || alias == null) {
17556            return null;
17557        }
17558        synchronized(mPackages) {
17559            final PackageParser.Package pkg = mPackages.get(packageName);
17560            if (pkg == null) {
17561                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17562                throw new IllegalArgumentException("Unknown package: " + packageName);
17563            }
17564            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17565            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17566        }
17567    }
17568
17569    @Override
17570    public KeySet getSigningKeySet(String packageName) {
17571        if (packageName == null) {
17572            return null;
17573        }
17574        synchronized(mPackages) {
17575            final PackageParser.Package pkg = mPackages.get(packageName);
17576            if (pkg == null) {
17577                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17578                throw new IllegalArgumentException("Unknown package: " + packageName);
17579            }
17580            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17581                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17582                throw new SecurityException("May not access signing KeySet of other apps.");
17583            }
17584            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17585            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17586        }
17587    }
17588
17589    @Override
17590    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17591        if (packageName == null || ks == null) {
17592            return false;
17593        }
17594        synchronized(mPackages) {
17595            final PackageParser.Package pkg = mPackages.get(packageName);
17596            if (pkg == null) {
17597                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17598                throw new IllegalArgumentException("Unknown package: " + packageName);
17599            }
17600            IBinder ksh = ks.getToken();
17601            if (ksh instanceof KeySetHandle) {
17602                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17603                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17604            }
17605            return false;
17606        }
17607    }
17608
17609    @Override
17610    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17611        if (packageName == null || ks == null) {
17612            return false;
17613        }
17614        synchronized(mPackages) {
17615            final PackageParser.Package pkg = mPackages.get(packageName);
17616            if (pkg == null) {
17617                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17618                throw new IllegalArgumentException("Unknown package: " + packageName);
17619            }
17620            IBinder ksh = ks.getToken();
17621            if (ksh instanceof KeySetHandle) {
17622                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17623                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17624            }
17625            return false;
17626        }
17627    }
17628
17629    private void deletePackageIfUnusedLPr(final String packageName) {
17630        PackageSetting ps = mSettings.mPackages.get(packageName);
17631        if (ps == null) {
17632            return;
17633        }
17634        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17635            // TODO Implement atomic delete if package is unused
17636            // It is currently possible that the package will be deleted even if it is installed
17637            // after this method returns.
17638            mHandler.post(new Runnable() {
17639                public void run() {
17640                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17641                }
17642            });
17643        }
17644    }
17645
17646    /**
17647     * Check and throw if the given before/after packages would be considered a
17648     * downgrade.
17649     */
17650    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17651            throws PackageManagerException {
17652        if (after.versionCode < before.mVersionCode) {
17653            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17654                    "Update version code " + after.versionCode + " is older than current "
17655                    + before.mVersionCode);
17656        } else if (after.versionCode == before.mVersionCode) {
17657            if (after.baseRevisionCode < before.baseRevisionCode) {
17658                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17659                        "Update base revision code " + after.baseRevisionCode
17660                        + " is older than current " + before.baseRevisionCode);
17661            }
17662
17663            if (!ArrayUtils.isEmpty(after.splitNames)) {
17664                for (int i = 0; i < after.splitNames.length; i++) {
17665                    final String splitName = after.splitNames[i];
17666                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17667                    if (j != -1) {
17668                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17669                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17670                                    "Update split " + splitName + " revision code "
17671                                    + after.splitRevisionCodes[i] + " is older than current "
17672                                    + before.splitRevisionCodes[j]);
17673                        }
17674                    }
17675                }
17676            }
17677        }
17678    }
17679
17680    private static class MoveCallbacks extends Handler {
17681        private static final int MSG_CREATED = 1;
17682        private static final int MSG_STATUS_CHANGED = 2;
17683
17684        private final RemoteCallbackList<IPackageMoveObserver>
17685                mCallbacks = new RemoteCallbackList<>();
17686
17687        private final SparseIntArray mLastStatus = new SparseIntArray();
17688
17689        public MoveCallbacks(Looper looper) {
17690            super(looper);
17691        }
17692
17693        public void register(IPackageMoveObserver callback) {
17694            mCallbacks.register(callback);
17695        }
17696
17697        public void unregister(IPackageMoveObserver callback) {
17698            mCallbacks.unregister(callback);
17699        }
17700
17701        @Override
17702        public void handleMessage(Message msg) {
17703            final SomeArgs args = (SomeArgs) msg.obj;
17704            final int n = mCallbacks.beginBroadcast();
17705            for (int i = 0; i < n; i++) {
17706                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17707                try {
17708                    invokeCallback(callback, msg.what, args);
17709                } catch (RemoteException ignored) {
17710                }
17711            }
17712            mCallbacks.finishBroadcast();
17713            args.recycle();
17714        }
17715
17716        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17717                throws RemoteException {
17718            switch (what) {
17719                case MSG_CREATED: {
17720                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17721                    break;
17722                }
17723                case MSG_STATUS_CHANGED: {
17724                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17725                    break;
17726                }
17727            }
17728        }
17729
17730        private void notifyCreated(int moveId, Bundle extras) {
17731            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17732
17733            final SomeArgs args = SomeArgs.obtain();
17734            args.argi1 = moveId;
17735            args.arg2 = extras;
17736            obtainMessage(MSG_CREATED, args).sendToTarget();
17737        }
17738
17739        private void notifyStatusChanged(int moveId, int status) {
17740            notifyStatusChanged(moveId, status, -1);
17741        }
17742
17743        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17744            Slog.v(TAG, "Move " + moveId + " status " + status);
17745
17746            final SomeArgs args = SomeArgs.obtain();
17747            args.argi1 = moveId;
17748            args.argi2 = status;
17749            args.arg3 = estMillis;
17750            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17751
17752            synchronized (mLastStatus) {
17753                mLastStatus.put(moveId, status);
17754            }
17755        }
17756    }
17757
17758    private final static class OnPermissionChangeListeners extends Handler {
17759        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17760
17761        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17762                new RemoteCallbackList<>();
17763
17764        public OnPermissionChangeListeners(Looper looper) {
17765            super(looper);
17766        }
17767
17768        @Override
17769        public void handleMessage(Message msg) {
17770            switch (msg.what) {
17771                case MSG_ON_PERMISSIONS_CHANGED: {
17772                    final int uid = msg.arg1;
17773                    handleOnPermissionsChanged(uid);
17774                } break;
17775            }
17776        }
17777
17778        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17779            mPermissionListeners.register(listener);
17780
17781        }
17782
17783        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17784            mPermissionListeners.unregister(listener);
17785        }
17786
17787        public void onPermissionsChanged(int uid) {
17788            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17789                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17790            }
17791        }
17792
17793        private void handleOnPermissionsChanged(int uid) {
17794            final int count = mPermissionListeners.beginBroadcast();
17795            try {
17796                for (int i = 0; i < count; i++) {
17797                    IOnPermissionsChangeListener callback = mPermissionListeners
17798                            .getBroadcastItem(i);
17799                    try {
17800                        callback.onPermissionsChanged(uid);
17801                    } catch (RemoteException e) {
17802                        Log.e(TAG, "Permission listener is dead", e);
17803                    }
17804                }
17805            } finally {
17806                mPermissionListeners.finishBroadcast();
17807            }
17808        }
17809    }
17810
17811    private class PackageManagerInternalImpl extends PackageManagerInternal {
17812        @Override
17813        public void setLocationPackagesProvider(PackagesProvider provider) {
17814            synchronized (mPackages) {
17815                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17816            }
17817        }
17818
17819        @Override
17820        public void setImePackagesProvider(PackagesProvider provider) {
17821            synchronized (mPackages) {
17822                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17823            }
17824        }
17825
17826        @Override
17827        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17828            synchronized (mPackages) {
17829                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17830            }
17831        }
17832
17833        @Override
17834        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17835            synchronized (mPackages) {
17836                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17837            }
17838        }
17839
17840        @Override
17841        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17842            synchronized (mPackages) {
17843                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17844            }
17845        }
17846
17847        @Override
17848        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17849            synchronized (mPackages) {
17850                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17851            }
17852        }
17853
17854        @Override
17855        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17856            synchronized (mPackages) {
17857                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17858            }
17859        }
17860
17861        @Override
17862        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17863            synchronized (mPackages) {
17864                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17865                        packageName, userId);
17866            }
17867        }
17868
17869        @Override
17870        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17871            synchronized (mPackages) {
17872                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17873                        packageName, userId);
17874            }
17875        }
17876
17877        @Override
17878        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17879            synchronized (mPackages) {
17880                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17881                        packageName, userId);
17882            }
17883        }
17884
17885        @Override
17886        public void setKeepUninstalledPackages(final List<String> packageList) {
17887            Preconditions.checkNotNull(packageList);
17888            List<String> removedFromList = null;
17889            synchronized (mPackages) {
17890                if (mKeepUninstalledPackages != null) {
17891                    final int packagesCount = mKeepUninstalledPackages.size();
17892                    for (int i = 0; i < packagesCount; i++) {
17893                        String oldPackage = mKeepUninstalledPackages.get(i);
17894                        if (packageList != null && packageList.contains(oldPackage)) {
17895                            continue;
17896                        }
17897                        if (removedFromList == null) {
17898                            removedFromList = new ArrayList<>();
17899                        }
17900                        removedFromList.add(oldPackage);
17901                    }
17902                }
17903                mKeepUninstalledPackages = new ArrayList<>(packageList);
17904                if (removedFromList != null) {
17905                    final int removedCount = removedFromList.size();
17906                    for (int i = 0; i < removedCount; i++) {
17907                        deletePackageIfUnusedLPr(removedFromList.get(i));
17908                    }
17909                }
17910            }
17911        }
17912
17913        @Override
17914        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17915            synchronized (mPackages) {
17916                // If we do not support permission review, done.
17917                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17918                    return false;
17919                }
17920
17921                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17922                if (packageSetting == null) {
17923                    return false;
17924                }
17925
17926                // Permission review applies only to apps not supporting the new permission model.
17927                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17928                    return false;
17929                }
17930
17931                // Legacy apps have the permission and get user consent on launch.
17932                PermissionsState permissionsState = packageSetting.getPermissionsState();
17933                return permissionsState.isPermissionReviewRequired(userId);
17934            }
17935        }
17936    }
17937
17938    @Override
17939    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17940        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17941        synchronized (mPackages) {
17942            final long identity = Binder.clearCallingIdentity();
17943            try {
17944                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17945                        packageNames, userId);
17946            } finally {
17947                Binder.restoreCallingIdentity(identity);
17948            }
17949        }
17950    }
17951
17952    private static void enforceSystemOrPhoneCaller(String tag) {
17953        int callingUid = Binder.getCallingUid();
17954        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17955            throw new SecurityException(
17956                    "Cannot call " + tag + " from UID " + callingUid);
17957        }
17958    }
17959}
17960