PackageManagerService.java revision 12cde00dc03ec802801b8fd7611c1706ab7d4363
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                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2097                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2098                            }
2099                        } catch (FileNotFoundException e) {
2100                            Slog.w(TAG, "Library not found: " + lib);
2101                        } catch (IOException | InstallerException e) {
2102                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2103                                    + e.getMessage());
2104                        }
2105                    }
2106                }
2107            }
2108
2109            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2110
2111            final VersionInfo ver = mSettings.getInternalVersion();
2112            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2113            // when upgrading from pre-M, promote system app permissions from install to runtime
2114            mPromoteSystemApps =
2115                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2116
2117            // save off the names of pre-existing system packages prior to scanning; we don't
2118            // want to automatically grant runtime permissions for new system apps
2119            if (mPromoteSystemApps) {
2120                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2121                while (pkgSettingIter.hasNext()) {
2122                    PackageSetting ps = pkgSettingIter.next();
2123                    if (isSystemApp(ps)) {
2124                        mExistingSystemPackages.add(ps.name);
2125                    }
2126                }
2127            }
2128
2129            // Collect vendor overlay packages.
2130            // (Do this before scanning any apps.)
2131            // For security and version matching reason, only consider
2132            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2133            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2134            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2135                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2136
2137            // Find base frameworks (resource packages without code).
2138            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2139                    | PackageParser.PARSE_IS_SYSTEM_DIR
2140                    | PackageParser.PARSE_IS_PRIVILEGED,
2141                    scanFlags | SCAN_NO_DEX, 0);
2142
2143            // Collected privileged system packages.
2144            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2145            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2146                    | PackageParser.PARSE_IS_SYSTEM_DIR
2147                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2148
2149            // Collect ordinary system packages.
2150            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2151            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2152                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2153
2154            // Collect all vendor packages.
2155            File vendorAppDir = new File("/vendor/app");
2156            try {
2157                vendorAppDir = vendorAppDir.getCanonicalFile();
2158            } catch (IOException e) {
2159                // failed to look up canonical path, continue with original one
2160            }
2161            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2162                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2163
2164            // Collect all OEM packages.
2165            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2166            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2167                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2168
2169            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2170            try {
2171                mInstaller.moveFiles();
2172            } catch (InstallerException e) {
2173                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2174            }
2175
2176            // Prune any system packages that no longer exist.
2177            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2178            if (!mOnlyCore) {
2179                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2180                while (psit.hasNext()) {
2181                    PackageSetting ps = psit.next();
2182
2183                    /*
2184                     * If this is not a system app, it can't be a
2185                     * disable system app.
2186                     */
2187                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2188                        continue;
2189                    }
2190
2191                    /*
2192                     * If the package is scanned, it's not erased.
2193                     */
2194                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2195                    if (scannedPkg != null) {
2196                        /*
2197                         * If the system app is both scanned and in the
2198                         * disabled packages list, then it must have been
2199                         * added via OTA. Remove it from the currently
2200                         * scanned package so the previously user-installed
2201                         * application can be scanned.
2202                         */
2203                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2204                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2205                                    + ps.name + "; removing system app.  Last known codePath="
2206                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2207                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2208                                    + scannedPkg.mVersionCode);
2209                            removePackageLI(ps, true);
2210                            mExpectingBetter.put(ps.name, ps.codePath);
2211                        }
2212
2213                        continue;
2214                    }
2215
2216                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2217                        psit.remove();
2218                        logCriticalInfo(Log.WARN, "System package " + ps.name
2219                                + " no longer exists; wiping its data");
2220                        removeDataDirsLI(null, ps.name);
2221                    } else {
2222                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2223                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2224                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2225                        }
2226                    }
2227                }
2228            }
2229
2230            //look for any incomplete package installations
2231            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2232            //clean up list
2233            for(int i = 0; i < deletePkgsList.size(); i++) {
2234                //clean up here
2235                cleanupInstallFailedPackage(deletePkgsList.get(i));
2236            }
2237            //delete tmp files
2238            deleteTempPackageFiles();
2239
2240            // Remove any shared userIDs that have no associated packages
2241            mSettings.pruneSharedUsersLPw();
2242
2243            if (!mOnlyCore) {
2244                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2245                        SystemClock.uptimeMillis());
2246                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2247
2248                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2249                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2250
2251                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2252                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2253
2254                /**
2255                 * Remove disable package settings for any updated system
2256                 * apps that were removed via an OTA. If they're not a
2257                 * previously-updated app, remove them completely.
2258                 * Otherwise, just revoke their system-level permissions.
2259                 */
2260                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2261                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2262                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2263
2264                    String msg;
2265                    if (deletedPkg == null) {
2266                        msg = "Updated system package " + deletedAppName
2267                                + " no longer exists; wiping its data";
2268                        removeDataDirsLI(null, deletedAppName);
2269                    } else {
2270                        msg = "Updated system app + " + deletedAppName
2271                                + " no longer present; removing system privileges for "
2272                                + deletedAppName;
2273
2274                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2275
2276                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2277                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2278                    }
2279                    logCriticalInfo(Log.WARN, msg);
2280                }
2281
2282                /**
2283                 * Make sure all system apps that we expected to appear on
2284                 * the userdata partition actually showed up. If they never
2285                 * appeared, crawl back and revive the system version.
2286                 */
2287                for (int i = 0; i < mExpectingBetter.size(); i++) {
2288                    final String packageName = mExpectingBetter.keyAt(i);
2289                    if (!mPackages.containsKey(packageName)) {
2290                        final File scanFile = mExpectingBetter.valueAt(i);
2291
2292                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2293                                + " but never showed up; reverting to system");
2294
2295                        final int reparseFlags;
2296                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2297                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2298                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2299                                    | PackageParser.PARSE_IS_PRIVILEGED;
2300                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2301                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2302                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2303                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2304                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2305                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2306                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2307                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2308                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2309                        } else {
2310                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2311                            continue;
2312                        }
2313
2314                        mSettings.enableSystemPackageLPw(packageName);
2315
2316                        try {
2317                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2318                        } catch (PackageManagerException e) {
2319                            Slog.e(TAG, "Failed to parse original system package: "
2320                                    + e.getMessage());
2321                        }
2322                    }
2323                }
2324            }
2325            mExpectingBetter.clear();
2326
2327            // Now that we know all of the shared libraries, update all clients to have
2328            // the correct library paths.
2329            updateAllSharedLibrariesLPw();
2330
2331            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2332                // NOTE: We ignore potential failures here during a system scan (like
2333                // the rest of the commands above) because there's precious little we
2334                // can do about it. A settings error is reported, though.
2335                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2336                        false /* boot complete */);
2337            }
2338
2339            // Now that we know all the packages we are keeping,
2340            // read and update their last usage times.
2341            mPackageUsage.readLP();
2342
2343            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2344                    SystemClock.uptimeMillis());
2345            Slog.i(TAG, "Time to scan packages: "
2346                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2347                    + " seconds");
2348
2349            // If the platform SDK has changed since the last time we booted,
2350            // we need to re-grant app permission to catch any new ones that
2351            // appear.  This is really a hack, and means that apps can in some
2352            // cases get permissions that the user didn't initially explicitly
2353            // allow...  it would be nice to have some better way to handle
2354            // this situation.
2355            int updateFlags = UPDATE_PERMISSIONS_ALL;
2356            if (ver.sdkVersion != mSdkVersion) {
2357                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2358                        + mSdkVersion + "; regranting permissions for internal storage");
2359                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2360            }
2361            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2362            ver.sdkVersion = mSdkVersion;
2363
2364            // If this is the first boot or an update from pre-M, and it is a normal
2365            // boot, then we need to initialize the default preferred apps across
2366            // all defined users.
2367            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2368                for (UserInfo user : sUserManager.getUsers(true)) {
2369                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2370                    applyFactoryDefaultBrowserLPw(user.id);
2371                    primeDomainVerificationsLPw(user.id);
2372                }
2373            }
2374
2375            // Prepare storage for system user really early during boot,
2376            // since core system apps like SettingsProvider and SystemUI
2377            // can't wait for user to start
2378            final int flags;
2379            if (StorageManager.isFileBasedEncryptionEnabled()) {
2380                flags = Installer.FLAG_DE_STORAGE;
2381            } else {
2382                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
2383            }
2384            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2385
2386            // If this is first boot after an OTA, and a normal boot, then
2387            // we need to clear code cache directories.
2388            if (mIsUpgrade && !onlyCore) {
2389                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2390                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2391                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2392                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2393                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2394                    }
2395                }
2396                ver.fingerprint = Build.FINGERPRINT;
2397            }
2398
2399            checkDefaultBrowser();
2400
2401            // clear only after permissions and other defaults have been updated
2402            mExistingSystemPackages.clear();
2403            mPromoteSystemApps = false;
2404
2405            // All the changes are done during package scanning.
2406            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2407
2408            // can downgrade to reader
2409            mSettings.writeLPr();
2410
2411            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2412                    SystemClock.uptimeMillis());
2413
2414            if (!mOnlyCore) {
2415                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2416                mRequiredInstallerPackage = getRequiredInstallerLPr();
2417                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2418                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2419                        mIntentFilterVerifierComponent);
2420            } else {
2421                mRequiredVerifierPackage = null;
2422                mRequiredInstallerPackage = null;
2423                mIntentFilterVerifierComponent = null;
2424                mIntentFilterVerifier = null;
2425            }
2426
2427            mInstallerService = new PackageInstallerService(context, this);
2428
2429            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2430            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2431            // both the installer and resolver must be present to enable ephemeral
2432            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2433                if (DEBUG_EPHEMERAL) {
2434                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2435                            + " installer:" + ephemeralInstallerComponent);
2436                }
2437                mEphemeralResolverComponent = ephemeralResolverComponent;
2438                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2439                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2440                mEphemeralResolverConnection =
2441                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2442            } else {
2443                if (DEBUG_EPHEMERAL) {
2444                    final String missingComponent =
2445                            (ephemeralResolverComponent == null)
2446                            ? (ephemeralInstallerComponent == null)
2447                                    ? "resolver and installer"
2448                                    : "resolver"
2449                            : "installer";
2450                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2451                }
2452                mEphemeralResolverComponent = null;
2453                mEphemeralInstallerComponent = null;
2454                mEphemeralResolverConnection = null;
2455            }
2456
2457            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2458        } // synchronized (mPackages)
2459        } // synchronized (mInstallLock)
2460
2461        // Now after opening every single application zip, make sure they
2462        // are all flushed.  Not really needed, but keeps things nice and
2463        // tidy.
2464        Runtime.getRuntime().gc();
2465
2466        // The initial scanning above does many calls into installd while
2467        // holding the mPackages lock, but we're mostly interested in yelling
2468        // once we have a booted system.
2469        mInstaller.setWarnIfHeld(mPackages);
2470
2471        // Expose private service for system components to use.
2472        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2473    }
2474
2475    @Override
2476    public boolean isFirstBoot() {
2477        return !mRestoredSettings;
2478    }
2479
2480    @Override
2481    public boolean isOnlyCoreApps() {
2482        return mOnlyCore;
2483    }
2484
2485    @Override
2486    public boolean isUpgrade() {
2487        return mIsUpgrade;
2488    }
2489
2490    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2491        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2492
2493        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2494                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2495        if (matches.size() == 1) {
2496            return matches.get(0).getComponentInfo().packageName;
2497        } else {
2498            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2499            return null;
2500        }
2501    }
2502
2503    private @NonNull String getRequiredInstallerLPr() {
2504        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2505        intent.addCategory(Intent.CATEGORY_DEFAULT);
2506        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2507
2508        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2509                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2510        if (matches.size() == 1) {
2511            return matches.get(0).getComponentInfo().packageName;
2512        } else {
2513            throw new RuntimeException("There must be exactly one installer; found " + matches);
2514        }
2515    }
2516
2517    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2518        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2519
2520        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2521                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2522        ResolveInfo best = null;
2523        final int N = matches.size();
2524        for (int i = 0; i < N; i++) {
2525            final ResolveInfo cur = matches.get(i);
2526            final String packageName = cur.getComponentInfo().packageName;
2527            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2528                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2529                continue;
2530            }
2531
2532            if (best == null || cur.priority > best.priority) {
2533                best = cur;
2534            }
2535        }
2536
2537        if (best != null) {
2538            return best.getComponentInfo().getComponentName();
2539        } else {
2540            throw new RuntimeException("There must be at least one intent filter verifier");
2541        }
2542    }
2543
2544    private @Nullable ComponentName getEphemeralResolverLPr() {
2545        final String[] packageArray =
2546                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2547        if (packageArray.length == 0) {
2548            if (DEBUG_EPHEMERAL) {
2549                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2550            }
2551            return null;
2552        }
2553
2554        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2555        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2556                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2557
2558        final int N = resolvers.size();
2559        if (N == 0) {
2560            if (DEBUG_EPHEMERAL) {
2561                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2562            }
2563            return null;
2564        }
2565
2566        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2567        for (int i = 0; i < N; i++) {
2568            final ResolveInfo info = resolvers.get(i);
2569
2570            if (info.serviceInfo == null) {
2571                continue;
2572            }
2573
2574            final String packageName = info.serviceInfo.packageName;
2575            if (!possiblePackages.contains(packageName)) {
2576                if (DEBUG_EPHEMERAL) {
2577                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2578                            + " pkg: " + packageName + ", info:" + info);
2579                }
2580                continue;
2581            }
2582
2583            if (DEBUG_EPHEMERAL) {
2584                Slog.v(TAG, "Ephemeral resolver found;"
2585                        + " pkg: " + packageName + ", info:" + info);
2586            }
2587            return new ComponentName(packageName, info.serviceInfo.name);
2588        }
2589        if (DEBUG_EPHEMERAL) {
2590            Slog.v(TAG, "Ephemeral resolver NOT found");
2591        }
2592        return null;
2593    }
2594
2595    private @Nullable ComponentName getEphemeralInstallerLPr() {
2596        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2597        intent.addCategory(Intent.CATEGORY_DEFAULT);
2598        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2599
2600        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2601                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2602        if (matches.size() == 0) {
2603            return null;
2604        } else if (matches.size() == 1) {
2605            return matches.get(0).getComponentInfo().getComponentName();
2606        } else {
2607            throw new RuntimeException(
2608                    "There must be at most one ephemeral installer; found " + matches);
2609        }
2610    }
2611
2612    private void primeDomainVerificationsLPw(int userId) {
2613        if (DEBUG_DOMAIN_VERIFICATION) {
2614            Slog.d(TAG, "Priming domain verifications in user " + userId);
2615        }
2616
2617        SystemConfig systemConfig = SystemConfig.getInstance();
2618        ArraySet<String> packages = systemConfig.getLinkedApps();
2619        ArraySet<String> domains = new ArraySet<String>();
2620
2621        for (String packageName : packages) {
2622            PackageParser.Package pkg = mPackages.get(packageName);
2623            if (pkg != null) {
2624                if (!pkg.isSystemApp()) {
2625                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2626                    continue;
2627                }
2628
2629                domains.clear();
2630                for (PackageParser.Activity a : pkg.activities) {
2631                    for (ActivityIntentInfo filter : a.intents) {
2632                        if (hasValidDomains(filter)) {
2633                            domains.addAll(filter.getHostsList());
2634                        }
2635                    }
2636                }
2637
2638                if (domains.size() > 0) {
2639                    if (DEBUG_DOMAIN_VERIFICATION) {
2640                        Slog.v(TAG, "      + " + packageName);
2641                    }
2642                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2643                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2644                    // and then 'always' in the per-user state actually used for intent resolution.
2645                    final IntentFilterVerificationInfo ivi;
2646                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2647                            new ArrayList<String>(domains));
2648                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2649                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2650                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2651                } else {
2652                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2653                            + "' does not handle web links");
2654                }
2655            } else {
2656                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2657            }
2658        }
2659
2660        scheduleWritePackageRestrictionsLocked(userId);
2661        scheduleWriteSettingsLocked();
2662    }
2663
2664    private void applyFactoryDefaultBrowserLPw(int userId) {
2665        // The default browser app's package name is stored in a string resource,
2666        // with a product-specific overlay used for vendor customization.
2667        String browserPkg = mContext.getResources().getString(
2668                com.android.internal.R.string.default_browser);
2669        if (!TextUtils.isEmpty(browserPkg)) {
2670            // non-empty string => required to be a known package
2671            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2672            if (ps == null) {
2673                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2674                browserPkg = null;
2675            } else {
2676                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2677            }
2678        }
2679
2680        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2681        // default.  If there's more than one, just leave everything alone.
2682        if (browserPkg == null) {
2683            calculateDefaultBrowserLPw(userId);
2684        }
2685    }
2686
2687    private void calculateDefaultBrowserLPw(int userId) {
2688        List<String> allBrowsers = resolveAllBrowserApps(userId);
2689        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2690        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2691    }
2692
2693    private List<String> resolveAllBrowserApps(int userId) {
2694        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2695        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2696                PackageManager.MATCH_ALL, userId);
2697
2698        final int count = list.size();
2699        List<String> result = new ArrayList<String>(count);
2700        for (int i=0; i<count; i++) {
2701            ResolveInfo info = list.get(i);
2702            if (info.activityInfo == null
2703                    || !info.handleAllWebDataURI
2704                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2705                    || result.contains(info.activityInfo.packageName)) {
2706                continue;
2707            }
2708            result.add(info.activityInfo.packageName);
2709        }
2710
2711        return result;
2712    }
2713
2714    private boolean packageIsBrowser(String packageName, int userId) {
2715        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2716                PackageManager.MATCH_ALL, userId);
2717        final int N = list.size();
2718        for (int i = 0; i < N; i++) {
2719            ResolveInfo info = list.get(i);
2720            if (packageName.equals(info.activityInfo.packageName)) {
2721                return true;
2722            }
2723        }
2724        return false;
2725    }
2726
2727    private void checkDefaultBrowser() {
2728        final int myUserId = UserHandle.myUserId();
2729        final String packageName = getDefaultBrowserPackageName(myUserId);
2730        if (packageName != null) {
2731            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2732            if (info == null) {
2733                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2734                synchronized (mPackages) {
2735                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2736                }
2737            }
2738        }
2739    }
2740
2741    @Override
2742    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2743            throws RemoteException {
2744        try {
2745            return super.onTransact(code, data, reply, flags);
2746        } catch (RuntimeException e) {
2747            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2748                Slog.wtf(TAG, "Package Manager Crash", e);
2749            }
2750            throw e;
2751        }
2752    }
2753
2754    void cleanupInstallFailedPackage(PackageSetting ps) {
2755        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2756
2757        removeDataDirsLI(ps.volumeUuid, ps.name);
2758        if (ps.codePath != null) {
2759            removeCodePathLI(ps.codePath);
2760        }
2761        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2762            if (ps.resourcePath.isDirectory()) {
2763                FileUtils.deleteContents(ps.resourcePath);
2764            }
2765            ps.resourcePath.delete();
2766        }
2767        mSettings.removePackageLPw(ps.name);
2768    }
2769
2770    static int[] appendInts(int[] cur, int[] add) {
2771        if (add == null) return cur;
2772        if (cur == null) return add;
2773        final int N = add.length;
2774        for (int i=0; i<N; i++) {
2775            cur = appendInt(cur, add[i]);
2776        }
2777        return cur;
2778    }
2779
2780    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2781        if (!sUserManager.exists(userId)) return null;
2782        final PackageSetting ps = (PackageSetting) p.mExtras;
2783        if (ps == null) {
2784            return null;
2785        }
2786
2787        final PermissionsState permissionsState = ps.getPermissionsState();
2788
2789        final int[] gids = permissionsState.computeGids(userId);
2790        final Set<String> permissions = permissionsState.getPermissions(userId);
2791        final PackageUserState state = ps.readUserState(userId);
2792
2793        return PackageParser.generatePackageInfo(p, gids, flags,
2794                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2795    }
2796
2797    @Override
2798    public void checkPackageStartable(String packageName, int userId) {
2799        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2800
2801        synchronized (mPackages) {
2802            final PackageSetting ps = mSettings.mPackages.get(packageName);
2803            if (ps == null) {
2804                throw new SecurityException("Package " + packageName + " was not found!");
2805            }
2806
2807            if (ps.frozen) {
2808                throw new SecurityException("Package " + packageName + " is currently frozen!");
2809            }
2810
2811            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2812                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2813                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2814            }
2815        }
2816    }
2817
2818    @Override
2819    public boolean isPackageAvailable(String packageName, int userId) {
2820        if (!sUserManager.exists(userId)) return false;
2821        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2822        synchronized (mPackages) {
2823            PackageParser.Package p = mPackages.get(packageName);
2824            if (p != null) {
2825                final PackageSetting ps = (PackageSetting) p.mExtras;
2826                if (ps != null) {
2827                    final PackageUserState state = ps.readUserState(userId);
2828                    if (state != null) {
2829                        return PackageParser.isAvailable(state);
2830                    }
2831                }
2832            }
2833        }
2834        return false;
2835    }
2836
2837    @Override
2838    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2839        if (!sUserManager.exists(userId)) return null;
2840        flags = updateFlagsForPackage(flags, userId, packageName);
2841        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2842        // reader
2843        synchronized (mPackages) {
2844            PackageParser.Package p = mPackages.get(packageName);
2845            if (DEBUG_PACKAGE_INFO)
2846                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2847            if (p != null) {
2848                return generatePackageInfo(p, flags, userId);
2849            }
2850            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2851                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2852            }
2853        }
2854        return null;
2855    }
2856
2857    @Override
2858    public String[] currentToCanonicalPackageNames(String[] names) {
2859        String[] out = new String[names.length];
2860        // reader
2861        synchronized (mPackages) {
2862            for (int i=names.length-1; i>=0; i--) {
2863                PackageSetting ps = mSettings.mPackages.get(names[i]);
2864                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2865            }
2866        }
2867        return out;
2868    }
2869
2870    @Override
2871    public String[] canonicalToCurrentPackageNames(String[] names) {
2872        String[] out = new String[names.length];
2873        // reader
2874        synchronized (mPackages) {
2875            for (int i=names.length-1; i>=0; i--) {
2876                String cur = mSettings.mRenamedPackages.get(names[i]);
2877                out[i] = cur != null ? cur : names[i];
2878            }
2879        }
2880        return out;
2881    }
2882
2883    @Override
2884    public int getPackageUid(String packageName, int flags, int userId) {
2885        if (!sUserManager.exists(userId)) return -1;
2886        flags = updateFlagsForPackage(flags, userId, packageName);
2887        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2888
2889        // reader
2890        synchronized (mPackages) {
2891            final PackageParser.Package p = mPackages.get(packageName);
2892            if (p != null && p.isMatch(flags)) {
2893                return UserHandle.getUid(userId, p.applicationInfo.uid);
2894            }
2895            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2896                final PackageSetting ps = mSettings.mPackages.get(packageName);
2897                if (ps != null && ps.isMatch(flags)) {
2898                    return UserHandle.getUid(userId, ps.appId);
2899                }
2900            }
2901        }
2902
2903        return -1;
2904    }
2905
2906    @Override
2907    public int[] getPackageGids(String packageName, int flags, int userId) {
2908        if (!sUserManager.exists(userId)) return null;
2909        flags = updateFlagsForPackage(flags, userId, packageName);
2910        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2911                "getPackageGids");
2912
2913        // reader
2914        synchronized (mPackages) {
2915            final PackageParser.Package p = mPackages.get(packageName);
2916            if (p != null && p.isMatch(flags)) {
2917                PackageSetting ps = (PackageSetting) p.mExtras;
2918                return ps.getPermissionsState().computeGids(userId);
2919            }
2920            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2921                final PackageSetting ps = mSettings.mPackages.get(packageName);
2922                if (ps != null && ps.isMatch(flags)) {
2923                    return ps.getPermissionsState().computeGids(userId);
2924                }
2925            }
2926        }
2927
2928        return null;
2929    }
2930
2931    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2932        if (bp.perm != null) {
2933            return PackageParser.generatePermissionInfo(bp.perm, flags);
2934        }
2935        PermissionInfo pi = new PermissionInfo();
2936        pi.name = bp.name;
2937        pi.packageName = bp.sourcePackage;
2938        pi.nonLocalizedLabel = bp.name;
2939        pi.protectionLevel = bp.protectionLevel;
2940        return pi;
2941    }
2942
2943    @Override
2944    public PermissionInfo getPermissionInfo(String name, int flags) {
2945        // reader
2946        synchronized (mPackages) {
2947            final BasePermission p = mSettings.mPermissions.get(name);
2948            if (p != null) {
2949                return generatePermissionInfo(p, flags);
2950            }
2951            return null;
2952        }
2953    }
2954
2955    @Override
2956    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2957        // reader
2958        synchronized (mPackages) {
2959            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2960            for (BasePermission p : mSettings.mPermissions.values()) {
2961                if (group == null) {
2962                    if (p.perm == null || p.perm.info.group == null) {
2963                        out.add(generatePermissionInfo(p, flags));
2964                    }
2965                } else {
2966                    if (p.perm != null && group.equals(p.perm.info.group)) {
2967                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2968                    }
2969                }
2970            }
2971
2972            if (out.size() > 0) {
2973                return out;
2974            }
2975            return mPermissionGroups.containsKey(group) ? out : null;
2976        }
2977    }
2978
2979    @Override
2980    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2981        // reader
2982        synchronized (mPackages) {
2983            return PackageParser.generatePermissionGroupInfo(
2984                    mPermissionGroups.get(name), flags);
2985        }
2986    }
2987
2988    @Override
2989    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2990        // reader
2991        synchronized (mPackages) {
2992            final int N = mPermissionGroups.size();
2993            ArrayList<PermissionGroupInfo> out
2994                    = new ArrayList<PermissionGroupInfo>(N);
2995            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2996                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2997            }
2998            return out;
2999        }
3000    }
3001
3002    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3003            int userId) {
3004        if (!sUserManager.exists(userId)) return null;
3005        PackageSetting ps = mSettings.mPackages.get(packageName);
3006        if (ps != null) {
3007            if (ps.pkg == null) {
3008                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3009                        flags, userId);
3010                if (pInfo != null) {
3011                    return pInfo.applicationInfo;
3012                }
3013                return null;
3014            }
3015            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3016                    ps.readUserState(userId), userId);
3017        }
3018        return null;
3019    }
3020
3021    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3022            int userId) {
3023        if (!sUserManager.exists(userId)) return null;
3024        PackageSetting ps = mSettings.mPackages.get(packageName);
3025        if (ps != null) {
3026            PackageParser.Package pkg = ps.pkg;
3027            if (pkg == null) {
3028                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3029                    return null;
3030                }
3031                // Only data remains, so we aren't worried about code paths
3032                pkg = new PackageParser.Package(packageName);
3033                pkg.applicationInfo.packageName = packageName;
3034                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3035                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3036                pkg.applicationInfo.uid = ps.appId;
3037                pkg.applicationInfo.initForUser(userId);
3038                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3039                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3040            }
3041            return generatePackageInfo(pkg, flags, userId);
3042        }
3043        return null;
3044    }
3045
3046    @Override
3047    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3048        if (!sUserManager.exists(userId)) return null;
3049        flags = updateFlagsForApplication(flags, userId, packageName);
3050        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3051        // writer
3052        synchronized (mPackages) {
3053            PackageParser.Package p = mPackages.get(packageName);
3054            if (DEBUG_PACKAGE_INFO) Log.v(
3055                    TAG, "getApplicationInfo " + packageName
3056                    + ": " + p);
3057            if (p != null) {
3058                PackageSetting ps = mSettings.mPackages.get(packageName);
3059                if (ps == null) return null;
3060                // Note: isEnabledLP() does not apply here - always return info
3061                return PackageParser.generateApplicationInfo(
3062                        p, flags, ps.readUserState(userId), userId);
3063            }
3064            if ("android".equals(packageName)||"system".equals(packageName)) {
3065                return mAndroidApplication;
3066            }
3067            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3068                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3069            }
3070        }
3071        return null;
3072    }
3073
3074    @Override
3075    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3076            final IPackageDataObserver observer) {
3077        mContext.enforceCallingOrSelfPermission(
3078                android.Manifest.permission.CLEAR_APP_CACHE, null);
3079        // Queue up an async operation since clearing cache may take a little while.
3080        mHandler.post(new Runnable() {
3081            public void run() {
3082                mHandler.removeCallbacks(this);
3083                boolean success = true;
3084                synchronized (mInstallLock) {
3085                    try {
3086                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3087                    } catch (InstallerException e) {
3088                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3089                        success = false;
3090                    }
3091                }
3092                if (observer != null) {
3093                    try {
3094                        observer.onRemoveCompleted(null, success);
3095                    } catch (RemoteException e) {
3096                        Slog.w(TAG, "RemoveException when invoking call back");
3097                    }
3098                }
3099            }
3100        });
3101    }
3102
3103    @Override
3104    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3105            final IntentSender pi) {
3106        mContext.enforceCallingOrSelfPermission(
3107                android.Manifest.permission.CLEAR_APP_CACHE, null);
3108        // Queue up an async operation since clearing cache may take a little while.
3109        mHandler.post(new Runnable() {
3110            public void run() {
3111                mHandler.removeCallbacks(this);
3112                boolean success = true;
3113                synchronized (mInstallLock) {
3114                    try {
3115                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3116                    } catch (InstallerException e) {
3117                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3118                        success = false;
3119                    }
3120                }
3121                if(pi != null) {
3122                    try {
3123                        // Callback via pending intent
3124                        int code = success ? 1 : 0;
3125                        pi.sendIntent(null, code, null,
3126                                null, null);
3127                    } catch (SendIntentException e1) {
3128                        Slog.i(TAG, "Failed to send pending intent");
3129                    }
3130                }
3131            }
3132        });
3133    }
3134
3135    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3136        synchronized (mInstallLock) {
3137            try {
3138                mInstaller.freeCache(volumeUuid, freeStorageSize);
3139            } catch (InstallerException e) {
3140                throw new IOException("Failed to free enough space", e);
3141            }
3142        }
3143    }
3144
3145    /**
3146     * Return if the user key is currently unlocked.
3147     */
3148    private boolean isUserKeyUnlocked(int userId) {
3149        if (StorageManager.isFileBasedEncryptionEnabled()) {
3150            final IMountService mount = IMountService.Stub
3151                    .asInterface(ServiceManager.getService("mount"));
3152            if (mount == null) {
3153                Slog.w(TAG, "Early during boot, assuming locked");
3154                return false;
3155            }
3156            final long token = Binder.clearCallingIdentity();
3157            try {
3158                return mount.isUserKeyUnlocked(userId);
3159            } catch (RemoteException e) {
3160                throw e.rethrowAsRuntimeException();
3161            } finally {
3162                Binder.restoreCallingIdentity(token);
3163            }
3164        } else {
3165            return true;
3166        }
3167    }
3168
3169    /**
3170     * Update given flags based on encryption status of current user.
3171     */
3172    private int updateFlags(int flags, int userId) {
3173        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3174                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3175            // Caller expressed an explicit opinion about what encryption
3176            // aware/unaware components they want to see, so fall through and
3177            // give them what they want
3178        } else {
3179            // Caller expressed no opinion, so match based on user state
3180            if (isUserKeyUnlocked(userId)) {
3181                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3182            } else {
3183                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3184            }
3185        }
3186
3187        // Safe mode means we should ignore any third-party apps
3188        if (mSafeMode) {
3189            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3190        }
3191
3192        return flags;
3193    }
3194
3195    /**
3196     * Update given flags when being used to request {@link PackageInfo}.
3197     */
3198    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3199        boolean triaged = true;
3200        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3201                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3202            // Caller is asking for component details, so they'd better be
3203            // asking for specific encryption matching behavior, or be triaged
3204            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3205                    | PackageManager.MATCH_ENCRYPTION_AWARE
3206                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3207                triaged = false;
3208            }
3209        }
3210        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3211                | PackageManager.MATCH_SYSTEM_ONLY
3212                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3213            triaged = false;
3214        }
3215        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3216            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3217                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3218        }
3219        return updateFlags(flags, userId);
3220    }
3221
3222    /**
3223     * Update given flags when being used to request {@link ApplicationInfo}.
3224     */
3225    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3226        return updateFlagsForPackage(flags, userId, cookie);
3227    }
3228
3229    /**
3230     * Update given flags when being used to request {@link ComponentInfo}.
3231     */
3232    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3233        if (cookie instanceof Intent) {
3234            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3235                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3236            }
3237        }
3238
3239        boolean triaged = true;
3240        // Caller is asking for component details, so they'd better be
3241        // asking for specific encryption matching behavior, or be triaged
3242        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3243                | PackageManager.MATCH_ENCRYPTION_AWARE
3244                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3245            triaged = false;
3246        }
3247        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3248            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3249                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3250        }
3251        return updateFlags(flags, userId);
3252    }
3253
3254    /**
3255     * Update given flags when being used to request {@link ResolveInfo}.
3256     */
3257    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3258        return updateFlagsForComponent(flags, userId, cookie);
3259    }
3260
3261    @Override
3262    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3263        if (!sUserManager.exists(userId)) return null;
3264        flags = updateFlagsForComponent(flags, userId, component);
3265        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3266        synchronized (mPackages) {
3267            PackageParser.Activity a = mActivities.mActivities.get(component);
3268
3269            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3270            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3271                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3272                if (ps == null) return null;
3273                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3274                        userId);
3275            }
3276            if (mResolveComponentName.equals(component)) {
3277                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3278                        new PackageUserState(), userId);
3279            }
3280        }
3281        return null;
3282    }
3283
3284    @Override
3285    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3286            String resolvedType) {
3287        synchronized (mPackages) {
3288            if (component.equals(mResolveComponentName)) {
3289                // The resolver supports EVERYTHING!
3290                return true;
3291            }
3292            PackageParser.Activity a = mActivities.mActivities.get(component);
3293            if (a == null) {
3294                return false;
3295            }
3296            for (int i=0; i<a.intents.size(); i++) {
3297                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3298                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3299                    return true;
3300                }
3301            }
3302            return false;
3303        }
3304    }
3305
3306    @Override
3307    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3308        if (!sUserManager.exists(userId)) return null;
3309        flags = updateFlagsForComponent(flags, userId, component);
3310        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3311        synchronized (mPackages) {
3312            PackageParser.Activity a = mReceivers.mActivities.get(component);
3313            if (DEBUG_PACKAGE_INFO) Log.v(
3314                TAG, "getReceiverInfo " + component + ": " + a);
3315            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3316                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3317                if (ps == null) return null;
3318                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3319                        userId);
3320            }
3321        }
3322        return null;
3323    }
3324
3325    @Override
3326    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3327        if (!sUserManager.exists(userId)) return null;
3328        flags = updateFlagsForComponent(flags, userId, component);
3329        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3330        synchronized (mPackages) {
3331            PackageParser.Service s = mServices.mServices.get(component);
3332            if (DEBUG_PACKAGE_INFO) Log.v(
3333                TAG, "getServiceInfo " + component + ": " + s);
3334            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3335                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3336                if (ps == null) return null;
3337                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3338                        userId);
3339            }
3340        }
3341        return null;
3342    }
3343
3344    @Override
3345    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3346        if (!sUserManager.exists(userId)) return null;
3347        flags = updateFlagsForComponent(flags, userId, component);
3348        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3349        synchronized (mPackages) {
3350            PackageParser.Provider p = mProviders.mProviders.get(component);
3351            if (DEBUG_PACKAGE_INFO) Log.v(
3352                TAG, "getProviderInfo " + component + ": " + p);
3353            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3354                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3355                if (ps == null) return null;
3356                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3357                        userId);
3358            }
3359        }
3360        return null;
3361    }
3362
3363    @Override
3364    public String[] getSystemSharedLibraryNames() {
3365        Set<String> libSet;
3366        synchronized (mPackages) {
3367            libSet = mSharedLibraries.keySet();
3368            int size = libSet.size();
3369            if (size > 0) {
3370                String[] libs = new String[size];
3371                libSet.toArray(libs);
3372                return libs;
3373            }
3374        }
3375        return null;
3376    }
3377
3378    /**
3379     * @hide
3380     */
3381    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3382        synchronized (mPackages) {
3383            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3384            if (lib != null && lib.apk != null) {
3385                return mPackages.get(lib.apk);
3386            }
3387        }
3388        return null;
3389    }
3390
3391    @Override
3392    public FeatureInfo[] getSystemAvailableFeatures() {
3393        Collection<FeatureInfo> featSet;
3394        synchronized (mPackages) {
3395            featSet = mAvailableFeatures.values();
3396            int size = featSet.size();
3397            if (size > 0) {
3398                FeatureInfo[] features = new FeatureInfo[size+1];
3399                featSet.toArray(features);
3400                FeatureInfo fi = new FeatureInfo();
3401                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3402                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3403                features[size] = fi;
3404                return features;
3405            }
3406        }
3407        return null;
3408    }
3409
3410    @Override
3411    public boolean hasSystemFeature(String name) {
3412        synchronized (mPackages) {
3413            return mAvailableFeatures.containsKey(name);
3414        }
3415    }
3416
3417    @Override
3418    public int checkPermission(String permName, String pkgName, int userId) {
3419        if (!sUserManager.exists(userId)) {
3420            return PackageManager.PERMISSION_DENIED;
3421        }
3422
3423        synchronized (mPackages) {
3424            final PackageParser.Package p = mPackages.get(pkgName);
3425            if (p != null && p.mExtras != null) {
3426                final PackageSetting ps = (PackageSetting) p.mExtras;
3427                final PermissionsState permissionsState = ps.getPermissionsState();
3428                if (permissionsState.hasPermission(permName, userId)) {
3429                    return PackageManager.PERMISSION_GRANTED;
3430                }
3431                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3432                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3433                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3434                    return PackageManager.PERMISSION_GRANTED;
3435                }
3436            }
3437        }
3438
3439        return PackageManager.PERMISSION_DENIED;
3440    }
3441
3442    @Override
3443    public int checkUidPermission(String permName, int uid) {
3444        final int userId = UserHandle.getUserId(uid);
3445
3446        if (!sUserManager.exists(userId)) {
3447            return PackageManager.PERMISSION_DENIED;
3448        }
3449
3450        synchronized (mPackages) {
3451            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3452            if (obj != null) {
3453                final SettingBase ps = (SettingBase) obj;
3454                final PermissionsState permissionsState = ps.getPermissionsState();
3455                if (permissionsState.hasPermission(permName, userId)) {
3456                    return PackageManager.PERMISSION_GRANTED;
3457                }
3458                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3459                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3460                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3461                    return PackageManager.PERMISSION_GRANTED;
3462                }
3463            } else {
3464                ArraySet<String> perms = mSystemPermissions.get(uid);
3465                if (perms != null) {
3466                    if (perms.contains(permName)) {
3467                        return PackageManager.PERMISSION_GRANTED;
3468                    }
3469                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3470                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3471                        return PackageManager.PERMISSION_GRANTED;
3472                    }
3473                }
3474            }
3475        }
3476
3477        return PackageManager.PERMISSION_DENIED;
3478    }
3479
3480    @Override
3481    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3482        if (UserHandle.getCallingUserId() != userId) {
3483            mContext.enforceCallingPermission(
3484                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3485                    "isPermissionRevokedByPolicy for user " + userId);
3486        }
3487
3488        if (checkPermission(permission, packageName, userId)
3489                == PackageManager.PERMISSION_GRANTED) {
3490            return false;
3491        }
3492
3493        final long identity = Binder.clearCallingIdentity();
3494        try {
3495            final int flags = getPermissionFlags(permission, packageName, userId);
3496            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3497        } finally {
3498            Binder.restoreCallingIdentity(identity);
3499        }
3500    }
3501
3502    @Override
3503    public String getPermissionControllerPackageName() {
3504        synchronized (mPackages) {
3505            return mRequiredInstallerPackage;
3506        }
3507    }
3508
3509    /**
3510     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3511     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3512     * @param checkShell TODO(yamasani):
3513     * @param message the message to log on security exception
3514     */
3515    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3516            boolean checkShell, String message) {
3517        if (userId < 0) {
3518            throw new IllegalArgumentException("Invalid userId " + userId);
3519        }
3520        if (checkShell) {
3521            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3522        }
3523        if (userId == UserHandle.getUserId(callingUid)) return;
3524        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3525            if (requireFullPermission) {
3526                mContext.enforceCallingOrSelfPermission(
3527                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3528            } else {
3529                try {
3530                    mContext.enforceCallingOrSelfPermission(
3531                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3532                } catch (SecurityException se) {
3533                    mContext.enforceCallingOrSelfPermission(
3534                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3535                }
3536            }
3537        }
3538    }
3539
3540    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3541        if (callingUid == Process.SHELL_UID) {
3542            if (userHandle >= 0
3543                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3544                throw new SecurityException("Shell does not have permission to access user "
3545                        + userHandle);
3546            } else if (userHandle < 0) {
3547                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3548                        + Debug.getCallers(3));
3549            }
3550        }
3551    }
3552
3553    private BasePermission findPermissionTreeLP(String permName) {
3554        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3555            if (permName.startsWith(bp.name) &&
3556                    permName.length() > bp.name.length() &&
3557                    permName.charAt(bp.name.length()) == '.') {
3558                return bp;
3559            }
3560        }
3561        return null;
3562    }
3563
3564    private BasePermission checkPermissionTreeLP(String permName) {
3565        if (permName != null) {
3566            BasePermission bp = findPermissionTreeLP(permName);
3567            if (bp != null) {
3568                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3569                    return bp;
3570                }
3571                throw new SecurityException("Calling uid "
3572                        + Binder.getCallingUid()
3573                        + " is not allowed to add to permission tree "
3574                        + bp.name + " owned by uid " + bp.uid);
3575            }
3576        }
3577        throw new SecurityException("No permission tree found for " + permName);
3578    }
3579
3580    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3581        if (s1 == null) {
3582            return s2 == null;
3583        }
3584        if (s2 == null) {
3585            return false;
3586        }
3587        if (s1.getClass() != s2.getClass()) {
3588            return false;
3589        }
3590        return s1.equals(s2);
3591    }
3592
3593    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3594        if (pi1.icon != pi2.icon) return false;
3595        if (pi1.logo != pi2.logo) return false;
3596        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3597        if (!compareStrings(pi1.name, pi2.name)) return false;
3598        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3599        // We'll take care of setting this one.
3600        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3601        // These are not currently stored in settings.
3602        //if (!compareStrings(pi1.group, pi2.group)) return false;
3603        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3604        //if (pi1.labelRes != pi2.labelRes) return false;
3605        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3606        return true;
3607    }
3608
3609    int permissionInfoFootprint(PermissionInfo info) {
3610        int size = info.name.length();
3611        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3612        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3613        return size;
3614    }
3615
3616    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3617        int size = 0;
3618        for (BasePermission perm : mSettings.mPermissions.values()) {
3619            if (perm.uid == tree.uid) {
3620                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3621            }
3622        }
3623        return size;
3624    }
3625
3626    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3627        // We calculate the max size of permissions defined by this uid and throw
3628        // if that plus the size of 'info' would exceed our stated maximum.
3629        if (tree.uid != Process.SYSTEM_UID) {
3630            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3631            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3632                throw new SecurityException("Permission tree size cap exceeded");
3633            }
3634        }
3635    }
3636
3637    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3638        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3639            throw new SecurityException("Label must be specified in permission");
3640        }
3641        BasePermission tree = checkPermissionTreeLP(info.name);
3642        BasePermission bp = mSettings.mPermissions.get(info.name);
3643        boolean added = bp == null;
3644        boolean changed = true;
3645        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3646        if (added) {
3647            enforcePermissionCapLocked(info, tree);
3648            bp = new BasePermission(info.name, tree.sourcePackage,
3649                    BasePermission.TYPE_DYNAMIC);
3650        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3651            throw new SecurityException(
3652                    "Not allowed to modify non-dynamic permission "
3653                    + info.name);
3654        } else {
3655            if (bp.protectionLevel == fixedLevel
3656                    && bp.perm.owner.equals(tree.perm.owner)
3657                    && bp.uid == tree.uid
3658                    && comparePermissionInfos(bp.perm.info, info)) {
3659                changed = false;
3660            }
3661        }
3662        bp.protectionLevel = fixedLevel;
3663        info = new PermissionInfo(info);
3664        info.protectionLevel = fixedLevel;
3665        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3666        bp.perm.info.packageName = tree.perm.info.packageName;
3667        bp.uid = tree.uid;
3668        if (added) {
3669            mSettings.mPermissions.put(info.name, bp);
3670        }
3671        if (changed) {
3672            if (!async) {
3673                mSettings.writeLPr();
3674            } else {
3675                scheduleWriteSettingsLocked();
3676            }
3677        }
3678        return added;
3679    }
3680
3681    @Override
3682    public boolean addPermission(PermissionInfo info) {
3683        synchronized (mPackages) {
3684            return addPermissionLocked(info, false);
3685        }
3686    }
3687
3688    @Override
3689    public boolean addPermissionAsync(PermissionInfo info) {
3690        synchronized (mPackages) {
3691            return addPermissionLocked(info, true);
3692        }
3693    }
3694
3695    @Override
3696    public void removePermission(String name) {
3697        synchronized (mPackages) {
3698            checkPermissionTreeLP(name);
3699            BasePermission bp = mSettings.mPermissions.get(name);
3700            if (bp != null) {
3701                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3702                    throw new SecurityException(
3703                            "Not allowed to modify non-dynamic permission "
3704                            + name);
3705                }
3706                mSettings.mPermissions.remove(name);
3707                mSettings.writeLPr();
3708            }
3709        }
3710    }
3711
3712    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3713            BasePermission bp) {
3714        int index = pkg.requestedPermissions.indexOf(bp.name);
3715        if (index == -1) {
3716            throw new SecurityException("Package " + pkg.packageName
3717                    + " has not requested permission " + bp.name);
3718        }
3719        if (!bp.isRuntime() && !bp.isDevelopment()) {
3720            throw new SecurityException("Permission " + bp.name
3721                    + " is not a changeable permission type");
3722        }
3723    }
3724
3725    @Override
3726    public void grantRuntimePermission(String packageName, String name, final int userId) {
3727        if (!sUserManager.exists(userId)) {
3728            Log.e(TAG, "No such user:" + userId);
3729            return;
3730        }
3731
3732        mContext.enforceCallingOrSelfPermission(
3733                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3734                "grantRuntimePermission");
3735
3736        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3737                "grantRuntimePermission");
3738
3739        final int uid;
3740        final SettingBase sb;
3741
3742        synchronized (mPackages) {
3743            final PackageParser.Package pkg = mPackages.get(packageName);
3744            if (pkg == null) {
3745                throw new IllegalArgumentException("Unknown package: " + packageName);
3746            }
3747
3748            final BasePermission bp = mSettings.mPermissions.get(name);
3749            if (bp == null) {
3750                throw new IllegalArgumentException("Unknown permission: " + name);
3751            }
3752
3753            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3754
3755            // If a permission review is required for legacy apps we represent
3756            // their permissions as always granted runtime ones since we need
3757            // to keep the review required permission flag per user while an
3758            // install permission's state is shared across all users.
3759            if (Build.PERMISSIONS_REVIEW_REQUIRED
3760                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3761                    && bp.isRuntime()) {
3762                return;
3763            }
3764
3765            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3766            sb = (SettingBase) pkg.mExtras;
3767            if (sb == null) {
3768                throw new IllegalArgumentException("Unknown package: " + packageName);
3769            }
3770
3771            final PermissionsState permissionsState = sb.getPermissionsState();
3772
3773            final int flags = permissionsState.getPermissionFlags(name, userId);
3774            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3775                throw new SecurityException("Cannot grant system fixed permission "
3776                        + name + " for package " + packageName);
3777            }
3778
3779            if (bp.isDevelopment()) {
3780                // Development permissions must be handled specially, since they are not
3781                // normal runtime permissions.  For now they apply to all users.
3782                if (permissionsState.grantInstallPermission(bp) !=
3783                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3784                    scheduleWriteSettingsLocked();
3785                }
3786                return;
3787            }
3788
3789            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3790                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3791                return;
3792            }
3793
3794            final int result = permissionsState.grantRuntimePermission(bp, userId);
3795            switch (result) {
3796                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3797                    return;
3798                }
3799
3800                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3801                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3802                    mHandler.post(new Runnable() {
3803                        @Override
3804                        public void run() {
3805                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3806                        }
3807                    });
3808                }
3809                break;
3810            }
3811
3812            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3813
3814            // Not critical if that is lost - app has to request again.
3815            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3816        }
3817
3818        // Only need to do this if user is initialized. Otherwise it's a new user
3819        // and there are no processes running as the user yet and there's no need
3820        // to make an expensive call to remount processes for the changed permissions.
3821        if (READ_EXTERNAL_STORAGE.equals(name)
3822                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3823            final long token = Binder.clearCallingIdentity();
3824            try {
3825                if (sUserManager.isInitialized(userId)) {
3826                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3827                            MountServiceInternal.class);
3828                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3829                }
3830            } finally {
3831                Binder.restoreCallingIdentity(token);
3832            }
3833        }
3834    }
3835
3836    @Override
3837    public void revokeRuntimePermission(String packageName, String name, int userId) {
3838        if (!sUserManager.exists(userId)) {
3839            Log.e(TAG, "No such user:" + userId);
3840            return;
3841        }
3842
3843        mContext.enforceCallingOrSelfPermission(
3844                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3845                "revokeRuntimePermission");
3846
3847        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3848                "revokeRuntimePermission");
3849
3850        final int appId;
3851
3852        synchronized (mPackages) {
3853            final PackageParser.Package pkg = mPackages.get(packageName);
3854            if (pkg == null) {
3855                throw new IllegalArgumentException("Unknown package: " + packageName);
3856            }
3857
3858            final BasePermission bp = mSettings.mPermissions.get(name);
3859            if (bp == null) {
3860                throw new IllegalArgumentException("Unknown permission: " + name);
3861            }
3862
3863            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3864
3865            // If a permission review is required for legacy apps we represent
3866            // their permissions as always granted runtime ones since we need
3867            // to keep the review required permission flag per user while an
3868            // install permission's state is shared across all users.
3869            if (Build.PERMISSIONS_REVIEW_REQUIRED
3870                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3871                    && bp.isRuntime()) {
3872                return;
3873            }
3874
3875            SettingBase sb = (SettingBase) pkg.mExtras;
3876            if (sb == null) {
3877                throw new IllegalArgumentException("Unknown package: " + packageName);
3878            }
3879
3880            final PermissionsState permissionsState = sb.getPermissionsState();
3881
3882            final int flags = permissionsState.getPermissionFlags(name, userId);
3883            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3884                throw new SecurityException("Cannot revoke system fixed permission "
3885                        + name + " for package " + packageName);
3886            }
3887
3888            if (bp.isDevelopment()) {
3889                // Development permissions must be handled specially, since they are not
3890                // normal runtime permissions.  For now they apply to all users.
3891                if (permissionsState.revokeInstallPermission(bp) !=
3892                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3893                    scheduleWriteSettingsLocked();
3894                }
3895                return;
3896            }
3897
3898            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3899                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3900                return;
3901            }
3902
3903            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3904
3905            // Critical, after this call app should never have the permission.
3906            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3907
3908            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3909        }
3910
3911        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3912    }
3913
3914    @Override
3915    public void resetRuntimePermissions() {
3916        mContext.enforceCallingOrSelfPermission(
3917                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3918                "revokeRuntimePermission");
3919
3920        int callingUid = Binder.getCallingUid();
3921        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3922            mContext.enforceCallingOrSelfPermission(
3923                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3924                    "resetRuntimePermissions");
3925        }
3926
3927        synchronized (mPackages) {
3928            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3929            for (int userId : UserManagerService.getInstance().getUserIds()) {
3930                final int packageCount = mPackages.size();
3931                for (int i = 0; i < packageCount; i++) {
3932                    PackageParser.Package pkg = mPackages.valueAt(i);
3933                    if (!(pkg.mExtras instanceof PackageSetting)) {
3934                        continue;
3935                    }
3936                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3937                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3938                }
3939            }
3940        }
3941    }
3942
3943    @Override
3944    public int getPermissionFlags(String name, String packageName, int userId) {
3945        if (!sUserManager.exists(userId)) {
3946            return 0;
3947        }
3948
3949        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3950
3951        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3952                "getPermissionFlags");
3953
3954        synchronized (mPackages) {
3955            final PackageParser.Package pkg = mPackages.get(packageName);
3956            if (pkg == null) {
3957                throw new IllegalArgumentException("Unknown package: " + packageName);
3958            }
3959
3960            final BasePermission bp = mSettings.mPermissions.get(name);
3961            if (bp == null) {
3962                throw new IllegalArgumentException("Unknown permission: " + name);
3963            }
3964
3965            SettingBase sb = (SettingBase) pkg.mExtras;
3966            if (sb == null) {
3967                throw new IllegalArgumentException("Unknown package: " + packageName);
3968            }
3969
3970            PermissionsState permissionsState = sb.getPermissionsState();
3971            return permissionsState.getPermissionFlags(name, userId);
3972        }
3973    }
3974
3975    @Override
3976    public void updatePermissionFlags(String name, String packageName, int flagMask,
3977            int flagValues, int userId) {
3978        if (!sUserManager.exists(userId)) {
3979            return;
3980        }
3981
3982        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3983
3984        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3985                "updatePermissionFlags");
3986
3987        // Only the system can change these flags and nothing else.
3988        if (getCallingUid() != Process.SYSTEM_UID) {
3989            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3990            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3991            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3992            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3993            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3994        }
3995
3996        synchronized (mPackages) {
3997            final PackageParser.Package pkg = mPackages.get(packageName);
3998            if (pkg == null) {
3999                throw new IllegalArgumentException("Unknown package: " + packageName);
4000            }
4001
4002            final BasePermission bp = mSettings.mPermissions.get(name);
4003            if (bp == null) {
4004                throw new IllegalArgumentException("Unknown permission: " + name);
4005            }
4006
4007            SettingBase sb = (SettingBase) pkg.mExtras;
4008            if (sb == null) {
4009                throw new IllegalArgumentException("Unknown package: " + packageName);
4010            }
4011
4012            PermissionsState permissionsState = sb.getPermissionsState();
4013
4014            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4015
4016            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4017                // Install and runtime permissions are stored in different places,
4018                // so figure out what permission changed and persist the change.
4019                if (permissionsState.getInstallPermissionState(name) != null) {
4020                    scheduleWriteSettingsLocked();
4021                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4022                        || hadState) {
4023                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4024                }
4025            }
4026        }
4027    }
4028
4029    /**
4030     * Update the permission flags for all packages and runtime permissions of a user in order
4031     * to allow device or profile owner to remove POLICY_FIXED.
4032     */
4033    @Override
4034    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4035        if (!sUserManager.exists(userId)) {
4036            return;
4037        }
4038
4039        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4040
4041        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4042                "updatePermissionFlagsForAllApps");
4043
4044        // Only the system can change system fixed flags.
4045        if (getCallingUid() != Process.SYSTEM_UID) {
4046            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4047            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4048        }
4049
4050        synchronized (mPackages) {
4051            boolean changed = false;
4052            final int packageCount = mPackages.size();
4053            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4054                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4055                SettingBase sb = (SettingBase) pkg.mExtras;
4056                if (sb == null) {
4057                    continue;
4058                }
4059                PermissionsState permissionsState = sb.getPermissionsState();
4060                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4061                        userId, flagMask, flagValues);
4062            }
4063            if (changed) {
4064                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4065            }
4066        }
4067    }
4068
4069    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4070        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4071                != PackageManager.PERMISSION_GRANTED
4072            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4073                != PackageManager.PERMISSION_GRANTED) {
4074            throw new SecurityException(message + " requires "
4075                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4076                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4077        }
4078    }
4079
4080    @Override
4081    public boolean shouldShowRequestPermissionRationale(String permissionName,
4082            String packageName, int userId) {
4083        if (UserHandle.getCallingUserId() != userId) {
4084            mContext.enforceCallingPermission(
4085                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4086                    "canShowRequestPermissionRationale for user " + userId);
4087        }
4088
4089        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4090        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4091            return false;
4092        }
4093
4094        if (checkPermission(permissionName, packageName, userId)
4095                == PackageManager.PERMISSION_GRANTED) {
4096            return false;
4097        }
4098
4099        final int flags;
4100
4101        final long identity = Binder.clearCallingIdentity();
4102        try {
4103            flags = getPermissionFlags(permissionName,
4104                    packageName, userId);
4105        } finally {
4106            Binder.restoreCallingIdentity(identity);
4107        }
4108
4109        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4110                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4111                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4112
4113        if ((flags & fixedFlags) != 0) {
4114            return false;
4115        }
4116
4117        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4118    }
4119
4120    @Override
4121    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4122        mContext.enforceCallingOrSelfPermission(
4123                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4124                "addOnPermissionsChangeListener");
4125
4126        synchronized (mPackages) {
4127            mOnPermissionChangeListeners.addListenerLocked(listener);
4128        }
4129    }
4130
4131    @Override
4132    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4133        synchronized (mPackages) {
4134            mOnPermissionChangeListeners.removeListenerLocked(listener);
4135        }
4136    }
4137
4138    @Override
4139    public boolean isProtectedBroadcast(String actionName) {
4140        synchronized (mPackages) {
4141            if (mProtectedBroadcasts.contains(actionName)) {
4142                return true;
4143            } else if (actionName != null) {
4144                // TODO: remove these terrible hacks
4145                if (actionName.startsWith("android.net.netmon.lingerExpired")
4146                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4147                    return true;
4148                }
4149            }
4150        }
4151        return false;
4152    }
4153
4154    @Override
4155    public int checkSignatures(String pkg1, String pkg2) {
4156        synchronized (mPackages) {
4157            final PackageParser.Package p1 = mPackages.get(pkg1);
4158            final PackageParser.Package p2 = mPackages.get(pkg2);
4159            if (p1 == null || p1.mExtras == null
4160                    || p2 == null || p2.mExtras == null) {
4161                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4162            }
4163            return compareSignatures(p1.mSignatures, p2.mSignatures);
4164        }
4165    }
4166
4167    @Override
4168    public int checkUidSignatures(int uid1, int uid2) {
4169        // Map to base uids.
4170        uid1 = UserHandle.getAppId(uid1);
4171        uid2 = UserHandle.getAppId(uid2);
4172        // reader
4173        synchronized (mPackages) {
4174            Signature[] s1;
4175            Signature[] s2;
4176            Object obj = mSettings.getUserIdLPr(uid1);
4177            if (obj != null) {
4178                if (obj instanceof SharedUserSetting) {
4179                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4180                } else if (obj instanceof PackageSetting) {
4181                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4182                } else {
4183                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4184                }
4185            } else {
4186                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4187            }
4188            obj = mSettings.getUserIdLPr(uid2);
4189            if (obj != null) {
4190                if (obj instanceof SharedUserSetting) {
4191                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4192                } else if (obj instanceof PackageSetting) {
4193                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4194                } else {
4195                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4196                }
4197            } else {
4198                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4199            }
4200            return compareSignatures(s1, s2);
4201        }
4202    }
4203
4204    private void killUid(int appId, int userId, String reason) {
4205        final long identity = Binder.clearCallingIdentity();
4206        try {
4207            IActivityManager am = ActivityManagerNative.getDefault();
4208            if (am != null) {
4209                try {
4210                    am.killUid(appId, userId, reason);
4211                } catch (RemoteException e) {
4212                    /* ignore - same process */
4213                }
4214            }
4215        } finally {
4216            Binder.restoreCallingIdentity(identity);
4217        }
4218    }
4219
4220    /**
4221     * Compares two sets of signatures. Returns:
4222     * <br />
4223     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4224     * <br />
4225     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4226     * <br />
4227     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4228     * <br />
4229     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4230     * <br />
4231     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4232     */
4233    static int compareSignatures(Signature[] s1, Signature[] s2) {
4234        if (s1 == null) {
4235            return s2 == null
4236                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4237                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4238        }
4239
4240        if (s2 == null) {
4241            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4242        }
4243
4244        if (s1.length != s2.length) {
4245            return PackageManager.SIGNATURE_NO_MATCH;
4246        }
4247
4248        // Since both signature sets are of size 1, we can compare without HashSets.
4249        if (s1.length == 1) {
4250            return s1[0].equals(s2[0]) ?
4251                    PackageManager.SIGNATURE_MATCH :
4252                    PackageManager.SIGNATURE_NO_MATCH;
4253        }
4254
4255        ArraySet<Signature> set1 = new ArraySet<Signature>();
4256        for (Signature sig : s1) {
4257            set1.add(sig);
4258        }
4259        ArraySet<Signature> set2 = new ArraySet<Signature>();
4260        for (Signature sig : s2) {
4261            set2.add(sig);
4262        }
4263        // Make sure s2 contains all signatures in s1.
4264        if (set1.equals(set2)) {
4265            return PackageManager.SIGNATURE_MATCH;
4266        }
4267        return PackageManager.SIGNATURE_NO_MATCH;
4268    }
4269
4270    /**
4271     * If the database version for this type of package (internal storage or
4272     * external storage) is less than the version where package signatures
4273     * were updated, return true.
4274     */
4275    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4276        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4277        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4278    }
4279
4280    /**
4281     * Used for backward compatibility to make sure any packages with
4282     * certificate chains get upgraded to the new style. {@code existingSigs}
4283     * will be in the old format (since they were stored on disk from before the
4284     * system upgrade) and {@code scannedSigs} will be in the newer format.
4285     */
4286    private int compareSignaturesCompat(PackageSignatures existingSigs,
4287            PackageParser.Package scannedPkg) {
4288        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4289            return PackageManager.SIGNATURE_NO_MATCH;
4290        }
4291
4292        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4293        for (Signature sig : existingSigs.mSignatures) {
4294            existingSet.add(sig);
4295        }
4296        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4297        for (Signature sig : scannedPkg.mSignatures) {
4298            try {
4299                Signature[] chainSignatures = sig.getChainSignatures();
4300                for (Signature chainSig : chainSignatures) {
4301                    scannedCompatSet.add(chainSig);
4302                }
4303            } catch (CertificateEncodingException e) {
4304                scannedCompatSet.add(sig);
4305            }
4306        }
4307        /*
4308         * Make sure the expanded scanned set contains all signatures in the
4309         * existing one.
4310         */
4311        if (scannedCompatSet.equals(existingSet)) {
4312            // Migrate the old signatures to the new scheme.
4313            existingSigs.assignSignatures(scannedPkg.mSignatures);
4314            // The new KeySets will be re-added later in the scanning process.
4315            synchronized (mPackages) {
4316                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4317            }
4318            return PackageManager.SIGNATURE_MATCH;
4319        }
4320        return PackageManager.SIGNATURE_NO_MATCH;
4321    }
4322
4323    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4324        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4325        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4326    }
4327
4328    private int compareSignaturesRecover(PackageSignatures existingSigs,
4329            PackageParser.Package scannedPkg) {
4330        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4331            return PackageManager.SIGNATURE_NO_MATCH;
4332        }
4333
4334        String msg = null;
4335        try {
4336            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4337                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4338                        + scannedPkg.packageName);
4339                return PackageManager.SIGNATURE_MATCH;
4340            }
4341        } catch (CertificateException e) {
4342            msg = e.getMessage();
4343        }
4344
4345        logCriticalInfo(Log.INFO,
4346                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4347        return PackageManager.SIGNATURE_NO_MATCH;
4348    }
4349
4350    @Override
4351    public String[] getPackagesForUid(int uid) {
4352        uid = UserHandle.getAppId(uid);
4353        // reader
4354        synchronized (mPackages) {
4355            Object obj = mSettings.getUserIdLPr(uid);
4356            if (obj instanceof SharedUserSetting) {
4357                final SharedUserSetting sus = (SharedUserSetting) obj;
4358                final int N = sus.packages.size();
4359                final String[] res = new String[N];
4360                final Iterator<PackageSetting> it = sus.packages.iterator();
4361                int i = 0;
4362                while (it.hasNext()) {
4363                    res[i++] = it.next().name;
4364                }
4365                return res;
4366            } else if (obj instanceof PackageSetting) {
4367                final PackageSetting ps = (PackageSetting) obj;
4368                return new String[] { ps.name };
4369            }
4370        }
4371        return null;
4372    }
4373
4374    @Override
4375    public String getNameForUid(int uid) {
4376        // reader
4377        synchronized (mPackages) {
4378            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4379            if (obj instanceof SharedUserSetting) {
4380                final SharedUserSetting sus = (SharedUserSetting) obj;
4381                return sus.name + ":" + sus.userId;
4382            } else if (obj instanceof PackageSetting) {
4383                final PackageSetting ps = (PackageSetting) obj;
4384                return ps.name;
4385            }
4386        }
4387        return null;
4388    }
4389
4390    @Override
4391    public int getUidForSharedUser(String sharedUserName) {
4392        if(sharedUserName == null) {
4393            return -1;
4394        }
4395        // reader
4396        synchronized (mPackages) {
4397            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4398            if (suid == null) {
4399                return -1;
4400            }
4401            return suid.userId;
4402        }
4403    }
4404
4405    @Override
4406    public int getFlagsForUid(int uid) {
4407        synchronized (mPackages) {
4408            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4409            if (obj instanceof SharedUserSetting) {
4410                final SharedUserSetting sus = (SharedUserSetting) obj;
4411                return sus.pkgFlags;
4412            } else if (obj instanceof PackageSetting) {
4413                final PackageSetting ps = (PackageSetting) obj;
4414                return ps.pkgFlags;
4415            }
4416        }
4417        return 0;
4418    }
4419
4420    @Override
4421    public int getPrivateFlagsForUid(int uid) {
4422        synchronized (mPackages) {
4423            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4424            if (obj instanceof SharedUserSetting) {
4425                final SharedUserSetting sus = (SharedUserSetting) obj;
4426                return sus.pkgPrivateFlags;
4427            } else if (obj instanceof PackageSetting) {
4428                final PackageSetting ps = (PackageSetting) obj;
4429                return ps.pkgPrivateFlags;
4430            }
4431        }
4432        return 0;
4433    }
4434
4435    @Override
4436    public boolean isUidPrivileged(int uid) {
4437        uid = UserHandle.getAppId(uid);
4438        // reader
4439        synchronized (mPackages) {
4440            Object obj = mSettings.getUserIdLPr(uid);
4441            if (obj instanceof SharedUserSetting) {
4442                final SharedUserSetting sus = (SharedUserSetting) obj;
4443                final Iterator<PackageSetting> it = sus.packages.iterator();
4444                while (it.hasNext()) {
4445                    if (it.next().isPrivileged()) {
4446                        return true;
4447                    }
4448                }
4449            } else if (obj instanceof PackageSetting) {
4450                final PackageSetting ps = (PackageSetting) obj;
4451                return ps.isPrivileged();
4452            }
4453        }
4454        return false;
4455    }
4456
4457    @Override
4458    public String[] getAppOpPermissionPackages(String permissionName) {
4459        synchronized (mPackages) {
4460            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4461            if (pkgs == null) {
4462                return null;
4463            }
4464            return pkgs.toArray(new String[pkgs.size()]);
4465        }
4466    }
4467
4468    @Override
4469    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4470            int flags, int userId) {
4471        if (!sUserManager.exists(userId)) return null;
4472        flags = updateFlagsForResolve(flags, userId, intent);
4473        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4474        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4475        final ResolveInfo bestChoice =
4476                chooseBestActivity(intent, resolvedType, flags, query, userId);
4477
4478        if (isEphemeralAllowed(intent, query, userId)) {
4479            final EphemeralResolveInfo ai =
4480                    getEphemeralResolveInfo(intent, resolvedType, userId);
4481            if (ai != null) {
4482                if (DEBUG_EPHEMERAL) {
4483                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4484                }
4485                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4486                bestChoice.ephemeralResolveInfo = ai;
4487            }
4488        }
4489        return bestChoice;
4490    }
4491
4492    @Override
4493    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4494            IntentFilter filter, int match, ComponentName activity) {
4495        final int userId = UserHandle.getCallingUserId();
4496        if (DEBUG_PREFERRED) {
4497            Log.v(TAG, "setLastChosenActivity intent=" + intent
4498                + " resolvedType=" + resolvedType
4499                + " flags=" + flags
4500                + " filter=" + filter
4501                + " match=" + match
4502                + " activity=" + activity);
4503            filter.dump(new PrintStreamPrinter(System.out), "    ");
4504        }
4505        intent.setComponent(null);
4506        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4507        // Find any earlier preferred or last chosen entries and nuke them
4508        findPreferredActivity(intent, resolvedType,
4509                flags, query, 0, false, true, false, userId);
4510        // Add the new activity as the last chosen for this filter
4511        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4512                "Setting last chosen");
4513    }
4514
4515    @Override
4516    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4517        final int userId = UserHandle.getCallingUserId();
4518        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4519        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4520        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4521                false, false, false, userId);
4522    }
4523
4524
4525    private boolean isEphemeralAllowed(
4526            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4527        // Short circuit and return early if possible.
4528        if (DISABLE_EPHEMERAL_APPS) {
4529            return false;
4530        }
4531        final int callingUser = UserHandle.getCallingUserId();
4532        if (callingUser != UserHandle.USER_SYSTEM) {
4533            return false;
4534        }
4535        if (mEphemeralResolverConnection == null) {
4536            return false;
4537        }
4538        if (intent.getComponent() != null) {
4539            return false;
4540        }
4541        if (intent.getPackage() != null) {
4542            return false;
4543        }
4544        final boolean isWebUri = hasWebURI(intent);
4545        if (!isWebUri) {
4546            return false;
4547        }
4548        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4549        synchronized (mPackages) {
4550            final int count = resolvedActivites.size();
4551            for (int n = 0; n < count; n++) {
4552                ResolveInfo info = resolvedActivites.get(n);
4553                String packageName = info.activityInfo.packageName;
4554                PackageSetting ps = mSettings.mPackages.get(packageName);
4555                if (ps != null) {
4556                    // Try to get the status from User settings first
4557                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4558                    int status = (int) (packedStatus >> 32);
4559                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4560                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4561                        if (DEBUG_EPHEMERAL) {
4562                            Slog.v(TAG, "DENY ephemeral apps;"
4563                                + " pkg: " + packageName + ", status: " + status);
4564                        }
4565                        return false;
4566                    }
4567                }
4568            }
4569        }
4570        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4571        return true;
4572    }
4573
4574    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4575            int userId) {
4576        MessageDigest digest = null;
4577        try {
4578            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4579        } catch (NoSuchAlgorithmException e) {
4580            // If we can't create a digest, ignore ephemeral apps.
4581            return null;
4582        }
4583
4584        final byte[] hostBytes = intent.getData().getHost().getBytes();
4585        final byte[] digestBytes = digest.digest(hostBytes);
4586        int shaPrefix =
4587                digestBytes[0] << 24
4588                | digestBytes[1] << 16
4589                | digestBytes[2] << 8
4590                | digestBytes[3] << 0;
4591        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4592                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4593        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4594            // No hash prefix match; there are no ephemeral apps for this domain.
4595            return null;
4596        }
4597        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4598            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4599            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4600                continue;
4601            }
4602            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4603            // No filters; this should never happen.
4604            if (filters.isEmpty()) {
4605                continue;
4606            }
4607            // We have a domain match; resolve the filters to see if anything matches.
4608            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4609            for (int j = filters.size() - 1; j >= 0; --j) {
4610                final EphemeralResolveIntentInfo intentInfo =
4611                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4612                ephemeralResolver.addFilter(intentInfo);
4613            }
4614            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4615                    intent, resolvedType, false /*defaultOnly*/, userId);
4616            if (!matchedResolveInfoList.isEmpty()) {
4617                return matchedResolveInfoList.get(0);
4618            }
4619        }
4620        // Hash or filter mis-match; no ephemeral apps for this domain.
4621        return null;
4622    }
4623
4624    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4625            int flags, List<ResolveInfo> query, int userId) {
4626        if (query != null) {
4627            final int N = query.size();
4628            if (N == 1) {
4629                return query.get(0);
4630            } else if (N > 1) {
4631                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4632                // If there is more than one activity with the same priority,
4633                // then let the user decide between them.
4634                ResolveInfo r0 = query.get(0);
4635                ResolveInfo r1 = query.get(1);
4636                if (DEBUG_INTENT_MATCHING || debug) {
4637                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4638                            + r1.activityInfo.name + "=" + r1.priority);
4639                }
4640                // If the first activity has a higher priority, or a different
4641                // default, then it is always desirable to pick it.
4642                if (r0.priority != r1.priority
4643                        || r0.preferredOrder != r1.preferredOrder
4644                        || r0.isDefault != r1.isDefault) {
4645                    return query.get(0);
4646                }
4647                // If we have saved a preference for a preferred activity for
4648                // this Intent, use that.
4649                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4650                        flags, query, r0.priority, true, false, debug, userId);
4651                if (ri != null) {
4652                    return ri;
4653                }
4654                ri = new ResolveInfo(mResolveInfo);
4655                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4656                ri.activityInfo.applicationInfo = new ApplicationInfo(
4657                        ri.activityInfo.applicationInfo);
4658                if (userId != 0) {
4659                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4660                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4661                }
4662                // Make sure that the resolver is displayable in car mode
4663                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4664                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4665                return ri;
4666            }
4667        }
4668        return null;
4669    }
4670
4671    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4672            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4673        final int N = query.size();
4674        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4675                .get(userId);
4676        // Get the list of persistent preferred activities that handle the intent
4677        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4678        List<PersistentPreferredActivity> pprefs = ppir != null
4679                ? ppir.queryIntent(intent, resolvedType,
4680                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4681                : null;
4682        if (pprefs != null && pprefs.size() > 0) {
4683            final int M = pprefs.size();
4684            for (int i=0; i<M; i++) {
4685                final PersistentPreferredActivity ppa = pprefs.get(i);
4686                if (DEBUG_PREFERRED || debug) {
4687                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4688                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4689                            + "\n  component=" + ppa.mComponent);
4690                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4691                }
4692                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4693                        flags | MATCH_DISABLED_COMPONENTS, userId);
4694                if (DEBUG_PREFERRED || debug) {
4695                    Slog.v(TAG, "Found persistent preferred activity:");
4696                    if (ai != null) {
4697                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4698                    } else {
4699                        Slog.v(TAG, "  null");
4700                    }
4701                }
4702                if (ai == null) {
4703                    // This previously registered persistent preferred activity
4704                    // component is no longer known. Ignore it and do NOT remove it.
4705                    continue;
4706                }
4707                for (int j=0; j<N; j++) {
4708                    final ResolveInfo ri = query.get(j);
4709                    if (!ri.activityInfo.applicationInfo.packageName
4710                            .equals(ai.applicationInfo.packageName)) {
4711                        continue;
4712                    }
4713                    if (!ri.activityInfo.name.equals(ai.name)) {
4714                        continue;
4715                    }
4716                    //  Found a persistent preference that can handle the intent.
4717                    if (DEBUG_PREFERRED || debug) {
4718                        Slog.v(TAG, "Returning persistent preferred activity: " +
4719                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4720                    }
4721                    return ri;
4722                }
4723            }
4724        }
4725        return null;
4726    }
4727
4728    // TODO: handle preferred activities missing while user has amnesia
4729    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4730            List<ResolveInfo> query, int priority, boolean always,
4731            boolean removeMatches, boolean debug, int userId) {
4732        if (!sUserManager.exists(userId)) return null;
4733        flags = updateFlagsForResolve(flags, userId, intent);
4734        // writer
4735        synchronized (mPackages) {
4736            if (intent.getSelector() != null) {
4737                intent = intent.getSelector();
4738            }
4739            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4740
4741            // Try to find a matching persistent preferred activity.
4742            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4743                    debug, userId);
4744
4745            // If a persistent preferred activity matched, use it.
4746            if (pri != null) {
4747                return pri;
4748            }
4749
4750            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4751            // Get the list of preferred activities that handle the intent
4752            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4753            List<PreferredActivity> prefs = pir != null
4754                    ? pir.queryIntent(intent, resolvedType,
4755                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4756                    : null;
4757            if (prefs != null && prefs.size() > 0) {
4758                boolean changed = false;
4759                try {
4760                    // First figure out how good the original match set is.
4761                    // We will only allow preferred activities that came
4762                    // from the same match quality.
4763                    int match = 0;
4764
4765                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4766
4767                    final int N = query.size();
4768                    for (int j=0; j<N; j++) {
4769                        final ResolveInfo ri = query.get(j);
4770                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4771                                + ": 0x" + Integer.toHexString(match));
4772                        if (ri.match > match) {
4773                            match = ri.match;
4774                        }
4775                    }
4776
4777                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4778                            + Integer.toHexString(match));
4779
4780                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4781                    final int M = prefs.size();
4782                    for (int i=0; i<M; i++) {
4783                        final PreferredActivity pa = prefs.get(i);
4784                        if (DEBUG_PREFERRED || debug) {
4785                            Slog.v(TAG, "Checking PreferredActivity ds="
4786                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4787                                    + "\n  component=" + pa.mPref.mComponent);
4788                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4789                        }
4790                        if (pa.mPref.mMatch != match) {
4791                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4792                                    + Integer.toHexString(pa.mPref.mMatch));
4793                            continue;
4794                        }
4795                        // If it's not an "always" type preferred activity and that's what we're
4796                        // looking for, skip it.
4797                        if (always && !pa.mPref.mAlways) {
4798                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4799                            continue;
4800                        }
4801                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4802                                flags | MATCH_DISABLED_COMPONENTS, userId);
4803                        if (DEBUG_PREFERRED || debug) {
4804                            Slog.v(TAG, "Found preferred activity:");
4805                            if (ai != null) {
4806                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4807                            } else {
4808                                Slog.v(TAG, "  null");
4809                            }
4810                        }
4811                        if (ai == null) {
4812                            // This previously registered preferred activity
4813                            // component is no longer known.  Most likely an update
4814                            // to the app was installed and in the new version this
4815                            // component no longer exists.  Clean it up by removing
4816                            // it from the preferred activities list, and skip it.
4817                            Slog.w(TAG, "Removing dangling preferred activity: "
4818                                    + pa.mPref.mComponent);
4819                            pir.removeFilter(pa);
4820                            changed = true;
4821                            continue;
4822                        }
4823                        for (int j=0; j<N; j++) {
4824                            final ResolveInfo ri = query.get(j);
4825                            if (!ri.activityInfo.applicationInfo.packageName
4826                                    .equals(ai.applicationInfo.packageName)) {
4827                                continue;
4828                            }
4829                            if (!ri.activityInfo.name.equals(ai.name)) {
4830                                continue;
4831                            }
4832
4833                            if (removeMatches) {
4834                                pir.removeFilter(pa);
4835                                changed = true;
4836                                if (DEBUG_PREFERRED) {
4837                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4838                                }
4839                                break;
4840                            }
4841
4842                            // Okay we found a previously set preferred or last chosen app.
4843                            // If the result set is different from when this
4844                            // was created, we need to clear it and re-ask the
4845                            // user their preference, if we're looking for an "always" type entry.
4846                            if (always && !pa.mPref.sameSet(query)) {
4847                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4848                                        + intent + " type " + resolvedType);
4849                                if (DEBUG_PREFERRED) {
4850                                    Slog.v(TAG, "Removing preferred activity since set changed "
4851                                            + pa.mPref.mComponent);
4852                                }
4853                                pir.removeFilter(pa);
4854                                // Re-add the filter as a "last chosen" entry (!always)
4855                                PreferredActivity lastChosen = new PreferredActivity(
4856                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4857                                pir.addFilter(lastChosen);
4858                                changed = true;
4859                                return null;
4860                            }
4861
4862                            // Yay! Either the set matched or we're looking for the last chosen
4863                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4864                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4865                            return ri;
4866                        }
4867                    }
4868                } finally {
4869                    if (changed) {
4870                        if (DEBUG_PREFERRED) {
4871                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4872                        }
4873                        scheduleWritePackageRestrictionsLocked(userId);
4874                    }
4875                }
4876            }
4877        }
4878        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4879        return null;
4880    }
4881
4882    /*
4883     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4884     */
4885    @Override
4886    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4887            int targetUserId) {
4888        mContext.enforceCallingOrSelfPermission(
4889                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4890        List<CrossProfileIntentFilter> matches =
4891                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4892        if (matches != null) {
4893            int size = matches.size();
4894            for (int i = 0; i < size; i++) {
4895                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4896            }
4897        }
4898        if (hasWebURI(intent)) {
4899            // cross-profile app linking works only towards the parent.
4900            final UserInfo parent = getProfileParent(sourceUserId);
4901            synchronized(mPackages) {
4902                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4903                        intent, resolvedType, 0, sourceUserId, parent.id);
4904                return xpDomainInfo != null;
4905            }
4906        }
4907        return false;
4908    }
4909
4910    private UserInfo getProfileParent(int userId) {
4911        final long identity = Binder.clearCallingIdentity();
4912        try {
4913            return sUserManager.getProfileParent(userId);
4914        } finally {
4915            Binder.restoreCallingIdentity(identity);
4916        }
4917    }
4918
4919    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4920            String resolvedType, int userId) {
4921        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4922        if (resolver != null) {
4923            return resolver.queryIntent(intent, resolvedType, false, userId);
4924        }
4925        return null;
4926    }
4927
4928    @Override
4929    public List<ResolveInfo> queryIntentActivities(Intent intent,
4930            String resolvedType, int flags, int userId) {
4931        if (!sUserManager.exists(userId)) return Collections.emptyList();
4932        flags = updateFlagsForResolve(flags, userId, intent);
4933        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4934        ComponentName comp = intent.getComponent();
4935        if (comp == null) {
4936            if (intent.getSelector() != null) {
4937                intent = intent.getSelector();
4938                comp = intent.getComponent();
4939            }
4940        }
4941
4942        if (comp != null) {
4943            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4944            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4945            if (ai != null) {
4946                final ResolveInfo ri = new ResolveInfo();
4947                ri.activityInfo = ai;
4948                list.add(ri);
4949            }
4950            return list;
4951        }
4952
4953        // reader
4954        synchronized (mPackages) {
4955            final String pkgName = intent.getPackage();
4956            if (pkgName == null) {
4957                List<CrossProfileIntentFilter> matchingFilters =
4958                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4959                // Check for results that need to skip the current profile.
4960                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4961                        resolvedType, flags, userId);
4962                if (xpResolveInfo != null) {
4963                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4964                    result.add(xpResolveInfo);
4965                    return filterIfNotSystemUser(result, userId);
4966                }
4967
4968                // Check for results in the current profile.
4969                List<ResolveInfo> result = mActivities.queryIntent(
4970                        intent, resolvedType, flags, userId);
4971                result = filterIfNotSystemUser(result, userId);
4972
4973                // Check for cross profile results.
4974                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4975                xpResolveInfo = queryCrossProfileIntents(
4976                        matchingFilters, intent, resolvedType, flags, userId,
4977                        hasNonNegativePriorityResult);
4978                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4979                    boolean isVisibleToUser = filterIfNotSystemUser(
4980                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4981                    if (isVisibleToUser) {
4982                        result.add(xpResolveInfo);
4983                        Collections.sort(result, mResolvePrioritySorter);
4984                    }
4985                }
4986                if (hasWebURI(intent)) {
4987                    CrossProfileDomainInfo xpDomainInfo = null;
4988                    final UserInfo parent = getProfileParent(userId);
4989                    if (parent != null) {
4990                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4991                                flags, userId, parent.id);
4992                    }
4993                    if (xpDomainInfo != null) {
4994                        if (xpResolveInfo != null) {
4995                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4996                            // in the result.
4997                            result.remove(xpResolveInfo);
4998                        }
4999                        if (result.size() == 0) {
5000                            result.add(xpDomainInfo.resolveInfo);
5001                            return result;
5002                        }
5003                    } else if (result.size() <= 1) {
5004                        return result;
5005                    }
5006                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5007                            xpDomainInfo, userId);
5008                    Collections.sort(result, mResolvePrioritySorter);
5009                }
5010                return result;
5011            }
5012            final PackageParser.Package pkg = mPackages.get(pkgName);
5013            if (pkg != null) {
5014                return filterIfNotSystemUser(
5015                        mActivities.queryIntentForPackage(
5016                                intent, resolvedType, flags, pkg.activities, userId),
5017                        userId);
5018            }
5019            return new ArrayList<ResolveInfo>();
5020        }
5021    }
5022
5023    private static class CrossProfileDomainInfo {
5024        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5025        ResolveInfo resolveInfo;
5026        /* Best domain verification status of the activities found in the other profile */
5027        int bestDomainVerificationStatus;
5028    }
5029
5030    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5031            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5032        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5033                sourceUserId)) {
5034            return null;
5035        }
5036        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5037                resolvedType, flags, parentUserId);
5038
5039        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5040            return null;
5041        }
5042        CrossProfileDomainInfo result = null;
5043        int size = resultTargetUser.size();
5044        for (int i = 0; i < size; i++) {
5045            ResolveInfo riTargetUser = resultTargetUser.get(i);
5046            // Intent filter verification is only for filters that specify a host. So don't return
5047            // those that handle all web uris.
5048            if (riTargetUser.handleAllWebDataURI) {
5049                continue;
5050            }
5051            String packageName = riTargetUser.activityInfo.packageName;
5052            PackageSetting ps = mSettings.mPackages.get(packageName);
5053            if (ps == null) {
5054                continue;
5055            }
5056            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5057            int status = (int)(verificationState >> 32);
5058            if (result == null) {
5059                result = new CrossProfileDomainInfo();
5060                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5061                        sourceUserId, parentUserId);
5062                result.bestDomainVerificationStatus = status;
5063            } else {
5064                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5065                        result.bestDomainVerificationStatus);
5066            }
5067        }
5068        // Don't consider matches with status NEVER across profiles.
5069        if (result != null && result.bestDomainVerificationStatus
5070                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5071            return null;
5072        }
5073        return result;
5074    }
5075
5076    /**
5077     * Verification statuses are ordered from the worse to the best, except for
5078     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5079     */
5080    private int bestDomainVerificationStatus(int status1, int status2) {
5081        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5082            return status2;
5083        }
5084        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5085            return status1;
5086        }
5087        return (int) MathUtils.max(status1, status2);
5088    }
5089
5090    private boolean isUserEnabled(int userId) {
5091        long callingId = Binder.clearCallingIdentity();
5092        try {
5093            UserInfo userInfo = sUserManager.getUserInfo(userId);
5094            return userInfo != null && userInfo.isEnabled();
5095        } finally {
5096            Binder.restoreCallingIdentity(callingId);
5097        }
5098    }
5099
5100    /**
5101     * Filter out activities with systemUserOnly flag set, when current user is not System.
5102     *
5103     * @return filtered list
5104     */
5105    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5106        if (userId == UserHandle.USER_SYSTEM) {
5107            return resolveInfos;
5108        }
5109        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5110            ResolveInfo info = resolveInfos.get(i);
5111            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5112                resolveInfos.remove(i);
5113            }
5114        }
5115        return resolveInfos;
5116    }
5117
5118    /**
5119     * @param resolveInfos list of resolve infos in descending priority order
5120     * @return if the list contains a resolve info with non-negative priority
5121     */
5122    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5123        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5124    }
5125
5126    private static boolean hasWebURI(Intent intent) {
5127        if (intent.getData() == null) {
5128            return false;
5129        }
5130        final String scheme = intent.getScheme();
5131        if (TextUtils.isEmpty(scheme)) {
5132            return false;
5133        }
5134        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5135    }
5136
5137    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5138            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5139            int userId) {
5140        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5141
5142        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5143            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5144                    candidates.size());
5145        }
5146
5147        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5148        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5149        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5150        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5151        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5152        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5153
5154        synchronized (mPackages) {
5155            final int count = candidates.size();
5156            // First, try to use linked apps. Partition the candidates into four lists:
5157            // one for the final results, one for the "do not use ever", one for "undefined status"
5158            // and finally one for "browser app type".
5159            for (int n=0; n<count; n++) {
5160                ResolveInfo info = candidates.get(n);
5161                String packageName = info.activityInfo.packageName;
5162                PackageSetting ps = mSettings.mPackages.get(packageName);
5163                if (ps != null) {
5164                    // Add to the special match all list (Browser use case)
5165                    if (info.handleAllWebDataURI) {
5166                        matchAllList.add(info);
5167                        continue;
5168                    }
5169                    // Try to get the status from User settings first
5170                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5171                    int status = (int)(packedStatus >> 32);
5172                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5173                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5174                        if (DEBUG_DOMAIN_VERIFICATION) {
5175                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5176                                    + " : linkgen=" + linkGeneration);
5177                        }
5178                        // Use link-enabled generation as preferredOrder, i.e.
5179                        // prefer newly-enabled over earlier-enabled.
5180                        info.preferredOrder = linkGeneration;
5181                        alwaysList.add(info);
5182                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5183                        if (DEBUG_DOMAIN_VERIFICATION) {
5184                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5185                        }
5186                        neverList.add(info);
5187                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5188                        if (DEBUG_DOMAIN_VERIFICATION) {
5189                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5190                        }
5191                        alwaysAskList.add(info);
5192                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5193                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5194                        if (DEBUG_DOMAIN_VERIFICATION) {
5195                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5196                        }
5197                        undefinedList.add(info);
5198                    }
5199                }
5200            }
5201
5202            // We'll want to include browser possibilities in a few cases
5203            boolean includeBrowser = false;
5204
5205            // First try to add the "always" resolution(s) for the current user, if any
5206            if (alwaysList.size() > 0) {
5207                result.addAll(alwaysList);
5208            } else {
5209                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5210                result.addAll(undefinedList);
5211                // Maybe add one for the other profile.
5212                if (xpDomainInfo != null && (
5213                        xpDomainInfo.bestDomainVerificationStatus
5214                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5215                    result.add(xpDomainInfo.resolveInfo);
5216                }
5217                includeBrowser = true;
5218            }
5219
5220            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5221            // If there were 'always' entries their preferred order has been set, so we also
5222            // back that off to make the alternatives equivalent
5223            if (alwaysAskList.size() > 0) {
5224                for (ResolveInfo i : result) {
5225                    i.preferredOrder = 0;
5226                }
5227                result.addAll(alwaysAskList);
5228                includeBrowser = true;
5229            }
5230
5231            if (includeBrowser) {
5232                // Also add browsers (all of them or only the default one)
5233                if (DEBUG_DOMAIN_VERIFICATION) {
5234                    Slog.v(TAG, "   ...including browsers in candidate set");
5235                }
5236                if ((matchFlags & MATCH_ALL) != 0) {
5237                    result.addAll(matchAllList);
5238                } else {
5239                    // Browser/generic handling case.  If there's a default browser, go straight
5240                    // to that (but only if there is no other higher-priority match).
5241                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5242                    int maxMatchPrio = 0;
5243                    ResolveInfo defaultBrowserMatch = null;
5244                    final int numCandidates = matchAllList.size();
5245                    for (int n = 0; n < numCandidates; n++) {
5246                        ResolveInfo info = matchAllList.get(n);
5247                        // track the highest overall match priority...
5248                        if (info.priority > maxMatchPrio) {
5249                            maxMatchPrio = info.priority;
5250                        }
5251                        // ...and the highest-priority default browser match
5252                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5253                            if (defaultBrowserMatch == null
5254                                    || (defaultBrowserMatch.priority < info.priority)) {
5255                                if (debug) {
5256                                    Slog.v(TAG, "Considering default browser match " + info);
5257                                }
5258                                defaultBrowserMatch = info;
5259                            }
5260                        }
5261                    }
5262                    if (defaultBrowserMatch != null
5263                            && defaultBrowserMatch.priority >= maxMatchPrio
5264                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5265                    {
5266                        if (debug) {
5267                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5268                        }
5269                        result.add(defaultBrowserMatch);
5270                    } else {
5271                        result.addAll(matchAllList);
5272                    }
5273                }
5274
5275                // If there is nothing selected, add all candidates and remove the ones that the user
5276                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5277                if (result.size() == 0) {
5278                    result.addAll(candidates);
5279                    result.removeAll(neverList);
5280                }
5281            }
5282        }
5283        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5284            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5285                    result.size());
5286            for (ResolveInfo info : result) {
5287                Slog.v(TAG, "  + " + info.activityInfo);
5288            }
5289        }
5290        return result;
5291    }
5292
5293    // Returns a packed value as a long:
5294    //
5295    // high 'int'-sized word: link status: undefined/ask/never/always.
5296    // low 'int'-sized word: relative priority among 'always' results.
5297    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5298        long result = ps.getDomainVerificationStatusForUser(userId);
5299        // if none available, get the master status
5300        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5301            if (ps.getIntentFilterVerificationInfo() != null) {
5302                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5303            }
5304        }
5305        return result;
5306    }
5307
5308    private ResolveInfo querySkipCurrentProfileIntents(
5309            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5310            int flags, int sourceUserId) {
5311        if (matchingFilters != null) {
5312            int size = matchingFilters.size();
5313            for (int i = 0; i < size; i ++) {
5314                CrossProfileIntentFilter filter = matchingFilters.get(i);
5315                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5316                    // Checking if there are activities in the target user that can handle the
5317                    // intent.
5318                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5319                            resolvedType, flags, sourceUserId);
5320                    if (resolveInfo != null) {
5321                        return resolveInfo;
5322                    }
5323                }
5324            }
5325        }
5326        return null;
5327    }
5328
5329    // Return matching ResolveInfo in target user if any.
5330    private ResolveInfo queryCrossProfileIntents(
5331            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5332            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5333        if (matchingFilters != null) {
5334            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5335            // match the same intent. For performance reasons, it is better not to
5336            // run queryIntent twice for the same userId
5337            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5338            int size = matchingFilters.size();
5339            for (int i = 0; i < size; i++) {
5340                CrossProfileIntentFilter filter = matchingFilters.get(i);
5341                int targetUserId = filter.getTargetUserId();
5342                boolean skipCurrentProfile =
5343                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5344                boolean skipCurrentProfileIfNoMatchFound =
5345                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5346                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5347                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5348                    // Checking if there are activities in the target user that can handle the
5349                    // intent.
5350                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5351                            resolvedType, flags, sourceUserId);
5352                    if (resolveInfo != null) return resolveInfo;
5353                    alreadyTriedUserIds.put(targetUserId, true);
5354                }
5355            }
5356        }
5357        return null;
5358    }
5359
5360    /**
5361     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5362     * will forward the intent to the filter's target user.
5363     * Otherwise, returns null.
5364     */
5365    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5366            String resolvedType, int flags, int sourceUserId) {
5367        int targetUserId = filter.getTargetUserId();
5368        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5369                resolvedType, flags, targetUserId);
5370        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5371                && isUserEnabled(targetUserId)) {
5372            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5373        }
5374        return null;
5375    }
5376
5377    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5378            int sourceUserId, int targetUserId) {
5379        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5380        long ident = Binder.clearCallingIdentity();
5381        boolean targetIsProfile;
5382        try {
5383            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5384        } finally {
5385            Binder.restoreCallingIdentity(ident);
5386        }
5387        String className;
5388        if (targetIsProfile) {
5389            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5390        } else {
5391            className = FORWARD_INTENT_TO_PARENT;
5392        }
5393        ComponentName forwardingActivityComponentName = new ComponentName(
5394                mAndroidApplication.packageName, className);
5395        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5396                sourceUserId);
5397        if (!targetIsProfile) {
5398            forwardingActivityInfo.showUserIcon = targetUserId;
5399            forwardingResolveInfo.noResourceId = true;
5400        }
5401        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5402        forwardingResolveInfo.priority = 0;
5403        forwardingResolveInfo.preferredOrder = 0;
5404        forwardingResolveInfo.match = 0;
5405        forwardingResolveInfo.isDefault = true;
5406        forwardingResolveInfo.filter = filter;
5407        forwardingResolveInfo.targetUserId = targetUserId;
5408        return forwardingResolveInfo;
5409    }
5410
5411    @Override
5412    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5413            Intent[] specifics, String[] specificTypes, Intent intent,
5414            String resolvedType, int flags, int userId) {
5415        if (!sUserManager.exists(userId)) return Collections.emptyList();
5416        flags = updateFlagsForResolve(flags, userId, intent);
5417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5418                false, "query intent activity options");
5419        final String resultsAction = intent.getAction();
5420
5421        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5422                | PackageManager.GET_RESOLVED_FILTER, userId);
5423
5424        if (DEBUG_INTENT_MATCHING) {
5425            Log.v(TAG, "Query " + intent + ": " + results);
5426        }
5427
5428        int specificsPos = 0;
5429        int N;
5430
5431        // todo: note that the algorithm used here is O(N^2).  This
5432        // isn't a problem in our current environment, but if we start running
5433        // into situations where we have more than 5 or 10 matches then this
5434        // should probably be changed to something smarter...
5435
5436        // First we go through and resolve each of the specific items
5437        // that were supplied, taking care of removing any corresponding
5438        // duplicate items in the generic resolve list.
5439        if (specifics != null) {
5440            for (int i=0; i<specifics.length; i++) {
5441                final Intent sintent = specifics[i];
5442                if (sintent == null) {
5443                    continue;
5444                }
5445
5446                if (DEBUG_INTENT_MATCHING) {
5447                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5448                }
5449
5450                String action = sintent.getAction();
5451                if (resultsAction != null && resultsAction.equals(action)) {
5452                    // If this action was explicitly requested, then don't
5453                    // remove things that have it.
5454                    action = null;
5455                }
5456
5457                ResolveInfo ri = null;
5458                ActivityInfo ai = null;
5459
5460                ComponentName comp = sintent.getComponent();
5461                if (comp == null) {
5462                    ri = resolveIntent(
5463                        sintent,
5464                        specificTypes != null ? specificTypes[i] : null,
5465                            flags, userId);
5466                    if (ri == null) {
5467                        continue;
5468                    }
5469                    if (ri == mResolveInfo) {
5470                        // ACK!  Must do something better with this.
5471                    }
5472                    ai = ri.activityInfo;
5473                    comp = new ComponentName(ai.applicationInfo.packageName,
5474                            ai.name);
5475                } else {
5476                    ai = getActivityInfo(comp, flags, userId);
5477                    if (ai == null) {
5478                        continue;
5479                    }
5480                }
5481
5482                // Look for any generic query activities that are duplicates
5483                // of this specific one, and remove them from the results.
5484                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5485                N = results.size();
5486                int j;
5487                for (j=specificsPos; j<N; j++) {
5488                    ResolveInfo sri = results.get(j);
5489                    if ((sri.activityInfo.name.equals(comp.getClassName())
5490                            && sri.activityInfo.applicationInfo.packageName.equals(
5491                                    comp.getPackageName()))
5492                        || (action != null && sri.filter.matchAction(action))) {
5493                        results.remove(j);
5494                        if (DEBUG_INTENT_MATCHING) Log.v(
5495                            TAG, "Removing duplicate item from " + j
5496                            + " due to specific " + specificsPos);
5497                        if (ri == null) {
5498                            ri = sri;
5499                        }
5500                        j--;
5501                        N--;
5502                    }
5503                }
5504
5505                // Add this specific item to its proper place.
5506                if (ri == null) {
5507                    ri = new ResolveInfo();
5508                    ri.activityInfo = ai;
5509                }
5510                results.add(specificsPos, ri);
5511                ri.specificIndex = i;
5512                specificsPos++;
5513            }
5514        }
5515
5516        // Now we go through the remaining generic results and remove any
5517        // duplicate actions that are found here.
5518        N = results.size();
5519        for (int i=specificsPos; i<N-1; i++) {
5520            final ResolveInfo rii = results.get(i);
5521            if (rii.filter == null) {
5522                continue;
5523            }
5524
5525            // Iterate over all of the actions of this result's intent
5526            // filter...  typically this should be just one.
5527            final Iterator<String> it = rii.filter.actionsIterator();
5528            if (it == null) {
5529                continue;
5530            }
5531            while (it.hasNext()) {
5532                final String action = it.next();
5533                if (resultsAction != null && resultsAction.equals(action)) {
5534                    // If this action was explicitly requested, then don't
5535                    // remove things that have it.
5536                    continue;
5537                }
5538                for (int j=i+1; j<N; j++) {
5539                    final ResolveInfo rij = results.get(j);
5540                    if (rij.filter != null && rij.filter.hasAction(action)) {
5541                        results.remove(j);
5542                        if (DEBUG_INTENT_MATCHING) Log.v(
5543                            TAG, "Removing duplicate item from " + j
5544                            + " due to action " + action + " at " + i);
5545                        j--;
5546                        N--;
5547                    }
5548                }
5549            }
5550
5551            // If the caller didn't request filter information, drop it now
5552            // so we don't have to marshall/unmarshall it.
5553            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5554                rii.filter = null;
5555            }
5556        }
5557
5558        // Filter out the caller activity if so requested.
5559        if (caller != null) {
5560            N = results.size();
5561            for (int i=0; i<N; i++) {
5562                ActivityInfo ainfo = results.get(i).activityInfo;
5563                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5564                        && caller.getClassName().equals(ainfo.name)) {
5565                    results.remove(i);
5566                    break;
5567                }
5568            }
5569        }
5570
5571        // If the caller didn't request filter information,
5572        // drop them now so we don't have to
5573        // marshall/unmarshall it.
5574        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5575            N = results.size();
5576            for (int i=0; i<N; i++) {
5577                results.get(i).filter = null;
5578            }
5579        }
5580
5581        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5582        return results;
5583    }
5584
5585    @Override
5586    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5587            int userId) {
5588        if (!sUserManager.exists(userId)) return Collections.emptyList();
5589        flags = updateFlagsForResolve(flags, userId, intent);
5590        ComponentName comp = intent.getComponent();
5591        if (comp == null) {
5592            if (intent.getSelector() != null) {
5593                intent = intent.getSelector();
5594                comp = intent.getComponent();
5595            }
5596        }
5597        if (comp != null) {
5598            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5599            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5600            if (ai != null) {
5601                ResolveInfo ri = new ResolveInfo();
5602                ri.activityInfo = ai;
5603                list.add(ri);
5604            }
5605            return list;
5606        }
5607
5608        // reader
5609        synchronized (mPackages) {
5610            String pkgName = intent.getPackage();
5611            if (pkgName == null) {
5612                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5613            }
5614            final PackageParser.Package pkg = mPackages.get(pkgName);
5615            if (pkg != null) {
5616                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5617                        userId);
5618            }
5619            return null;
5620        }
5621    }
5622
5623    @Override
5624    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5625        if (!sUserManager.exists(userId)) return null;
5626        flags = updateFlagsForResolve(flags, userId, intent);
5627        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5628        if (query != null) {
5629            if (query.size() >= 1) {
5630                // If there is more than one service with the same priority,
5631                // just arbitrarily pick the first one.
5632                return query.get(0);
5633            }
5634        }
5635        return null;
5636    }
5637
5638    @Override
5639    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5640            int userId) {
5641        if (!sUserManager.exists(userId)) return Collections.emptyList();
5642        flags = updateFlagsForResolve(flags, userId, intent);
5643        ComponentName comp = intent.getComponent();
5644        if (comp == null) {
5645            if (intent.getSelector() != null) {
5646                intent = intent.getSelector();
5647                comp = intent.getComponent();
5648            }
5649        }
5650        if (comp != null) {
5651            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5652            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5653            if (si != null) {
5654                final ResolveInfo ri = new ResolveInfo();
5655                ri.serviceInfo = si;
5656                list.add(ri);
5657            }
5658            return list;
5659        }
5660
5661        // reader
5662        synchronized (mPackages) {
5663            String pkgName = intent.getPackage();
5664            if (pkgName == null) {
5665                return mServices.queryIntent(intent, resolvedType, flags, userId);
5666            }
5667            final PackageParser.Package pkg = mPackages.get(pkgName);
5668            if (pkg != null) {
5669                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5670                        userId);
5671            }
5672            return null;
5673        }
5674    }
5675
5676    @Override
5677    public List<ResolveInfo> queryIntentContentProviders(
5678            Intent intent, String resolvedType, int flags, int userId) {
5679        if (!sUserManager.exists(userId)) return Collections.emptyList();
5680        flags = updateFlagsForResolve(flags, userId, intent);
5681        ComponentName comp = intent.getComponent();
5682        if (comp == null) {
5683            if (intent.getSelector() != null) {
5684                intent = intent.getSelector();
5685                comp = intent.getComponent();
5686            }
5687        }
5688        if (comp != null) {
5689            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5690            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5691            if (pi != null) {
5692                final ResolveInfo ri = new ResolveInfo();
5693                ri.providerInfo = pi;
5694                list.add(ri);
5695            }
5696            return list;
5697        }
5698
5699        // reader
5700        synchronized (mPackages) {
5701            String pkgName = intent.getPackage();
5702            if (pkgName == null) {
5703                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5704            }
5705            final PackageParser.Package pkg = mPackages.get(pkgName);
5706            if (pkg != null) {
5707                return mProviders.queryIntentForPackage(
5708                        intent, resolvedType, flags, pkg.providers, userId);
5709            }
5710            return null;
5711        }
5712    }
5713
5714    @Override
5715    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5716        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5717        flags = updateFlagsForPackage(flags, userId, null);
5718        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5719        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5720
5721        // writer
5722        synchronized (mPackages) {
5723            ArrayList<PackageInfo> list;
5724            if (listUninstalled) {
5725                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5726                for (PackageSetting ps : mSettings.mPackages.values()) {
5727                    PackageInfo pi;
5728                    if (ps.pkg != null) {
5729                        pi = generatePackageInfo(ps.pkg, flags, userId);
5730                    } else {
5731                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5732                    }
5733                    if (pi != null) {
5734                        list.add(pi);
5735                    }
5736                }
5737            } else {
5738                list = new ArrayList<PackageInfo>(mPackages.size());
5739                for (PackageParser.Package p : mPackages.values()) {
5740                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5741                    if (pi != null) {
5742                        list.add(pi);
5743                    }
5744                }
5745            }
5746
5747            return new ParceledListSlice<PackageInfo>(list);
5748        }
5749    }
5750
5751    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5752            String[] permissions, boolean[] tmp, int flags, int userId) {
5753        int numMatch = 0;
5754        final PermissionsState permissionsState = ps.getPermissionsState();
5755        for (int i=0; i<permissions.length; i++) {
5756            final String permission = permissions[i];
5757            if (permissionsState.hasPermission(permission, userId)) {
5758                tmp[i] = true;
5759                numMatch++;
5760            } else {
5761                tmp[i] = false;
5762            }
5763        }
5764        if (numMatch == 0) {
5765            return;
5766        }
5767        PackageInfo pi;
5768        if (ps.pkg != null) {
5769            pi = generatePackageInfo(ps.pkg, flags, userId);
5770        } else {
5771            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5772        }
5773        // The above might return null in cases of uninstalled apps or install-state
5774        // skew across users/profiles.
5775        if (pi != null) {
5776            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5777                if (numMatch == permissions.length) {
5778                    pi.requestedPermissions = permissions;
5779                } else {
5780                    pi.requestedPermissions = new String[numMatch];
5781                    numMatch = 0;
5782                    for (int i=0; i<permissions.length; i++) {
5783                        if (tmp[i]) {
5784                            pi.requestedPermissions[numMatch] = permissions[i];
5785                            numMatch++;
5786                        }
5787                    }
5788                }
5789            }
5790            list.add(pi);
5791        }
5792    }
5793
5794    @Override
5795    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5796            String[] permissions, int flags, int userId) {
5797        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5798        flags = updateFlagsForPackage(flags, userId, permissions);
5799        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5800
5801        // writer
5802        synchronized (mPackages) {
5803            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5804            boolean[] tmpBools = new boolean[permissions.length];
5805            if (listUninstalled) {
5806                for (PackageSetting ps : mSettings.mPackages.values()) {
5807                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5808                }
5809            } else {
5810                for (PackageParser.Package pkg : mPackages.values()) {
5811                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5812                    if (ps != null) {
5813                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5814                                userId);
5815                    }
5816                }
5817            }
5818
5819            return new ParceledListSlice<PackageInfo>(list);
5820        }
5821    }
5822
5823    @Override
5824    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5825        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5826        flags = updateFlagsForApplication(flags, userId, null);
5827        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5828
5829        // writer
5830        synchronized (mPackages) {
5831            ArrayList<ApplicationInfo> list;
5832            if (listUninstalled) {
5833                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5834                for (PackageSetting ps : mSettings.mPackages.values()) {
5835                    ApplicationInfo ai;
5836                    if (ps.pkg != null) {
5837                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5838                                ps.readUserState(userId), userId);
5839                    } else {
5840                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5841                    }
5842                    if (ai != null) {
5843                        list.add(ai);
5844                    }
5845                }
5846            } else {
5847                list = new ArrayList<ApplicationInfo>(mPackages.size());
5848                for (PackageParser.Package p : mPackages.values()) {
5849                    if (p.mExtras != null) {
5850                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5851                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5852                        if (ai != null) {
5853                            list.add(ai);
5854                        }
5855                    }
5856                }
5857            }
5858
5859            return new ParceledListSlice<ApplicationInfo>(list);
5860        }
5861    }
5862
5863    @Override
5864    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5865        if (DISABLE_EPHEMERAL_APPS) {
5866            return null;
5867        }
5868
5869        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5870                "getEphemeralApplications");
5871        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5872                "getEphemeralApplications");
5873        synchronized (mPackages) {
5874            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5875                    .getEphemeralApplicationsLPw(userId);
5876            if (ephemeralApps != null) {
5877                return new ParceledListSlice<>(ephemeralApps);
5878            }
5879        }
5880        return null;
5881    }
5882
5883    @Override
5884    public boolean isEphemeralApplication(String packageName, int userId) {
5885        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5886                "isEphemeral");
5887        if (DISABLE_EPHEMERAL_APPS) {
5888            return false;
5889        }
5890
5891        if (!isCallerSameApp(packageName)) {
5892            return false;
5893        }
5894        synchronized (mPackages) {
5895            PackageParser.Package pkg = mPackages.get(packageName);
5896            if (pkg != null) {
5897                return pkg.applicationInfo.isEphemeralApp();
5898            }
5899        }
5900        return false;
5901    }
5902
5903    @Override
5904    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5905        if (DISABLE_EPHEMERAL_APPS) {
5906            return null;
5907        }
5908
5909        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5910                "getCookie");
5911        if (!isCallerSameApp(packageName)) {
5912            return null;
5913        }
5914        synchronized (mPackages) {
5915            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5916                    packageName, userId);
5917        }
5918    }
5919
5920    @Override
5921    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5922        if (DISABLE_EPHEMERAL_APPS) {
5923            return true;
5924        }
5925
5926        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5927                "setCookie");
5928        if (!isCallerSameApp(packageName)) {
5929            return false;
5930        }
5931        synchronized (mPackages) {
5932            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5933                    packageName, cookie, userId);
5934        }
5935    }
5936
5937    @Override
5938    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5939        if (DISABLE_EPHEMERAL_APPS) {
5940            return null;
5941        }
5942
5943        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5944                "getEphemeralApplicationIcon");
5945        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5946                "getEphemeralApplicationIcon");
5947        synchronized (mPackages) {
5948            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5949                    packageName, userId);
5950        }
5951    }
5952
5953    private boolean isCallerSameApp(String packageName) {
5954        PackageParser.Package pkg = mPackages.get(packageName);
5955        return pkg != null
5956                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5957    }
5958
5959    public List<ApplicationInfo> getPersistentApplications(int flags) {
5960        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5961
5962        // reader
5963        synchronized (mPackages) {
5964            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5965            final int userId = UserHandle.getCallingUserId();
5966            while (i.hasNext()) {
5967                final PackageParser.Package p = i.next();
5968                if (p.applicationInfo != null
5969                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5970                        && (!mSafeMode || isSystemApp(p))) {
5971                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5972                    if (ps != null) {
5973                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5974                                ps.readUserState(userId), userId);
5975                        if (ai != null) {
5976                            finalList.add(ai);
5977                        }
5978                    }
5979                }
5980            }
5981        }
5982
5983        return finalList;
5984    }
5985
5986    @Override
5987    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5988        if (!sUserManager.exists(userId)) return null;
5989        flags = updateFlagsForComponent(flags, userId, name);
5990        // reader
5991        synchronized (mPackages) {
5992            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5993            PackageSetting ps = provider != null
5994                    ? mSettings.mPackages.get(provider.owner.packageName)
5995                    : null;
5996            return ps != null
5997                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5998                    ? PackageParser.generateProviderInfo(provider, flags,
5999                            ps.readUserState(userId), userId)
6000                    : null;
6001        }
6002    }
6003
6004    /**
6005     * @deprecated
6006     */
6007    @Deprecated
6008    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6009        // reader
6010        synchronized (mPackages) {
6011            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6012                    .entrySet().iterator();
6013            final int userId = UserHandle.getCallingUserId();
6014            while (i.hasNext()) {
6015                Map.Entry<String, PackageParser.Provider> entry = i.next();
6016                PackageParser.Provider p = entry.getValue();
6017                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6018
6019                if (ps != null && p.syncable
6020                        && (!mSafeMode || (p.info.applicationInfo.flags
6021                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6022                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6023                            ps.readUserState(userId), userId);
6024                    if (info != null) {
6025                        outNames.add(entry.getKey());
6026                        outInfo.add(info);
6027                    }
6028                }
6029            }
6030        }
6031    }
6032
6033    @Override
6034    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6035            int uid, int flags) {
6036        final int userId = processName != null ? UserHandle.getUserId(uid)
6037                : UserHandle.getCallingUserId();
6038        if (!sUserManager.exists(userId)) return null;
6039        flags = updateFlagsForComponent(flags, userId, processName);
6040
6041        ArrayList<ProviderInfo> finalList = null;
6042        // reader
6043        synchronized (mPackages) {
6044            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6045            while (i.hasNext()) {
6046                final PackageParser.Provider p = i.next();
6047                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6048                if (ps != null && p.info.authority != null
6049                        && (processName == null
6050                                || (p.info.processName.equals(processName)
6051                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6052                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6053                    if (finalList == null) {
6054                        finalList = new ArrayList<ProviderInfo>(3);
6055                    }
6056                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6057                            ps.readUserState(userId), userId);
6058                    if (info != null) {
6059                        finalList.add(info);
6060                    }
6061                }
6062            }
6063        }
6064
6065        if (finalList != null) {
6066            Collections.sort(finalList, mProviderInitOrderSorter);
6067            return new ParceledListSlice<ProviderInfo>(finalList);
6068        }
6069
6070        return null;
6071    }
6072
6073    @Override
6074    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6075        // reader
6076        synchronized (mPackages) {
6077            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6078            return PackageParser.generateInstrumentationInfo(i, flags);
6079        }
6080    }
6081
6082    @Override
6083    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6084            int flags) {
6085        ArrayList<InstrumentationInfo> finalList =
6086            new ArrayList<InstrumentationInfo>();
6087
6088        // reader
6089        synchronized (mPackages) {
6090            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6091            while (i.hasNext()) {
6092                final PackageParser.Instrumentation p = i.next();
6093                if (targetPackage == null
6094                        || targetPackage.equals(p.info.targetPackage)) {
6095                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6096                            flags);
6097                    if (ii != null) {
6098                        finalList.add(ii);
6099                    }
6100                }
6101            }
6102        }
6103
6104        return finalList;
6105    }
6106
6107    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6108        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6109        if (overlays == null) {
6110            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6111            return;
6112        }
6113        for (PackageParser.Package opkg : overlays.values()) {
6114            // Not much to do if idmap fails: we already logged the error
6115            // and we certainly don't want to abort installation of pkg simply
6116            // because an overlay didn't fit properly. For these reasons,
6117            // ignore the return value of createIdmapForPackagePairLI.
6118            createIdmapForPackagePairLI(pkg, opkg);
6119        }
6120    }
6121
6122    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6123            PackageParser.Package opkg) {
6124        if (!opkg.mTrustedOverlay) {
6125            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6126                    opkg.baseCodePath + ": overlay not trusted");
6127            return false;
6128        }
6129        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6130        if (overlaySet == null) {
6131            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6132                    opkg.baseCodePath + " but target package has no known overlays");
6133            return false;
6134        }
6135        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6136        // TODO: generate idmap for split APKs
6137        try {
6138            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6139        } catch (InstallerException e) {
6140            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6141                    + opkg.baseCodePath);
6142            return false;
6143        }
6144        PackageParser.Package[] overlayArray =
6145            overlaySet.values().toArray(new PackageParser.Package[0]);
6146        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6147            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6148                return p1.mOverlayPriority - p2.mOverlayPriority;
6149            }
6150        };
6151        Arrays.sort(overlayArray, cmp);
6152
6153        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6154        int i = 0;
6155        for (PackageParser.Package p : overlayArray) {
6156            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6157        }
6158        return true;
6159    }
6160
6161    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6162        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6163        try {
6164            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6165        } finally {
6166            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6167        }
6168    }
6169
6170    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6171        final File[] files = dir.listFiles();
6172        if (ArrayUtils.isEmpty(files)) {
6173            Log.d(TAG, "No files in app dir " + dir);
6174            return;
6175        }
6176
6177        if (DEBUG_PACKAGE_SCANNING) {
6178            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6179                    + " flags=0x" + Integer.toHexString(parseFlags));
6180        }
6181
6182        for (File file : files) {
6183            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6184                    && !PackageInstallerService.isStageName(file.getName());
6185            if (!isPackage) {
6186                // Ignore entries which are not packages
6187                continue;
6188            }
6189            try {
6190                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6191                        scanFlags, currentTime, null);
6192            } catch (PackageManagerException e) {
6193                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6194
6195                // Delete invalid userdata apps
6196                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6197                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6198                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6199                    removeCodePathLI(file);
6200                }
6201            }
6202        }
6203    }
6204
6205    private static File getSettingsProblemFile() {
6206        File dataDir = Environment.getDataDirectory();
6207        File systemDir = new File(dataDir, "system");
6208        File fname = new File(systemDir, "uiderrors.txt");
6209        return fname;
6210    }
6211
6212    static void reportSettingsProblem(int priority, String msg) {
6213        logCriticalInfo(priority, msg);
6214    }
6215
6216    static void logCriticalInfo(int priority, String msg) {
6217        Slog.println(priority, TAG, msg);
6218        EventLogTags.writePmCriticalInfo(msg);
6219        try {
6220            File fname = getSettingsProblemFile();
6221            FileOutputStream out = new FileOutputStream(fname, true);
6222            PrintWriter pw = new FastPrintWriter(out);
6223            SimpleDateFormat formatter = new SimpleDateFormat();
6224            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6225            pw.println(dateString + ": " + msg);
6226            pw.close();
6227            FileUtils.setPermissions(
6228                    fname.toString(),
6229                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6230                    -1, -1);
6231        } catch (java.io.IOException e) {
6232        }
6233    }
6234
6235    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6236            PackageParser.Package pkg, File srcFile, int parseFlags)
6237            throws PackageManagerException {
6238        if (ps != null
6239                && ps.codePath.equals(srcFile)
6240                && ps.timeStamp == srcFile.lastModified()
6241                && !isCompatSignatureUpdateNeeded(pkg)
6242                && !isRecoverSignatureUpdateNeeded(pkg)) {
6243            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6244            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6245            ArraySet<PublicKey> signingKs;
6246            synchronized (mPackages) {
6247                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6248            }
6249            if (ps.signatures.mSignatures != null
6250                    && ps.signatures.mSignatures.length != 0
6251                    && signingKs != null) {
6252                // Optimization: reuse the existing cached certificates
6253                // if the package appears to be unchanged.
6254                pkg.mSignatures = ps.signatures.mSignatures;
6255                pkg.mSigningKeys = signingKs;
6256                return;
6257            }
6258
6259            Slog.w(TAG, "PackageSetting for " + ps.name
6260                    + " is missing signatures.  Collecting certs again to recover them.");
6261        } else {
6262            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6263        }
6264
6265        try {
6266            pp.collectCertificates(pkg, parseFlags);
6267        } catch (PackageParserException e) {
6268            throw PackageManagerException.from(e);
6269        }
6270    }
6271
6272    /**
6273     *  Traces a package scan.
6274     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6275     */
6276    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6277            long currentTime, UserHandle user) throws PackageManagerException {
6278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6279        try {
6280            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6281        } finally {
6282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6283        }
6284    }
6285
6286    /**
6287     *  Scans a package and returns the newly parsed package.
6288     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6289     */
6290    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6291            long currentTime, UserHandle user) throws PackageManagerException {
6292        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6293        parseFlags |= mDefParseFlags;
6294        PackageParser pp = new PackageParser();
6295        pp.setSeparateProcesses(mSeparateProcesses);
6296        pp.setOnlyCoreApps(mOnlyCore);
6297        pp.setDisplayMetrics(mMetrics);
6298
6299        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6300            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6301        }
6302
6303        final PackageParser.Package pkg;
6304        try {
6305            pkg = pp.parsePackage(scanFile, parseFlags);
6306        } catch (PackageParserException e) {
6307            throw PackageManagerException.from(e);
6308        }
6309
6310        PackageSetting ps = null;
6311        PackageSetting updatedPkg;
6312        // reader
6313        synchronized (mPackages) {
6314            // Look to see if we already know about this package.
6315            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6316            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6317                // This package has been renamed to its original name.  Let's
6318                // use that.
6319                ps = mSettings.peekPackageLPr(oldName);
6320            }
6321            // If there was no original package, see one for the real package name.
6322            if (ps == null) {
6323                ps = mSettings.peekPackageLPr(pkg.packageName);
6324            }
6325            // Check to see if this package could be hiding/updating a system
6326            // package.  Must look for it either under the original or real
6327            // package name depending on our state.
6328            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6329            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6330        }
6331        boolean updatedPkgBetter = false;
6332        // First check if this is a system package that may involve an update
6333        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6334            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6335            // it needs to drop FLAG_PRIVILEGED.
6336            if (locationIsPrivileged(scanFile)) {
6337                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6338            } else {
6339                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6340            }
6341
6342            if (ps != null && !ps.codePath.equals(scanFile)) {
6343                // The path has changed from what was last scanned...  check the
6344                // version of the new path against what we have stored to determine
6345                // what to do.
6346                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6347                if (pkg.mVersionCode <= ps.versionCode) {
6348                    // The system package has been updated and the code path does not match
6349                    // Ignore entry. Skip it.
6350                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6351                            + " ignored: updated version " + ps.versionCode
6352                            + " better than this " + pkg.mVersionCode);
6353                    if (!updatedPkg.codePath.equals(scanFile)) {
6354                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6355                                + ps.name + " changing from " + updatedPkg.codePathString
6356                                + " to " + scanFile);
6357                        updatedPkg.codePath = scanFile;
6358                        updatedPkg.codePathString = scanFile.toString();
6359                        updatedPkg.resourcePath = scanFile;
6360                        updatedPkg.resourcePathString = scanFile.toString();
6361                    }
6362                    updatedPkg.pkg = pkg;
6363                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6364                            "Package " + ps.name + " at " + scanFile
6365                                    + " ignored: updated version " + ps.versionCode
6366                                    + " better than this " + pkg.mVersionCode);
6367                } else {
6368                    // The current app on the system partition is better than
6369                    // what we have updated to on the data partition; switch
6370                    // back to the system partition version.
6371                    // At this point, its safely assumed that package installation for
6372                    // apps in system partition will go through. If not there won't be a working
6373                    // version of the app
6374                    // writer
6375                    synchronized (mPackages) {
6376                        // Just remove the loaded entries from package lists.
6377                        mPackages.remove(ps.name);
6378                    }
6379
6380                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6381                            + " reverting from " + ps.codePathString
6382                            + ": new version " + pkg.mVersionCode
6383                            + " better than installed " + ps.versionCode);
6384
6385                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6386                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6387                    synchronized (mInstallLock) {
6388                        args.cleanUpResourcesLI();
6389                    }
6390                    synchronized (mPackages) {
6391                        mSettings.enableSystemPackageLPw(ps.name);
6392                    }
6393                    updatedPkgBetter = true;
6394                }
6395            }
6396        }
6397
6398        if (updatedPkg != null) {
6399            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6400            // initially
6401            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6402
6403            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6404            // flag set initially
6405            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6406                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6407            }
6408        }
6409
6410        // Verify certificates against what was last scanned
6411        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6412
6413        /*
6414         * A new system app appeared, but we already had a non-system one of the
6415         * same name installed earlier.
6416         */
6417        boolean shouldHideSystemApp = false;
6418        if (updatedPkg == null && ps != null
6419                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6420            /*
6421             * Check to make sure the signatures match first. If they don't,
6422             * wipe the installed application and its data.
6423             */
6424            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6425                    != PackageManager.SIGNATURE_MATCH) {
6426                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6427                        + " signatures don't match existing userdata copy; removing");
6428                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6429                ps = null;
6430            } else {
6431                /*
6432                 * If the newly-added system app is an older version than the
6433                 * already installed version, hide it. It will be scanned later
6434                 * and re-added like an update.
6435                 */
6436                if (pkg.mVersionCode <= ps.versionCode) {
6437                    shouldHideSystemApp = true;
6438                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6439                            + " but new version " + pkg.mVersionCode + " better than installed "
6440                            + ps.versionCode + "; hiding system");
6441                } else {
6442                    /*
6443                     * The newly found system app is a newer version that the
6444                     * one previously installed. Simply remove the
6445                     * already-installed application and replace it with our own
6446                     * while keeping the application data.
6447                     */
6448                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6449                            + " reverting from " + ps.codePathString + ": new version "
6450                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6451                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6452                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6453                    synchronized (mInstallLock) {
6454                        args.cleanUpResourcesLI();
6455                    }
6456                }
6457            }
6458        }
6459
6460        // The apk is forward locked (not public) if its code and resources
6461        // are kept in different files. (except for app in either system or
6462        // vendor path).
6463        // TODO grab this value from PackageSettings
6464        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6465            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6466                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6467            }
6468        }
6469
6470        // TODO: extend to support forward-locked splits
6471        String resourcePath = null;
6472        String baseResourcePath = null;
6473        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6474            if (ps != null && ps.resourcePathString != null) {
6475                resourcePath = ps.resourcePathString;
6476                baseResourcePath = ps.resourcePathString;
6477            } else {
6478                // Should not happen at all. Just log an error.
6479                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6480            }
6481        } else {
6482            resourcePath = pkg.codePath;
6483            baseResourcePath = pkg.baseCodePath;
6484        }
6485
6486        // Set application objects path explicitly.
6487        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6488        pkg.applicationInfo.setCodePath(pkg.codePath);
6489        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6490        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6491        pkg.applicationInfo.setResourcePath(resourcePath);
6492        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6493        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6494
6495        // Note that we invoke the following method only if we are about to unpack an application
6496        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6497                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6498
6499        /*
6500         * If the system app should be overridden by a previously installed
6501         * data, hide the system app now and let the /data/app scan pick it up
6502         * again.
6503         */
6504        if (shouldHideSystemApp) {
6505            synchronized (mPackages) {
6506                mSettings.disableSystemPackageLPw(pkg.packageName);
6507            }
6508        }
6509
6510        return scannedPkg;
6511    }
6512
6513    private static String fixProcessName(String defProcessName,
6514            String processName, int uid) {
6515        if (processName == null) {
6516            return defProcessName;
6517        }
6518        return processName;
6519    }
6520
6521    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6522            throws PackageManagerException {
6523        if (pkgSetting.signatures.mSignatures != null) {
6524            // Already existing package. Make sure signatures match
6525            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6526                    == PackageManager.SIGNATURE_MATCH;
6527            if (!match) {
6528                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6529                        == PackageManager.SIGNATURE_MATCH;
6530            }
6531            if (!match) {
6532                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6533                        == PackageManager.SIGNATURE_MATCH;
6534            }
6535            if (!match) {
6536                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6537                        + pkg.packageName + " signatures do not match the "
6538                        + "previously installed version; ignoring!");
6539            }
6540        }
6541
6542        // Check for shared user signatures
6543        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6544            // Already existing package. Make sure signatures match
6545            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6546                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6547            if (!match) {
6548                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6549                        == PackageManager.SIGNATURE_MATCH;
6550            }
6551            if (!match) {
6552                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6553                        == PackageManager.SIGNATURE_MATCH;
6554            }
6555            if (!match) {
6556                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6557                        "Package " + pkg.packageName
6558                        + " has no signatures that match those in shared user "
6559                        + pkgSetting.sharedUser.name + "; ignoring!");
6560            }
6561        }
6562    }
6563
6564    /**
6565     * Enforces that only the system UID or root's UID can call a method exposed
6566     * via Binder.
6567     *
6568     * @param message used as message if SecurityException is thrown
6569     * @throws SecurityException if the caller is not system or root
6570     */
6571    private static final void enforceSystemOrRoot(String message) {
6572        final int uid = Binder.getCallingUid();
6573        if (uid != Process.SYSTEM_UID && uid != 0) {
6574            throw new SecurityException(message);
6575        }
6576    }
6577
6578    @Override
6579    public void performFstrimIfNeeded() {
6580        enforceSystemOrRoot("Only the system can request fstrim");
6581
6582        // Before everything else, see whether we need to fstrim.
6583        try {
6584            IMountService ms = PackageHelper.getMountService();
6585            if (ms != null) {
6586                final boolean isUpgrade = isUpgrade();
6587                boolean doTrim = isUpgrade;
6588                if (doTrim) {
6589                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6590                } else {
6591                    final long interval = android.provider.Settings.Global.getLong(
6592                            mContext.getContentResolver(),
6593                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6594                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6595                    if (interval > 0) {
6596                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6597                        if (timeSinceLast > interval) {
6598                            doTrim = true;
6599                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6600                                    + "; running immediately");
6601                        }
6602                    }
6603                }
6604                if (doTrim) {
6605                    if (!isFirstBoot()) {
6606                        try {
6607                            ActivityManagerNative.getDefault().showBootMessage(
6608                                    mContext.getResources().getString(
6609                                            R.string.android_upgrading_fstrim), true);
6610                        } catch (RemoteException e) {
6611                        }
6612                    }
6613                    ms.runMaintenance();
6614                }
6615            } else {
6616                Slog.e(TAG, "Mount service unavailable!");
6617            }
6618        } catch (RemoteException e) {
6619            // Can't happen; MountService is local
6620        }
6621    }
6622
6623    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6624        List<ResolveInfo> ris = null;
6625        try {
6626            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6627                    intent, null, 0, userId);
6628        } catch (RemoteException e) {
6629        }
6630        ArraySet<String> pkgNames = new ArraySet<String>();
6631        if (ris != null) {
6632            for (ResolveInfo ri : ris) {
6633                pkgNames.add(ri.activityInfo.packageName);
6634            }
6635        }
6636        return pkgNames;
6637    }
6638
6639    @Override
6640    public void notifyPackageUse(String packageName) {
6641        synchronized (mPackages) {
6642            PackageParser.Package p = mPackages.get(packageName);
6643            if (p == null) {
6644                return;
6645            }
6646            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6647        }
6648    }
6649
6650    @Override
6651    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6652        return performDexOptTraced(packageName, instructionSet);
6653    }
6654
6655    public boolean performDexOpt(String packageName, String instructionSet) {
6656        return performDexOptTraced(packageName, instructionSet);
6657    }
6658
6659    private boolean performDexOptTraced(String packageName, String instructionSet) {
6660        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6661        try {
6662            return performDexOptInternal(packageName, instructionSet);
6663        } finally {
6664            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6665        }
6666    }
6667
6668    private boolean performDexOptInternal(String packageName, String instructionSet) {
6669        PackageParser.Package p;
6670        final String targetInstructionSet;
6671        synchronized (mPackages) {
6672            p = mPackages.get(packageName);
6673            if (p == null) {
6674                return false;
6675            }
6676            mPackageUsage.write(false);
6677
6678            targetInstructionSet = instructionSet != null ? instructionSet :
6679                    getPrimaryInstructionSet(p.applicationInfo);
6680            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6681                return false;
6682            }
6683        }
6684        long callingId = Binder.clearCallingIdentity();
6685        try {
6686            synchronized (mInstallLock) {
6687                final String[] instructionSets = new String[] { targetInstructionSet };
6688                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6689                        true /* inclDependencies */);
6690                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6691            }
6692        } finally {
6693            Binder.restoreCallingIdentity(callingId);
6694        }
6695    }
6696
6697    public ArraySet<String> getPackagesThatNeedDexOpt() {
6698        ArraySet<String> pkgs = null;
6699        synchronized (mPackages) {
6700            for (PackageParser.Package p : mPackages.values()) {
6701                if (DEBUG_DEXOPT) {
6702                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6703                }
6704                if (!p.mDexOptPerformed.isEmpty()) {
6705                    continue;
6706                }
6707                if (pkgs == null) {
6708                    pkgs = new ArraySet<String>();
6709                }
6710                pkgs.add(p.packageName);
6711            }
6712        }
6713        return pkgs;
6714    }
6715
6716    public void shutdown() {
6717        mPackageUsage.write(true);
6718    }
6719
6720    @Override
6721    public void forceDexOpt(String packageName) {
6722        enforceSystemOrRoot("forceDexOpt");
6723
6724        PackageParser.Package pkg;
6725        synchronized (mPackages) {
6726            pkg = mPackages.get(packageName);
6727            if (pkg == null) {
6728                throw new IllegalArgumentException("Unknown package: " + packageName);
6729            }
6730        }
6731
6732        synchronized (mInstallLock) {
6733            final String[] instructionSets = new String[] {
6734                    getPrimaryInstructionSet(pkg.applicationInfo) };
6735
6736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6737
6738            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6739                    true /* inclDependencies */);
6740
6741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6742            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6743                throw new IllegalStateException("Failed to dexopt: " + res);
6744            }
6745        }
6746    }
6747
6748    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6749        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6750            Slog.w(TAG, "Unable to update from " + oldPkg.name
6751                    + " to " + newPkg.packageName
6752                    + ": old package not in system partition");
6753            return false;
6754        } else if (mPackages.get(oldPkg.name) != null) {
6755            Slog.w(TAG, "Unable to update from " + oldPkg.name
6756                    + " to " + newPkg.packageName
6757                    + ": old package still exists");
6758            return false;
6759        }
6760        return true;
6761    }
6762
6763    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6764        // TODO: triage flags as part of 26466827
6765        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6766
6767        boolean res = true;
6768        final int[] users = sUserManager.getUserIds();
6769        for (int user : users) {
6770            try {
6771                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6772            } catch (InstallerException e) {
6773                Slog.w(TAG, "Failed to delete data directory", e);
6774                res = false;
6775            }
6776        }
6777        return res;
6778    }
6779
6780    void removeCodePathLI(File codePath) {
6781        if (codePath.isDirectory()) {
6782            try {
6783                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6784            } catch (InstallerException e) {
6785                Slog.w(TAG, "Failed to remove code path", e);
6786            }
6787        } else {
6788            codePath.delete();
6789        }
6790    }
6791
6792    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6793        try {
6794            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6795        } catch (InstallerException e) {
6796            Slog.w(TAG, "Failed to destroy app data", e);
6797        }
6798    }
6799
6800    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6801            int appId, String seinfo) {
6802        try {
6803            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6804        } catch (InstallerException e) {
6805            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6806        }
6807    }
6808
6809    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6810        // TODO: triage flags as part of 26466827
6811        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6812
6813        final int[] users = sUserManager.getUserIds();
6814        for (int user : users) {
6815            try {
6816                mInstaller.clearAppData(volumeUuid, packageName, user,
6817                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6818            } catch (InstallerException e) {
6819                Slog.w(TAG, "Failed to delete code cache directory", e);
6820            }
6821        }
6822    }
6823
6824    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6825            PackageParser.Package changingLib) {
6826        if (file.path != null) {
6827            usesLibraryFiles.add(file.path);
6828            return;
6829        }
6830        PackageParser.Package p = mPackages.get(file.apk);
6831        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6832            // If we are doing this while in the middle of updating a library apk,
6833            // then we need to make sure to use that new apk for determining the
6834            // dependencies here.  (We haven't yet finished committing the new apk
6835            // to the package manager state.)
6836            if (p == null || p.packageName.equals(changingLib.packageName)) {
6837                p = changingLib;
6838            }
6839        }
6840        if (p != null) {
6841            usesLibraryFiles.addAll(p.getAllCodePaths());
6842        }
6843    }
6844
6845    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6846            PackageParser.Package changingLib) throws PackageManagerException {
6847        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6848            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6849            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6850            for (int i=0; i<N; i++) {
6851                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6852                if (file == null) {
6853                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6854                            "Package " + pkg.packageName + " requires unavailable shared library "
6855                            + pkg.usesLibraries.get(i) + "; failing!");
6856                }
6857                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6858            }
6859            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6860            for (int i=0; i<N; i++) {
6861                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6862                if (file == null) {
6863                    Slog.w(TAG, "Package " + pkg.packageName
6864                            + " desires unavailable shared library "
6865                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6866                } else {
6867                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6868                }
6869            }
6870            N = usesLibraryFiles.size();
6871            if (N > 0) {
6872                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6873            } else {
6874                pkg.usesLibraryFiles = null;
6875            }
6876        }
6877    }
6878
6879    private static boolean hasString(List<String> list, List<String> which) {
6880        if (list == null) {
6881            return false;
6882        }
6883        for (int i=list.size()-1; i>=0; i--) {
6884            for (int j=which.size()-1; j>=0; j--) {
6885                if (which.get(j).equals(list.get(i))) {
6886                    return true;
6887                }
6888            }
6889        }
6890        return false;
6891    }
6892
6893    private void updateAllSharedLibrariesLPw() {
6894        for (PackageParser.Package pkg : mPackages.values()) {
6895            try {
6896                updateSharedLibrariesLPw(pkg, null);
6897            } catch (PackageManagerException e) {
6898                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6899            }
6900        }
6901    }
6902
6903    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6904            PackageParser.Package changingPkg) {
6905        ArrayList<PackageParser.Package> res = null;
6906        for (PackageParser.Package pkg : mPackages.values()) {
6907            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6908                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6909                if (res == null) {
6910                    res = new ArrayList<PackageParser.Package>();
6911                }
6912                res.add(pkg);
6913                try {
6914                    updateSharedLibrariesLPw(pkg, changingPkg);
6915                } catch (PackageManagerException e) {
6916                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6917                }
6918            }
6919        }
6920        return res;
6921    }
6922
6923    /**
6924     * Derive the value of the {@code cpuAbiOverride} based on the provided
6925     * value and an optional stored value from the package settings.
6926     */
6927    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6928        String cpuAbiOverride = null;
6929
6930        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6931            cpuAbiOverride = null;
6932        } else if (abiOverride != null) {
6933            cpuAbiOverride = abiOverride;
6934        } else if (settings != null) {
6935            cpuAbiOverride = settings.cpuAbiOverrideString;
6936        }
6937
6938        return cpuAbiOverride;
6939    }
6940
6941    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6942            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6943        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6944        try {
6945            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6946        } finally {
6947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6948        }
6949    }
6950
6951    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6952            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6953        boolean success = false;
6954        try {
6955            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6956                    currentTime, user);
6957            success = true;
6958            return res;
6959        } finally {
6960            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6961                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6962            }
6963        }
6964    }
6965
6966    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6967            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6968        final File scanFile = new File(pkg.codePath);
6969        if (pkg.applicationInfo.getCodePath() == null ||
6970                pkg.applicationInfo.getResourcePath() == null) {
6971            // Bail out. The resource and code paths haven't been set.
6972            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6973                    "Code and resource paths haven't been set correctly");
6974        }
6975
6976        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6977            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6978        } else {
6979            // Only allow system apps to be flagged as core apps.
6980            pkg.coreApp = false;
6981        }
6982
6983        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6984            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6985        }
6986
6987        if (mCustomResolverComponentName != null &&
6988                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6989            setUpCustomResolverActivity(pkg);
6990        }
6991
6992        if (pkg.packageName.equals("android")) {
6993            synchronized (mPackages) {
6994                if (mAndroidApplication != null) {
6995                    Slog.w(TAG, "*************************************************");
6996                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6997                    Slog.w(TAG, " file=" + scanFile);
6998                    Slog.w(TAG, "*************************************************");
6999                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7000                            "Core android package being redefined.  Skipping.");
7001                }
7002
7003                // Set up information for our fall-back user intent resolution activity.
7004                mPlatformPackage = pkg;
7005                pkg.mVersionCode = mSdkVersion;
7006                mAndroidApplication = pkg.applicationInfo;
7007
7008                if (!mResolverReplaced) {
7009                    mResolveActivity.applicationInfo = mAndroidApplication;
7010                    mResolveActivity.name = ResolverActivity.class.getName();
7011                    mResolveActivity.packageName = mAndroidApplication.packageName;
7012                    mResolveActivity.processName = "system:ui";
7013                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7014                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7015                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7016                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7017                    mResolveActivity.exported = true;
7018                    mResolveActivity.enabled = true;
7019                    mResolveInfo.activityInfo = mResolveActivity;
7020                    mResolveInfo.priority = 0;
7021                    mResolveInfo.preferredOrder = 0;
7022                    mResolveInfo.match = 0;
7023                    mResolveComponentName = new ComponentName(
7024                            mAndroidApplication.packageName, mResolveActivity.name);
7025                }
7026            }
7027        }
7028
7029        if (DEBUG_PACKAGE_SCANNING) {
7030            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7031                Log.d(TAG, "Scanning package " + pkg.packageName);
7032        }
7033
7034        if (mPackages.containsKey(pkg.packageName)
7035                || mSharedLibraries.containsKey(pkg.packageName)) {
7036            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7037                    "Application package " + pkg.packageName
7038                    + " already installed.  Skipping duplicate.");
7039        }
7040
7041        // If we're only installing presumed-existing packages, require that the
7042        // scanned APK is both already known and at the path previously established
7043        // for it.  Previously unknown packages we pick up normally, but if we have an
7044        // a priori expectation about this package's install presence, enforce it.
7045        // With a singular exception for new system packages. When an OTA contains
7046        // a new system package, we allow the codepath to change from a system location
7047        // to the user-installed location. If we don't allow this change, any newer,
7048        // user-installed version of the application will be ignored.
7049        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7050            if (mExpectingBetter.containsKey(pkg.packageName)) {
7051                logCriticalInfo(Log.WARN,
7052                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7053            } else {
7054                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7055                if (known != null) {
7056                    if (DEBUG_PACKAGE_SCANNING) {
7057                        Log.d(TAG, "Examining " + pkg.codePath
7058                                + " and requiring known paths " + known.codePathString
7059                                + " & " + known.resourcePathString);
7060                    }
7061                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7062                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7063                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7064                                "Application package " + pkg.packageName
7065                                + " found at " + pkg.applicationInfo.getCodePath()
7066                                + " but expected at " + known.codePathString + "; ignoring.");
7067                    }
7068                }
7069            }
7070        }
7071
7072        // Initialize package source and resource directories
7073        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7074        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7075
7076        SharedUserSetting suid = null;
7077        PackageSetting pkgSetting = null;
7078
7079        if (!isSystemApp(pkg)) {
7080            // Only system apps can use these features.
7081            pkg.mOriginalPackages = null;
7082            pkg.mRealPackage = null;
7083            pkg.mAdoptPermissions = null;
7084        }
7085
7086        // writer
7087        synchronized (mPackages) {
7088            if (pkg.mSharedUserId != null) {
7089                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7090                if (suid == null) {
7091                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7092                            "Creating application package " + pkg.packageName
7093                            + " for shared user failed");
7094                }
7095                if (DEBUG_PACKAGE_SCANNING) {
7096                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7097                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7098                                + "): packages=" + suid.packages);
7099                }
7100            }
7101
7102            // Check if we are renaming from an original package name.
7103            PackageSetting origPackage = null;
7104            String realName = null;
7105            if (pkg.mOriginalPackages != null) {
7106                // This package may need to be renamed to a previously
7107                // installed name.  Let's check on that...
7108                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7109                if (pkg.mOriginalPackages.contains(renamed)) {
7110                    // This package had originally been installed as the
7111                    // original name, and we have already taken care of
7112                    // transitioning to the new one.  Just update the new
7113                    // one to continue using the old name.
7114                    realName = pkg.mRealPackage;
7115                    if (!pkg.packageName.equals(renamed)) {
7116                        // Callers into this function may have already taken
7117                        // care of renaming the package; only do it here if
7118                        // it is not already done.
7119                        pkg.setPackageName(renamed);
7120                    }
7121
7122                } else {
7123                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7124                        if ((origPackage = mSettings.peekPackageLPr(
7125                                pkg.mOriginalPackages.get(i))) != null) {
7126                            // We do have the package already installed under its
7127                            // original name...  should we use it?
7128                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7129                                // New package is not compatible with original.
7130                                origPackage = null;
7131                                continue;
7132                            } else if (origPackage.sharedUser != null) {
7133                                // Make sure uid is compatible between packages.
7134                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7135                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7136                                            + " to " + pkg.packageName + ": old uid "
7137                                            + origPackage.sharedUser.name
7138                                            + " differs from " + pkg.mSharedUserId);
7139                                    origPackage = null;
7140                                    continue;
7141                                }
7142                            } else {
7143                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7144                                        + pkg.packageName + " to old name " + origPackage.name);
7145                            }
7146                            break;
7147                        }
7148                    }
7149                }
7150            }
7151
7152            if (mTransferedPackages.contains(pkg.packageName)) {
7153                Slog.w(TAG, "Package " + pkg.packageName
7154                        + " was transferred to another, but its .apk remains");
7155            }
7156
7157            // Just create the setting, don't add it yet. For already existing packages
7158            // the PkgSetting exists already and doesn't have to be created.
7159            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7160                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7161                    pkg.applicationInfo.primaryCpuAbi,
7162                    pkg.applicationInfo.secondaryCpuAbi,
7163                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7164                    user, false);
7165            if (pkgSetting == null) {
7166                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7167                        "Creating application package " + pkg.packageName + " failed");
7168            }
7169
7170            if (pkgSetting.origPackage != null) {
7171                // If we are first transitioning from an original package,
7172                // fix up the new package's name now.  We need to do this after
7173                // looking up the package under its new name, so getPackageLP
7174                // can take care of fiddling things correctly.
7175                pkg.setPackageName(origPackage.name);
7176
7177                // File a report about this.
7178                String msg = "New package " + pkgSetting.realName
7179                        + " renamed to replace old package " + pkgSetting.name;
7180                reportSettingsProblem(Log.WARN, msg);
7181
7182                // Make a note of it.
7183                mTransferedPackages.add(origPackage.name);
7184
7185                // No longer need to retain this.
7186                pkgSetting.origPackage = null;
7187            }
7188
7189            if (realName != null) {
7190                // Make a note of it.
7191                mTransferedPackages.add(pkg.packageName);
7192            }
7193
7194            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7195                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7196            }
7197
7198            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7199                // Check all shared libraries and map to their actual file path.
7200                // We only do this here for apps not on a system dir, because those
7201                // are the only ones that can fail an install due to this.  We
7202                // will take care of the system apps by updating all of their
7203                // library paths after the scan is done.
7204                updateSharedLibrariesLPw(pkg, null);
7205            }
7206
7207            if (mFoundPolicyFile) {
7208                SELinuxMMAC.assignSeinfoValue(pkg);
7209            }
7210
7211            pkg.applicationInfo.uid = pkgSetting.appId;
7212            pkg.mExtras = pkgSetting;
7213            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7214                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7215                    // We just determined the app is signed correctly, so bring
7216                    // over the latest parsed certs.
7217                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7218                } else {
7219                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7220                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7221                                "Package " + pkg.packageName + " upgrade keys do not match the "
7222                                + "previously installed version");
7223                    } else {
7224                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7225                        String msg = "System package " + pkg.packageName
7226                            + " signature changed; retaining data.";
7227                        reportSettingsProblem(Log.WARN, msg);
7228                    }
7229                }
7230            } else {
7231                try {
7232                    verifySignaturesLP(pkgSetting, pkg);
7233                    // We just determined the app is signed correctly, so bring
7234                    // over the latest parsed certs.
7235                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7236                } catch (PackageManagerException e) {
7237                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7238                        throw e;
7239                    }
7240                    // The signature has changed, but this package is in the system
7241                    // image...  let's recover!
7242                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7243                    // However...  if this package is part of a shared user, but it
7244                    // doesn't match the signature of the shared user, let's fail.
7245                    // What this means is that you can't change the signatures
7246                    // associated with an overall shared user, which doesn't seem all
7247                    // that unreasonable.
7248                    if (pkgSetting.sharedUser != null) {
7249                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7250                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7251                            throw new PackageManagerException(
7252                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7253                                            "Signature mismatch for shared user: "
7254                                            + pkgSetting.sharedUser);
7255                        }
7256                    }
7257                    // File a report about this.
7258                    String msg = "System package " + pkg.packageName
7259                        + " signature changed; retaining data.";
7260                    reportSettingsProblem(Log.WARN, msg);
7261                }
7262            }
7263            // Verify that this new package doesn't have any content providers
7264            // that conflict with existing packages.  Only do this if the
7265            // package isn't already installed, since we don't want to break
7266            // things that are installed.
7267            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7268                final int N = pkg.providers.size();
7269                int i;
7270                for (i=0; i<N; i++) {
7271                    PackageParser.Provider p = pkg.providers.get(i);
7272                    if (p.info.authority != null) {
7273                        String names[] = p.info.authority.split(";");
7274                        for (int j = 0; j < names.length; j++) {
7275                            if (mProvidersByAuthority.containsKey(names[j])) {
7276                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7277                                final String otherPackageName =
7278                                        ((other != null && other.getComponentName() != null) ?
7279                                                other.getComponentName().getPackageName() : "?");
7280                                throw new PackageManagerException(
7281                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7282                                                "Can't install because provider name " + names[j]
7283                                                + " (in package " + pkg.applicationInfo.packageName
7284                                                + ") is already used by " + otherPackageName);
7285                            }
7286                        }
7287                    }
7288                }
7289            }
7290
7291            if (pkg.mAdoptPermissions != null) {
7292                // This package wants to adopt ownership of permissions from
7293                // another package.
7294                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7295                    final String origName = pkg.mAdoptPermissions.get(i);
7296                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7297                    if (orig != null) {
7298                        if (verifyPackageUpdateLPr(orig, pkg)) {
7299                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7300                                    + pkg.packageName);
7301                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7302                        }
7303                    }
7304                }
7305            }
7306        }
7307
7308        final String pkgName = pkg.packageName;
7309
7310        final long scanFileTime = scanFile.lastModified();
7311        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7312        pkg.applicationInfo.processName = fixProcessName(
7313                pkg.applicationInfo.packageName,
7314                pkg.applicationInfo.processName,
7315                pkg.applicationInfo.uid);
7316
7317        if (pkg != mPlatformPackage) {
7318            // Get all of our default paths setup
7319            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7320        }
7321
7322        final String path = scanFile.getPath();
7323        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7324
7325        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7326            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7327
7328            // Some system apps still use directory structure for native libraries
7329            // in which case we might end up not detecting abi solely based on apk
7330            // structure. Try to detect abi based on directory structure.
7331            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7332                    pkg.applicationInfo.primaryCpuAbi == null) {
7333                setBundledAppAbisAndRoots(pkg, pkgSetting);
7334                setNativeLibraryPaths(pkg);
7335            }
7336
7337        } else {
7338            if ((scanFlags & SCAN_MOVE) != 0) {
7339                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7340                // but we already have this packages package info in the PackageSetting. We just
7341                // use that and derive the native library path based on the new codepath.
7342                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7343                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7344            }
7345
7346            // Set native library paths again. For moves, the path will be updated based on the
7347            // ABIs we've determined above. For non-moves, the path will be updated based on the
7348            // ABIs we determined during compilation, but the path will depend on the final
7349            // package path (after the rename away from the stage path).
7350            setNativeLibraryPaths(pkg);
7351        }
7352
7353        // This is a special case for the "system" package, where the ABI is
7354        // dictated by the zygote configuration (and init.rc). We should keep track
7355        // of this ABI so that we can deal with "normal" applications that run under
7356        // the same UID correctly.
7357        if (mPlatformPackage == pkg) {
7358            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7359                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7360        }
7361
7362        // If there's a mismatch between the abi-override in the package setting
7363        // and the abiOverride specified for the install. Warn about this because we
7364        // would've already compiled the app without taking the package setting into
7365        // account.
7366        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7367            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7368                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7369                        " for package " + pkg.packageName);
7370            }
7371        }
7372
7373        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7374        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7375        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7376
7377        // Copy the derived override back to the parsed package, so that we can
7378        // update the package settings accordingly.
7379        pkg.cpuAbiOverride = cpuAbiOverride;
7380
7381        if (DEBUG_ABI_SELECTION) {
7382            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7383                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7384                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7385        }
7386
7387        // Push the derived path down into PackageSettings so we know what to
7388        // clean up at uninstall time.
7389        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7390
7391        if (DEBUG_ABI_SELECTION) {
7392            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7393                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7394                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7395        }
7396
7397        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7398            // We don't do this here during boot because we can do it all
7399            // at once after scanning all existing packages.
7400            //
7401            // We also do this *before* we perform dexopt on this package, so that
7402            // we can avoid redundant dexopts, and also to make sure we've got the
7403            // code and package path correct.
7404            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7405                    pkg, true /* boot complete */);
7406        }
7407
7408        if (mFactoryTest && pkg.requestedPermissions.contains(
7409                android.Manifest.permission.FACTORY_TEST)) {
7410            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7411        }
7412
7413        ArrayList<PackageParser.Package> clientLibPkgs = null;
7414
7415        // writer
7416        synchronized (mPackages) {
7417            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7418                // Only system apps can add new shared libraries.
7419                if (pkg.libraryNames != null) {
7420                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7421                        String name = pkg.libraryNames.get(i);
7422                        boolean allowed = false;
7423                        if (pkg.isUpdatedSystemApp()) {
7424                            // New library entries can only be added through the
7425                            // system image.  This is important to get rid of a lot
7426                            // of nasty edge cases: for example if we allowed a non-
7427                            // system update of the app to add a library, then uninstalling
7428                            // the update would make the library go away, and assumptions
7429                            // we made such as through app install filtering would now
7430                            // have allowed apps on the device which aren't compatible
7431                            // with it.  Better to just have the restriction here, be
7432                            // conservative, and create many fewer cases that can negatively
7433                            // impact the user experience.
7434                            final PackageSetting sysPs = mSettings
7435                                    .getDisabledSystemPkgLPr(pkg.packageName);
7436                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7437                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7438                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7439                                        allowed = true;
7440                                        break;
7441                                    }
7442                                }
7443                            }
7444                        } else {
7445                            allowed = true;
7446                        }
7447                        if (allowed) {
7448                            if (!mSharedLibraries.containsKey(name)) {
7449                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7450                            } else if (!name.equals(pkg.packageName)) {
7451                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7452                                        + name + " already exists; skipping");
7453                            }
7454                        } else {
7455                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7456                                    + name + " that is not declared on system image; skipping");
7457                        }
7458                    }
7459                    if ((scanFlags & SCAN_BOOTING) == 0) {
7460                        // If we are not booting, we need to update any applications
7461                        // that are clients of our shared library.  If we are booting,
7462                        // this will all be done once the scan is complete.
7463                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7464                    }
7465                }
7466            }
7467        }
7468
7469        // Request the ActivityManager to kill the process(only for existing packages)
7470        // so that we do not end up in a confused state while the user is still using the older
7471        // version of the application while the new one gets installed.
7472        if ((scanFlags & SCAN_REPLACING) != 0) {
7473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7474
7475            killApplication(pkg.applicationInfo.packageName,
7476                        pkg.applicationInfo.uid, "replace pkg");
7477
7478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7479        }
7480
7481        // Also need to kill any apps that are dependent on the library.
7482        if (clientLibPkgs != null) {
7483            for (int i=0; i<clientLibPkgs.size(); i++) {
7484                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7485                killApplication(clientPkg.applicationInfo.packageName,
7486                        clientPkg.applicationInfo.uid, "update lib");
7487            }
7488        }
7489
7490        // Make sure we're not adding any bogus keyset info
7491        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7492        ksms.assertScannedPackageValid(pkg);
7493
7494        // writer
7495        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7496
7497        boolean createIdmapFailed = false;
7498        synchronized (mPackages) {
7499            // We don't expect installation to fail beyond this point
7500
7501            // Add the new setting to mSettings
7502            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7503            // Add the new setting to mPackages
7504            mPackages.put(pkg.applicationInfo.packageName, pkg);
7505            // Make sure we don't accidentally delete its data.
7506            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7507            while (iter.hasNext()) {
7508                PackageCleanItem item = iter.next();
7509                if (pkgName.equals(item.packageName)) {
7510                    iter.remove();
7511                }
7512            }
7513
7514            // Take care of first install / last update times.
7515            if (currentTime != 0) {
7516                if (pkgSetting.firstInstallTime == 0) {
7517                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7518                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7519                    pkgSetting.lastUpdateTime = currentTime;
7520                }
7521            } else if (pkgSetting.firstInstallTime == 0) {
7522                // We need *something*.  Take time time stamp of the file.
7523                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7524            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7525                if (scanFileTime != pkgSetting.timeStamp) {
7526                    // A package on the system image has changed; consider this
7527                    // to be an update.
7528                    pkgSetting.lastUpdateTime = scanFileTime;
7529                }
7530            }
7531
7532            // Add the package's KeySets to the global KeySetManagerService
7533            ksms.addScannedPackageLPw(pkg);
7534
7535            int N = pkg.providers.size();
7536            StringBuilder r = null;
7537            int i;
7538            for (i=0; i<N; i++) {
7539                PackageParser.Provider p = pkg.providers.get(i);
7540                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7541                        p.info.processName, pkg.applicationInfo.uid);
7542                mProviders.addProvider(p);
7543                p.syncable = p.info.isSyncable;
7544                if (p.info.authority != null) {
7545                    String names[] = p.info.authority.split(";");
7546                    p.info.authority = null;
7547                    for (int j = 0; j < names.length; j++) {
7548                        if (j == 1 && p.syncable) {
7549                            // We only want the first authority for a provider to possibly be
7550                            // syncable, so if we already added this provider using a different
7551                            // authority clear the syncable flag. We copy the provider before
7552                            // changing it because the mProviders object contains a reference
7553                            // to a provider that we don't want to change.
7554                            // Only do this for the second authority since the resulting provider
7555                            // object can be the same for all future authorities for this provider.
7556                            p = new PackageParser.Provider(p);
7557                            p.syncable = false;
7558                        }
7559                        if (!mProvidersByAuthority.containsKey(names[j])) {
7560                            mProvidersByAuthority.put(names[j], p);
7561                            if (p.info.authority == null) {
7562                                p.info.authority = names[j];
7563                            } else {
7564                                p.info.authority = p.info.authority + ";" + names[j];
7565                            }
7566                            if (DEBUG_PACKAGE_SCANNING) {
7567                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7568                                    Log.d(TAG, "Registered content provider: " + names[j]
7569                                            + ", className = " + p.info.name + ", isSyncable = "
7570                                            + p.info.isSyncable);
7571                            }
7572                        } else {
7573                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7574                            Slog.w(TAG, "Skipping provider name " + names[j] +
7575                                    " (in package " + pkg.applicationInfo.packageName +
7576                                    "): name already used by "
7577                                    + ((other != null && other.getComponentName() != null)
7578                                            ? other.getComponentName().getPackageName() : "?"));
7579                        }
7580                    }
7581                }
7582                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7583                    if (r == null) {
7584                        r = new StringBuilder(256);
7585                    } else {
7586                        r.append(' ');
7587                    }
7588                    r.append(p.info.name);
7589                }
7590            }
7591            if (r != null) {
7592                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7593            }
7594
7595            N = pkg.services.size();
7596            r = null;
7597            for (i=0; i<N; i++) {
7598                PackageParser.Service s = pkg.services.get(i);
7599                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7600                        s.info.processName, pkg.applicationInfo.uid);
7601                mServices.addService(s);
7602                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7603                    if (r == null) {
7604                        r = new StringBuilder(256);
7605                    } else {
7606                        r.append(' ');
7607                    }
7608                    r.append(s.info.name);
7609                }
7610            }
7611            if (r != null) {
7612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7613            }
7614
7615            N = pkg.receivers.size();
7616            r = null;
7617            for (i=0; i<N; i++) {
7618                PackageParser.Activity a = pkg.receivers.get(i);
7619                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7620                        a.info.processName, pkg.applicationInfo.uid);
7621                mReceivers.addActivity(a, "receiver");
7622                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7623                    if (r == null) {
7624                        r = new StringBuilder(256);
7625                    } else {
7626                        r.append(' ');
7627                    }
7628                    r.append(a.info.name);
7629                }
7630            }
7631            if (r != null) {
7632                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7633            }
7634
7635            N = pkg.activities.size();
7636            r = null;
7637            for (i=0; i<N; i++) {
7638                PackageParser.Activity a = pkg.activities.get(i);
7639                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7640                        a.info.processName, pkg.applicationInfo.uid);
7641                mActivities.addActivity(a, "activity");
7642                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7643                    if (r == null) {
7644                        r = new StringBuilder(256);
7645                    } else {
7646                        r.append(' ');
7647                    }
7648                    r.append(a.info.name);
7649                }
7650            }
7651            if (r != null) {
7652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7653            }
7654
7655            N = pkg.permissionGroups.size();
7656            r = null;
7657            for (i=0; i<N; i++) {
7658                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7659                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7660                if (cur == null) {
7661                    mPermissionGroups.put(pg.info.name, pg);
7662                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7663                        if (r == null) {
7664                            r = new StringBuilder(256);
7665                        } else {
7666                            r.append(' ');
7667                        }
7668                        r.append(pg.info.name);
7669                    }
7670                } else {
7671                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7672                            + pg.info.packageName + " ignored: original from "
7673                            + cur.info.packageName);
7674                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7675                        if (r == null) {
7676                            r = new StringBuilder(256);
7677                        } else {
7678                            r.append(' ');
7679                        }
7680                        r.append("DUP:");
7681                        r.append(pg.info.name);
7682                    }
7683                }
7684            }
7685            if (r != null) {
7686                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7687            }
7688
7689            N = pkg.permissions.size();
7690            r = null;
7691            for (i=0; i<N; i++) {
7692                PackageParser.Permission p = pkg.permissions.get(i);
7693
7694                // Assume by default that we did not install this permission into the system.
7695                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7696
7697                // Now that permission groups have a special meaning, we ignore permission
7698                // groups for legacy apps to prevent unexpected behavior. In particular,
7699                // permissions for one app being granted to someone just becuase they happen
7700                // to be in a group defined by another app (before this had no implications).
7701                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7702                    p.group = mPermissionGroups.get(p.info.group);
7703                    // Warn for a permission in an unknown group.
7704                    if (p.info.group != null && p.group == null) {
7705                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7706                                + p.info.packageName + " in an unknown group " + p.info.group);
7707                    }
7708                }
7709
7710                ArrayMap<String, BasePermission> permissionMap =
7711                        p.tree ? mSettings.mPermissionTrees
7712                                : mSettings.mPermissions;
7713                BasePermission bp = permissionMap.get(p.info.name);
7714
7715                // Allow system apps to redefine non-system permissions
7716                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7717                    final boolean currentOwnerIsSystem = (bp.perm != null
7718                            && isSystemApp(bp.perm.owner));
7719                    if (isSystemApp(p.owner)) {
7720                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7721                            // It's a built-in permission and no owner, take ownership now
7722                            bp.packageSetting = pkgSetting;
7723                            bp.perm = p;
7724                            bp.uid = pkg.applicationInfo.uid;
7725                            bp.sourcePackage = p.info.packageName;
7726                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7727                        } else if (!currentOwnerIsSystem) {
7728                            String msg = "New decl " + p.owner + " of permission  "
7729                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7730                            reportSettingsProblem(Log.WARN, msg);
7731                            bp = null;
7732                        }
7733                    }
7734                }
7735
7736                if (bp == null) {
7737                    bp = new BasePermission(p.info.name, p.info.packageName,
7738                            BasePermission.TYPE_NORMAL);
7739                    permissionMap.put(p.info.name, bp);
7740                }
7741
7742                if (bp.perm == null) {
7743                    if (bp.sourcePackage == null
7744                            || bp.sourcePackage.equals(p.info.packageName)) {
7745                        BasePermission tree = findPermissionTreeLP(p.info.name);
7746                        if (tree == null
7747                                || tree.sourcePackage.equals(p.info.packageName)) {
7748                            bp.packageSetting = pkgSetting;
7749                            bp.perm = p;
7750                            bp.uid = pkg.applicationInfo.uid;
7751                            bp.sourcePackage = p.info.packageName;
7752                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7753                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7754                                if (r == null) {
7755                                    r = new StringBuilder(256);
7756                                } else {
7757                                    r.append(' ');
7758                                }
7759                                r.append(p.info.name);
7760                            }
7761                        } else {
7762                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7763                                    + p.info.packageName + " ignored: base tree "
7764                                    + tree.name + " is from package "
7765                                    + tree.sourcePackage);
7766                        }
7767                    } else {
7768                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7769                                + p.info.packageName + " ignored: original from "
7770                                + bp.sourcePackage);
7771                    }
7772                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7773                    if (r == null) {
7774                        r = new StringBuilder(256);
7775                    } else {
7776                        r.append(' ');
7777                    }
7778                    r.append("DUP:");
7779                    r.append(p.info.name);
7780                }
7781                if (bp.perm == p) {
7782                    bp.protectionLevel = p.info.protectionLevel;
7783                }
7784            }
7785
7786            if (r != null) {
7787                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7788            }
7789
7790            N = pkg.instrumentation.size();
7791            r = null;
7792            for (i=0; i<N; i++) {
7793                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7794                a.info.packageName = pkg.applicationInfo.packageName;
7795                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7796                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7797                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7798                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7799                a.info.dataDir = pkg.applicationInfo.dataDir;
7800                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7801                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7802
7803                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7804                // need other information about the application, like the ABI and what not ?
7805                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7806                mInstrumentation.put(a.getComponentName(), a);
7807                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7808                    if (r == null) {
7809                        r = new StringBuilder(256);
7810                    } else {
7811                        r.append(' ');
7812                    }
7813                    r.append(a.info.name);
7814                }
7815            }
7816            if (r != null) {
7817                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7818            }
7819
7820            if (pkg.protectedBroadcasts != null) {
7821                N = pkg.protectedBroadcasts.size();
7822                for (i=0; i<N; i++) {
7823                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7824                }
7825            }
7826
7827            pkgSetting.setTimeStamp(scanFileTime);
7828
7829            // Create idmap files for pairs of (packages, overlay packages).
7830            // Note: "android", ie framework-res.apk, is handled by native layers.
7831            if (pkg.mOverlayTarget != null) {
7832                // This is an overlay package.
7833                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7834                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7835                        mOverlays.put(pkg.mOverlayTarget,
7836                                new ArrayMap<String, PackageParser.Package>());
7837                    }
7838                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7839                    map.put(pkg.packageName, pkg);
7840                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7841                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7842                        createIdmapFailed = true;
7843                    }
7844                }
7845            } else if (mOverlays.containsKey(pkg.packageName) &&
7846                    !pkg.packageName.equals("android")) {
7847                // This is a regular package, with one or more known overlay packages.
7848                createIdmapsForPackageLI(pkg);
7849            }
7850        }
7851
7852        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7853
7854        if (createIdmapFailed) {
7855            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7856                    "scanPackageLI failed to createIdmap");
7857        }
7858        return pkg;
7859    }
7860
7861    /**
7862     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7863     * is derived purely on the basis of the contents of {@code scanFile} and
7864     * {@code cpuAbiOverride}.
7865     *
7866     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7867     */
7868    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7869                                 String cpuAbiOverride, boolean extractLibs)
7870            throws PackageManagerException {
7871        // TODO: We can probably be smarter about this stuff. For installed apps,
7872        // we can calculate this information at install time once and for all. For
7873        // system apps, we can probably assume that this information doesn't change
7874        // after the first boot scan. As things stand, we do lots of unnecessary work.
7875
7876        // Give ourselves some initial paths; we'll come back for another
7877        // pass once we've determined ABI below.
7878        setNativeLibraryPaths(pkg);
7879
7880        // We would never need to extract libs for forward-locked and external packages,
7881        // since the container service will do it for us. We shouldn't attempt to
7882        // extract libs from system app when it was not updated.
7883        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7884                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7885            extractLibs = false;
7886        }
7887
7888        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7889        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7890
7891        NativeLibraryHelper.Handle handle = null;
7892        try {
7893            handle = NativeLibraryHelper.Handle.create(pkg);
7894            // TODO(multiArch): This can be null for apps that didn't go through the
7895            // usual installation process. We can calculate it again, like we
7896            // do during install time.
7897            //
7898            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7899            // unnecessary.
7900            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7901
7902            // Null out the abis so that they can be recalculated.
7903            pkg.applicationInfo.primaryCpuAbi = null;
7904            pkg.applicationInfo.secondaryCpuAbi = null;
7905            if (isMultiArch(pkg.applicationInfo)) {
7906                // Warn if we've set an abiOverride for multi-lib packages..
7907                // By definition, we need to copy both 32 and 64 bit libraries for
7908                // such packages.
7909                if (pkg.cpuAbiOverride != null
7910                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7911                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7912                }
7913
7914                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7915                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7916                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7917                    if (extractLibs) {
7918                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7919                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7920                                useIsaSpecificSubdirs);
7921                    } else {
7922                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7923                    }
7924                }
7925
7926                maybeThrowExceptionForMultiArchCopy(
7927                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7928
7929                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7930                    if (extractLibs) {
7931                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7932                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7933                                useIsaSpecificSubdirs);
7934                    } else {
7935                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7936                    }
7937                }
7938
7939                maybeThrowExceptionForMultiArchCopy(
7940                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7941
7942                if (abi64 >= 0) {
7943                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7944                }
7945
7946                if (abi32 >= 0) {
7947                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7948                    if (abi64 >= 0) {
7949                        pkg.applicationInfo.secondaryCpuAbi = abi;
7950                    } else {
7951                        pkg.applicationInfo.primaryCpuAbi = abi;
7952                    }
7953                }
7954            } else {
7955                String[] abiList = (cpuAbiOverride != null) ?
7956                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7957
7958                // Enable gross and lame hacks for apps that are built with old
7959                // SDK tools. We must scan their APKs for renderscript bitcode and
7960                // not launch them if it's present. Don't bother checking on devices
7961                // that don't have 64 bit support.
7962                boolean needsRenderScriptOverride = false;
7963                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7964                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7965                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7966                    needsRenderScriptOverride = true;
7967                }
7968
7969                final int copyRet;
7970                if (extractLibs) {
7971                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7972                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7973                } else {
7974                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7975                }
7976
7977                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7978                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7979                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7980                }
7981
7982                if (copyRet >= 0) {
7983                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7984                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7985                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7986                } else if (needsRenderScriptOverride) {
7987                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7988                }
7989            }
7990        } catch (IOException ioe) {
7991            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7992        } finally {
7993            IoUtils.closeQuietly(handle);
7994        }
7995
7996        // Now that we've calculated the ABIs and determined if it's an internal app,
7997        // we will go ahead and populate the nativeLibraryPath.
7998        setNativeLibraryPaths(pkg);
7999    }
8000
8001    /**
8002     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8003     * i.e, so that all packages can be run inside a single process if required.
8004     *
8005     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8006     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8007     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8008     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8009     * updating a package that belongs to a shared user.
8010     *
8011     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8012     * adds unnecessary complexity.
8013     */
8014    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8015            PackageParser.Package scannedPackage, boolean bootComplete) {
8016        String requiredInstructionSet = null;
8017        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8018            requiredInstructionSet = VMRuntime.getInstructionSet(
8019                     scannedPackage.applicationInfo.primaryCpuAbi);
8020        }
8021
8022        PackageSetting requirer = null;
8023        for (PackageSetting ps : packagesForUser) {
8024            // If packagesForUser contains scannedPackage, we skip it. This will happen
8025            // when scannedPackage is an update of an existing package. Without this check,
8026            // we will never be able to change the ABI of any package belonging to a shared
8027            // user, even if it's compatible with other packages.
8028            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8029                if (ps.primaryCpuAbiString == null) {
8030                    continue;
8031                }
8032
8033                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8034                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8035                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8036                    // this but there's not much we can do.
8037                    String errorMessage = "Instruction set mismatch, "
8038                            + ((requirer == null) ? "[caller]" : requirer)
8039                            + " requires " + requiredInstructionSet + " whereas " + ps
8040                            + " requires " + instructionSet;
8041                    Slog.w(TAG, errorMessage);
8042                }
8043
8044                if (requiredInstructionSet == null) {
8045                    requiredInstructionSet = instructionSet;
8046                    requirer = ps;
8047                }
8048            }
8049        }
8050
8051        if (requiredInstructionSet != null) {
8052            String adjustedAbi;
8053            if (requirer != null) {
8054                // requirer != null implies that either scannedPackage was null or that scannedPackage
8055                // did not require an ABI, in which case we have to adjust scannedPackage to match
8056                // the ABI of the set (which is the same as requirer's ABI)
8057                adjustedAbi = requirer.primaryCpuAbiString;
8058                if (scannedPackage != null) {
8059                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8060                }
8061            } else {
8062                // requirer == null implies that we're updating all ABIs in the set to
8063                // match scannedPackage.
8064                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8065            }
8066
8067            for (PackageSetting ps : packagesForUser) {
8068                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8069                    if (ps.primaryCpuAbiString != null) {
8070                        continue;
8071                    }
8072
8073                    ps.primaryCpuAbiString = adjustedAbi;
8074                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8075                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8076                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8077                        try {
8078                            mInstaller.rmdex(ps.codePathString,
8079                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8080                        } catch (InstallerException ignored) {
8081                        }
8082                    }
8083                }
8084            }
8085        }
8086    }
8087
8088    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8089        synchronized (mPackages) {
8090            mResolverReplaced = true;
8091            // Set up information for custom user intent resolution activity.
8092            mResolveActivity.applicationInfo = pkg.applicationInfo;
8093            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8094            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8095            mResolveActivity.processName = pkg.applicationInfo.packageName;
8096            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8097            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8098                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8099            mResolveActivity.theme = 0;
8100            mResolveActivity.exported = true;
8101            mResolveActivity.enabled = true;
8102            mResolveInfo.activityInfo = mResolveActivity;
8103            mResolveInfo.priority = 0;
8104            mResolveInfo.preferredOrder = 0;
8105            mResolveInfo.match = 0;
8106            mResolveComponentName = mCustomResolverComponentName;
8107            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8108                    mResolveComponentName);
8109        }
8110    }
8111
8112    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8113        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8114
8115        // Set up information for ephemeral installer activity
8116        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8117        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8118        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8119        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8120        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8121        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8122                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8123        mEphemeralInstallerActivity.theme = 0;
8124        mEphemeralInstallerActivity.exported = true;
8125        mEphemeralInstallerActivity.enabled = true;
8126        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8127        mEphemeralInstallerInfo.priority = 0;
8128        mEphemeralInstallerInfo.preferredOrder = 0;
8129        mEphemeralInstallerInfo.match = 0;
8130
8131        if (DEBUG_EPHEMERAL) {
8132            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8133        }
8134    }
8135
8136    private static String calculateBundledApkRoot(final String codePathString) {
8137        final File codePath = new File(codePathString);
8138        final File codeRoot;
8139        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8140            codeRoot = Environment.getRootDirectory();
8141        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8142            codeRoot = Environment.getOemDirectory();
8143        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8144            codeRoot = Environment.getVendorDirectory();
8145        } else {
8146            // Unrecognized code path; take its top real segment as the apk root:
8147            // e.g. /something/app/blah.apk => /something
8148            try {
8149                File f = codePath.getCanonicalFile();
8150                File parent = f.getParentFile();    // non-null because codePath is a file
8151                File tmp;
8152                while ((tmp = parent.getParentFile()) != null) {
8153                    f = parent;
8154                    parent = tmp;
8155                }
8156                codeRoot = f;
8157                Slog.w(TAG, "Unrecognized code path "
8158                        + codePath + " - using " + codeRoot);
8159            } catch (IOException e) {
8160                // Can't canonicalize the code path -- shenanigans?
8161                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8162                return Environment.getRootDirectory().getPath();
8163            }
8164        }
8165        return codeRoot.getPath();
8166    }
8167
8168    /**
8169     * Derive and set the location of native libraries for the given package,
8170     * which varies depending on where and how the package was installed.
8171     */
8172    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8173        final ApplicationInfo info = pkg.applicationInfo;
8174        final String codePath = pkg.codePath;
8175        final File codeFile = new File(codePath);
8176        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8177        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8178
8179        info.nativeLibraryRootDir = null;
8180        info.nativeLibraryRootRequiresIsa = false;
8181        info.nativeLibraryDir = null;
8182        info.secondaryNativeLibraryDir = null;
8183
8184        if (isApkFile(codeFile)) {
8185            // Monolithic install
8186            if (bundledApp) {
8187                // If "/system/lib64/apkname" exists, assume that is the per-package
8188                // native library directory to use; otherwise use "/system/lib/apkname".
8189                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8190                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8191                        getPrimaryInstructionSet(info));
8192
8193                // This is a bundled system app so choose the path based on the ABI.
8194                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8195                // is just the default path.
8196                final String apkName = deriveCodePathName(codePath);
8197                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8198                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8199                        apkName).getAbsolutePath();
8200
8201                if (info.secondaryCpuAbi != null) {
8202                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8203                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8204                            secondaryLibDir, apkName).getAbsolutePath();
8205                }
8206            } else if (asecApp) {
8207                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8208                        .getAbsolutePath();
8209            } else {
8210                final String apkName = deriveCodePathName(codePath);
8211                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8212                        .getAbsolutePath();
8213            }
8214
8215            info.nativeLibraryRootRequiresIsa = false;
8216            info.nativeLibraryDir = info.nativeLibraryRootDir;
8217        } else {
8218            // Cluster install
8219            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8220            info.nativeLibraryRootRequiresIsa = true;
8221
8222            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8223                    getPrimaryInstructionSet(info)).getAbsolutePath();
8224
8225            if (info.secondaryCpuAbi != null) {
8226                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8227                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8228            }
8229        }
8230    }
8231
8232    /**
8233     * Calculate the abis and roots for a bundled app. These can uniquely
8234     * be determined from the contents of the system partition, i.e whether
8235     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8236     * of this information, and instead assume that the system was built
8237     * sensibly.
8238     */
8239    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8240                                           PackageSetting pkgSetting) {
8241        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8242
8243        // If "/system/lib64/apkname" exists, assume that is the per-package
8244        // native library directory to use; otherwise use "/system/lib/apkname".
8245        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8246        setBundledAppAbi(pkg, apkRoot, apkName);
8247        // pkgSetting might be null during rescan following uninstall of updates
8248        // to a bundled app, so accommodate that possibility.  The settings in
8249        // that case will be established later from the parsed package.
8250        //
8251        // If the settings aren't null, sync them up with what we've just derived.
8252        // note that apkRoot isn't stored in the package settings.
8253        if (pkgSetting != null) {
8254            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8255            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8256        }
8257    }
8258
8259    /**
8260     * Deduces the ABI of a bundled app and sets the relevant fields on the
8261     * parsed pkg object.
8262     *
8263     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8264     *        under which system libraries are installed.
8265     * @param apkName the name of the installed package.
8266     */
8267    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8268        final File codeFile = new File(pkg.codePath);
8269
8270        final boolean has64BitLibs;
8271        final boolean has32BitLibs;
8272        if (isApkFile(codeFile)) {
8273            // Monolithic install
8274            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8275            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8276        } else {
8277            // Cluster install
8278            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8279            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8280                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8281                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8282                has64BitLibs = (new File(rootDir, isa)).exists();
8283            } else {
8284                has64BitLibs = false;
8285            }
8286            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8287                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8288                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8289                has32BitLibs = (new File(rootDir, isa)).exists();
8290            } else {
8291                has32BitLibs = false;
8292            }
8293        }
8294
8295        if (has64BitLibs && !has32BitLibs) {
8296            // The package has 64 bit libs, but not 32 bit libs. Its primary
8297            // ABI should be 64 bit. We can safely assume here that the bundled
8298            // native libraries correspond to the most preferred ABI in the list.
8299
8300            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8301            pkg.applicationInfo.secondaryCpuAbi = null;
8302        } else if (has32BitLibs && !has64BitLibs) {
8303            // The package has 32 bit libs but not 64 bit libs. Its primary
8304            // ABI should be 32 bit.
8305
8306            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8307            pkg.applicationInfo.secondaryCpuAbi = null;
8308        } else if (has32BitLibs && has64BitLibs) {
8309            // The application has both 64 and 32 bit bundled libraries. We check
8310            // here that the app declares multiArch support, and warn if it doesn't.
8311            //
8312            // We will be lenient here and record both ABIs. The primary will be the
8313            // ABI that's higher on the list, i.e, a device that's configured to prefer
8314            // 64 bit apps will see a 64 bit primary ABI,
8315
8316            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8317                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8318            }
8319
8320            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8321                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8322                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8323            } else {
8324                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8325                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8326            }
8327        } else {
8328            pkg.applicationInfo.primaryCpuAbi = null;
8329            pkg.applicationInfo.secondaryCpuAbi = null;
8330        }
8331    }
8332
8333    private void killApplication(String pkgName, int appId, String reason) {
8334        // Request the ActivityManager to kill the process(only for existing packages)
8335        // so that we do not end up in a confused state while the user is still using the older
8336        // version of the application while the new one gets installed.
8337        IActivityManager am = ActivityManagerNative.getDefault();
8338        if (am != null) {
8339            try {
8340                am.killApplicationWithAppId(pkgName, appId, reason);
8341            } catch (RemoteException e) {
8342            }
8343        }
8344    }
8345
8346    void removePackageLI(PackageSetting ps, boolean chatty) {
8347        if (DEBUG_INSTALL) {
8348            if (chatty)
8349                Log.d(TAG, "Removing package " + ps.name);
8350        }
8351
8352        // writer
8353        synchronized (mPackages) {
8354            mPackages.remove(ps.name);
8355            final PackageParser.Package pkg = ps.pkg;
8356            if (pkg != null) {
8357                cleanPackageDataStructuresLILPw(pkg, chatty);
8358            }
8359        }
8360    }
8361
8362    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8363        if (DEBUG_INSTALL) {
8364            if (chatty)
8365                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8366        }
8367
8368        // writer
8369        synchronized (mPackages) {
8370            mPackages.remove(pkg.applicationInfo.packageName);
8371            cleanPackageDataStructuresLILPw(pkg, chatty);
8372        }
8373    }
8374
8375    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8376        int N = pkg.providers.size();
8377        StringBuilder r = null;
8378        int i;
8379        for (i=0; i<N; i++) {
8380            PackageParser.Provider p = pkg.providers.get(i);
8381            mProviders.removeProvider(p);
8382            if (p.info.authority == null) {
8383
8384                /* There was another ContentProvider with this authority when
8385                 * this app was installed so this authority is null,
8386                 * Ignore it as we don't have to unregister the provider.
8387                 */
8388                continue;
8389            }
8390            String names[] = p.info.authority.split(";");
8391            for (int j = 0; j < names.length; j++) {
8392                if (mProvidersByAuthority.get(names[j]) == p) {
8393                    mProvidersByAuthority.remove(names[j]);
8394                    if (DEBUG_REMOVE) {
8395                        if (chatty)
8396                            Log.d(TAG, "Unregistered content provider: " + names[j]
8397                                    + ", className = " + p.info.name + ", isSyncable = "
8398                                    + p.info.isSyncable);
8399                    }
8400                }
8401            }
8402            if (DEBUG_REMOVE && chatty) {
8403                if (r == null) {
8404                    r = new StringBuilder(256);
8405                } else {
8406                    r.append(' ');
8407                }
8408                r.append(p.info.name);
8409            }
8410        }
8411        if (r != null) {
8412            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8413        }
8414
8415        N = pkg.services.size();
8416        r = null;
8417        for (i=0; i<N; i++) {
8418            PackageParser.Service s = pkg.services.get(i);
8419            mServices.removeService(s);
8420            if (chatty) {
8421                if (r == null) {
8422                    r = new StringBuilder(256);
8423                } else {
8424                    r.append(' ');
8425                }
8426                r.append(s.info.name);
8427            }
8428        }
8429        if (r != null) {
8430            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8431        }
8432
8433        N = pkg.receivers.size();
8434        r = null;
8435        for (i=0; i<N; i++) {
8436            PackageParser.Activity a = pkg.receivers.get(i);
8437            mReceivers.removeActivity(a, "receiver");
8438            if (DEBUG_REMOVE && chatty) {
8439                if (r == null) {
8440                    r = new StringBuilder(256);
8441                } else {
8442                    r.append(' ');
8443                }
8444                r.append(a.info.name);
8445            }
8446        }
8447        if (r != null) {
8448            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8449        }
8450
8451        N = pkg.activities.size();
8452        r = null;
8453        for (i=0; i<N; i++) {
8454            PackageParser.Activity a = pkg.activities.get(i);
8455            mActivities.removeActivity(a, "activity");
8456            if (DEBUG_REMOVE && chatty) {
8457                if (r == null) {
8458                    r = new StringBuilder(256);
8459                } else {
8460                    r.append(' ');
8461                }
8462                r.append(a.info.name);
8463            }
8464        }
8465        if (r != null) {
8466            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8467        }
8468
8469        N = pkg.permissions.size();
8470        r = null;
8471        for (i=0; i<N; i++) {
8472            PackageParser.Permission p = pkg.permissions.get(i);
8473            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8474            if (bp == null) {
8475                bp = mSettings.mPermissionTrees.get(p.info.name);
8476            }
8477            if (bp != null && bp.perm == p) {
8478                bp.perm = null;
8479                if (DEBUG_REMOVE && chatty) {
8480                    if (r == null) {
8481                        r = new StringBuilder(256);
8482                    } else {
8483                        r.append(' ');
8484                    }
8485                    r.append(p.info.name);
8486                }
8487            }
8488            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8489                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8490                if (appOpPkgs != null) {
8491                    appOpPkgs.remove(pkg.packageName);
8492                }
8493            }
8494        }
8495        if (r != null) {
8496            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8497        }
8498
8499        N = pkg.requestedPermissions.size();
8500        r = null;
8501        for (i=0; i<N; i++) {
8502            String perm = pkg.requestedPermissions.get(i);
8503            BasePermission bp = mSettings.mPermissions.get(perm);
8504            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8505                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8506                if (appOpPkgs != null) {
8507                    appOpPkgs.remove(pkg.packageName);
8508                    if (appOpPkgs.isEmpty()) {
8509                        mAppOpPermissionPackages.remove(perm);
8510                    }
8511                }
8512            }
8513        }
8514        if (r != null) {
8515            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8516        }
8517
8518        N = pkg.instrumentation.size();
8519        r = null;
8520        for (i=0; i<N; i++) {
8521            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8522            mInstrumentation.remove(a.getComponentName());
8523            if (DEBUG_REMOVE && chatty) {
8524                if (r == null) {
8525                    r = new StringBuilder(256);
8526                } else {
8527                    r.append(' ');
8528                }
8529                r.append(a.info.name);
8530            }
8531        }
8532        if (r != null) {
8533            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8534        }
8535
8536        r = null;
8537        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8538            // Only system apps can hold shared libraries.
8539            if (pkg.libraryNames != null) {
8540                for (i=0; i<pkg.libraryNames.size(); i++) {
8541                    String name = pkg.libraryNames.get(i);
8542                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8543                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8544                        mSharedLibraries.remove(name);
8545                        if (DEBUG_REMOVE && chatty) {
8546                            if (r == null) {
8547                                r = new StringBuilder(256);
8548                            } else {
8549                                r.append(' ');
8550                            }
8551                            r.append(name);
8552                        }
8553                    }
8554                }
8555            }
8556        }
8557        if (r != null) {
8558            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8559        }
8560    }
8561
8562    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8563        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8564            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8565                return true;
8566            }
8567        }
8568        return false;
8569    }
8570
8571    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8572    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8573    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8574
8575    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8576            int flags) {
8577        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8578        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8579    }
8580
8581    private void updatePermissionsLPw(String changingPkg,
8582            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8583        // Make sure there are no dangling permission trees.
8584        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8585        while (it.hasNext()) {
8586            final BasePermission bp = it.next();
8587            if (bp.packageSetting == null) {
8588                // We may not yet have parsed the package, so just see if
8589                // we still know about its settings.
8590                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8591            }
8592            if (bp.packageSetting == null) {
8593                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8594                        + " from package " + bp.sourcePackage);
8595                it.remove();
8596            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8597                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8598                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8599                            + " from package " + bp.sourcePackage);
8600                    flags |= UPDATE_PERMISSIONS_ALL;
8601                    it.remove();
8602                }
8603            }
8604        }
8605
8606        // Make sure all dynamic permissions have been assigned to a package,
8607        // and make sure there are no dangling permissions.
8608        it = mSettings.mPermissions.values().iterator();
8609        while (it.hasNext()) {
8610            final BasePermission bp = it.next();
8611            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8612                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8613                        + bp.name + " pkg=" + bp.sourcePackage
8614                        + " info=" + bp.pendingInfo);
8615                if (bp.packageSetting == null && bp.pendingInfo != null) {
8616                    final BasePermission tree = findPermissionTreeLP(bp.name);
8617                    if (tree != null && tree.perm != null) {
8618                        bp.packageSetting = tree.packageSetting;
8619                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8620                                new PermissionInfo(bp.pendingInfo));
8621                        bp.perm.info.packageName = tree.perm.info.packageName;
8622                        bp.perm.info.name = bp.name;
8623                        bp.uid = tree.uid;
8624                    }
8625                }
8626            }
8627            if (bp.packageSetting == null) {
8628                // We may not yet have parsed the package, so just see if
8629                // we still know about its settings.
8630                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8631            }
8632            if (bp.packageSetting == null) {
8633                Slog.w(TAG, "Removing dangling permission: " + bp.name
8634                        + " from package " + bp.sourcePackage);
8635                it.remove();
8636            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8637                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8638                    Slog.i(TAG, "Removing old permission: " + bp.name
8639                            + " from package " + bp.sourcePackage);
8640                    flags |= UPDATE_PERMISSIONS_ALL;
8641                    it.remove();
8642                }
8643            }
8644        }
8645
8646        // Now update the permissions for all packages, in particular
8647        // replace the granted permissions of the system packages.
8648        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8649            for (PackageParser.Package pkg : mPackages.values()) {
8650                if (pkg != pkgInfo) {
8651                    // Only replace for packages on requested volume
8652                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8653                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8654                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8655                    grantPermissionsLPw(pkg, replace, changingPkg);
8656                }
8657            }
8658        }
8659
8660        if (pkgInfo != null) {
8661            // Only replace for packages on requested volume
8662            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8663            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8664                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8665            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8666        }
8667    }
8668
8669    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8670            String packageOfInterest) {
8671        // IMPORTANT: There are two types of permissions: install and runtime.
8672        // Install time permissions are granted when the app is installed to
8673        // all device users and users added in the future. Runtime permissions
8674        // are granted at runtime explicitly to specific users. Normal and signature
8675        // protected permissions are install time permissions. Dangerous permissions
8676        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8677        // otherwise they are runtime permissions. This function does not manage
8678        // runtime permissions except for the case an app targeting Lollipop MR1
8679        // being upgraded to target a newer SDK, in which case dangerous permissions
8680        // are transformed from install time to runtime ones.
8681
8682        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8683        if (ps == null) {
8684            return;
8685        }
8686
8687        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8688
8689        PermissionsState permissionsState = ps.getPermissionsState();
8690        PermissionsState origPermissions = permissionsState;
8691
8692        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8693
8694        boolean runtimePermissionsRevoked = false;
8695        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8696
8697        boolean changedInstallPermission = false;
8698
8699        if (replace) {
8700            ps.installPermissionsFixed = false;
8701            if (!ps.isSharedUser()) {
8702                origPermissions = new PermissionsState(permissionsState);
8703                permissionsState.reset();
8704            } else {
8705                // We need to know only about runtime permission changes since the
8706                // calling code always writes the install permissions state but
8707                // the runtime ones are written only if changed. The only cases of
8708                // changed runtime permissions here are promotion of an install to
8709                // runtime and revocation of a runtime from a shared user.
8710                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8711                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8712                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8713                    runtimePermissionsRevoked = true;
8714                }
8715            }
8716        }
8717
8718        permissionsState.setGlobalGids(mGlobalGids);
8719
8720        final int N = pkg.requestedPermissions.size();
8721        for (int i=0; i<N; i++) {
8722            final String name = pkg.requestedPermissions.get(i);
8723            final BasePermission bp = mSettings.mPermissions.get(name);
8724
8725            if (DEBUG_INSTALL) {
8726                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8727            }
8728
8729            if (bp == null || bp.packageSetting == null) {
8730                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8731                    Slog.w(TAG, "Unknown permission " + name
8732                            + " in package " + pkg.packageName);
8733                }
8734                continue;
8735            }
8736
8737            final String perm = bp.name;
8738            boolean allowedSig = false;
8739            int grant = GRANT_DENIED;
8740
8741            // Keep track of app op permissions.
8742            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8743                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8744                if (pkgs == null) {
8745                    pkgs = new ArraySet<>();
8746                    mAppOpPermissionPackages.put(bp.name, pkgs);
8747                }
8748                pkgs.add(pkg.packageName);
8749            }
8750
8751            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8752            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8753                    >= Build.VERSION_CODES.M;
8754            switch (level) {
8755                case PermissionInfo.PROTECTION_NORMAL: {
8756                    // For all apps normal permissions are install time ones.
8757                    grant = GRANT_INSTALL;
8758                } break;
8759
8760                case PermissionInfo.PROTECTION_DANGEROUS: {
8761                    // If a permission review is required for legacy apps we represent
8762                    // their permissions as always granted runtime ones since we need
8763                    // to keep the review required permission flag per user while an
8764                    // install permission's state is shared across all users.
8765                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8766                        // For legacy apps dangerous permissions are install time ones.
8767                        grant = GRANT_INSTALL;
8768                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8769                        // For legacy apps that became modern, install becomes runtime.
8770                        grant = GRANT_UPGRADE;
8771                    } else if (mPromoteSystemApps
8772                            && isSystemApp(ps)
8773                            && mExistingSystemPackages.contains(ps.name)) {
8774                        // For legacy system apps, install becomes runtime.
8775                        // We cannot check hasInstallPermission() for system apps since those
8776                        // permissions were granted implicitly and not persisted pre-M.
8777                        grant = GRANT_UPGRADE;
8778                    } else {
8779                        // For modern apps keep runtime permissions unchanged.
8780                        grant = GRANT_RUNTIME;
8781                    }
8782                } break;
8783
8784                case PermissionInfo.PROTECTION_SIGNATURE: {
8785                    // For all apps signature permissions are install time ones.
8786                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8787                    if (allowedSig) {
8788                        grant = GRANT_INSTALL;
8789                    }
8790                } break;
8791            }
8792
8793            if (DEBUG_INSTALL) {
8794                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8795            }
8796
8797            if (grant != GRANT_DENIED) {
8798                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8799                    // If this is an existing, non-system package, then
8800                    // we can't add any new permissions to it.
8801                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8802                        // Except...  if this is a permission that was added
8803                        // to the platform (note: need to only do this when
8804                        // updating the platform).
8805                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8806                            grant = GRANT_DENIED;
8807                        }
8808                    }
8809                }
8810
8811                switch (grant) {
8812                    case GRANT_INSTALL: {
8813                        // Revoke this as runtime permission to handle the case of
8814                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8815                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8816                            if (origPermissions.getRuntimePermissionState(
8817                                    bp.name, userId) != null) {
8818                                // Revoke the runtime permission and clear the flags.
8819                                origPermissions.revokeRuntimePermission(bp, userId);
8820                                origPermissions.updatePermissionFlags(bp, userId,
8821                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8822                                // If we revoked a permission permission, we have to write.
8823                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8824                                        changedRuntimePermissionUserIds, userId);
8825                            }
8826                        }
8827                        // Grant an install permission.
8828                        if (permissionsState.grantInstallPermission(bp) !=
8829                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8830                            changedInstallPermission = true;
8831                        }
8832                    } break;
8833
8834                    case GRANT_RUNTIME: {
8835                        // Grant previously granted runtime permissions.
8836                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8837                            PermissionState permissionState = origPermissions
8838                                    .getRuntimePermissionState(bp.name, userId);
8839                            int flags = permissionState != null
8840                                    ? permissionState.getFlags() : 0;
8841                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8842                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8843                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8844                                    // If we cannot put the permission as it was, we have to write.
8845                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8846                                            changedRuntimePermissionUserIds, userId);
8847                                }
8848                                // If the app supports runtime permissions no need for a review.
8849                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8850                                        && appSupportsRuntimePermissions
8851                                        && (flags & PackageManager
8852                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8853                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8854                                    // Since we changed the flags, we have to write.
8855                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8856                                            changedRuntimePermissionUserIds, userId);
8857                                }
8858                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8859                                    && !appSupportsRuntimePermissions) {
8860                                // For legacy apps that need a permission review, every new
8861                                // runtime permission is granted but it is pending a review.
8862                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8863                                    permissionsState.grantRuntimePermission(bp, userId);
8864                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8865                                    // We changed the permission and flags, hence have to write.
8866                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8867                                            changedRuntimePermissionUserIds, userId);
8868                                }
8869                            }
8870                            // Propagate the permission flags.
8871                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8872                        }
8873                    } break;
8874
8875                    case GRANT_UPGRADE: {
8876                        // Grant runtime permissions for a previously held install permission.
8877                        PermissionState permissionState = origPermissions
8878                                .getInstallPermissionState(bp.name);
8879                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8880
8881                        if (origPermissions.revokeInstallPermission(bp)
8882                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8883                            // We will be transferring the permission flags, so clear them.
8884                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8885                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8886                            changedInstallPermission = true;
8887                        }
8888
8889                        // If the permission is not to be promoted to runtime we ignore it and
8890                        // also its other flags as they are not applicable to install permissions.
8891                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8892                            for (int userId : currentUserIds) {
8893                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8894                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8895                                    // Transfer the permission flags.
8896                                    permissionsState.updatePermissionFlags(bp, userId,
8897                                            flags, flags);
8898                                    // If we granted the permission, we have to write.
8899                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8900                                            changedRuntimePermissionUserIds, userId);
8901                                }
8902                            }
8903                        }
8904                    } break;
8905
8906                    default: {
8907                        if (packageOfInterest == null
8908                                || packageOfInterest.equals(pkg.packageName)) {
8909                            Slog.w(TAG, "Not granting permission " + perm
8910                                    + " to package " + pkg.packageName
8911                                    + " because it was previously installed without");
8912                        }
8913                    } break;
8914                }
8915            } else {
8916                if (permissionsState.revokeInstallPermission(bp) !=
8917                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8918                    // Also drop the permission flags.
8919                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8920                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8921                    changedInstallPermission = true;
8922                    Slog.i(TAG, "Un-granting permission " + perm
8923                            + " from package " + pkg.packageName
8924                            + " (protectionLevel=" + bp.protectionLevel
8925                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8926                            + ")");
8927                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8928                    // Don't print warning for app op permissions, since it is fine for them
8929                    // not to be granted, there is a UI for the user to decide.
8930                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8931                        Slog.w(TAG, "Not granting permission " + perm
8932                                + " to package " + pkg.packageName
8933                                + " (protectionLevel=" + bp.protectionLevel
8934                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8935                                + ")");
8936                    }
8937                }
8938            }
8939        }
8940
8941        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8942                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8943            // This is the first that we have heard about this package, so the
8944            // permissions we have now selected are fixed until explicitly
8945            // changed.
8946            ps.installPermissionsFixed = true;
8947        }
8948
8949        // Persist the runtime permissions state for users with changes. If permissions
8950        // were revoked because no app in the shared user declares them we have to
8951        // write synchronously to avoid losing runtime permissions state.
8952        for (int userId : changedRuntimePermissionUserIds) {
8953            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8954        }
8955
8956        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8957    }
8958
8959    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8960        boolean allowed = false;
8961        final int NP = PackageParser.NEW_PERMISSIONS.length;
8962        for (int ip=0; ip<NP; ip++) {
8963            final PackageParser.NewPermissionInfo npi
8964                    = PackageParser.NEW_PERMISSIONS[ip];
8965            if (npi.name.equals(perm)
8966                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8967                allowed = true;
8968                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8969                        + pkg.packageName);
8970                break;
8971            }
8972        }
8973        return allowed;
8974    }
8975
8976    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8977            BasePermission bp, PermissionsState origPermissions) {
8978        boolean allowed;
8979        allowed = (compareSignatures(
8980                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8981                        == PackageManager.SIGNATURE_MATCH)
8982                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8983                        == PackageManager.SIGNATURE_MATCH);
8984        if (!allowed && (bp.protectionLevel
8985                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8986            if (isSystemApp(pkg)) {
8987                // For updated system applications, a system permission
8988                // is granted only if it had been defined by the original application.
8989                if (pkg.isUpdatedSystemApp()) {
8990                    final PackageSetting sysPs = mSettings
8991                            .getDisabledSystemPkgLPr(pkg.packageName);
8992                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8993                        // If the original was granted this permission, we take
8994                        // that grant decision as read and propagate it to the
8995                        // update.
8996                        if (sysPs.isPrivileged()) {
8997                            allowed = true;
8998                        }
8999                    } else {
9000                        // The system apk may have been updated with an older
9001                        // version of the one on the data partition, but which
9002                        // granted a new system permission that it didn't have
9003                        // before.  In this case we do want to allow the app to
9004                        // now get the new permission if the ancestral apk is
9005                        // privileged to get it.
9006                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9007                            for (int j=0;
9008                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9009                                if (perm.equals(
9010                                        sysPs.pkg.requestedPermissions.get(j))) {
9011                                    allowed = true;
9012                                    break;
9013                                }
9014                            }
9015                        }
9016                    }
9017                } else {
9018                    allowed = isPrivilegedApp(pkg);
9019                }
9020            }
9021        }
9022        if (!allowed) {
9023            if (!allowed && (bp.protectionLevel
9024                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9025                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9026                // If this was a previously normal/dangerous permission that got moved
9027                // to a system permission as part of the runtime permission redesign, then
9028                // we still want to blindly grant it to old apps.
9029                allowed = true;
9030            }
9031            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9032                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9033                // If this permission is to be granted to the system installer and
9034                // this app is an installer, then it gets the permission.
9035                allowed = true;
9036            }
9037            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9038                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9039                // If this permission is to be granted to the system verifier and
9040                // this app is a verifier, then it gets the permission.
9041                allowed = true;
9042            }
9043            if (!allowed && (bp.protectionLevel
9044                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9045                    && isSystemApp(pkg)) {
9046                // Any pre-installed system app is allowed to get this permission.
9047                allowed = true;
9048            }
9049            if (!allowed && (bp.protectionLevel
9050                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9051                // For development permissions, a development permission
9052                // is granted only if it was already granted.
9053                allowed = origPermissions.hasInstallPermission(perm);
9054            }
9055        }
9056        return allowed;
9057    }
9058
9059    final class ActivityIntentResolver
9060            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9061        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9062                boolean defaultOnly, int userId) {
9063            if (!sUserManager.exists(userId)) return null;
9064            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9065            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9066        }
9067
9068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9069                int userId) {
9070            if (!sUserManager.exists(userId)) return null;
9071            mFlags = flags;
9072            return super.queryIntent(intent, resolvedType,
9073                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9074        }
9075
9076        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9077                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9078            if (!sUserManager.exists(userId)) return null;
9079            if (packageActivities == null) {
9080                return null;
9081            }
9082            mFlags = flags;
9083            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9084            final int N = packageActivities.size();
9085            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9086                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9087
9088            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9089            for (int i = 0; i < N; ++i) {
9090                intentFilters = packageActivities.get(i).intents;
9091                if (intentFilters != null && intentFilters.size() > 0) {
9092                    PackageParser.ActivityIntentInfo[] array =
9093                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9094                    intentFilters.toArray(array);
9095                    listCut.add(array);
9096                }
9097            }
9098            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9099        }
9100
9101        public final void addActivity(PackageParser.Activity a, String type) {
9102            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9103            mActivities.put(a.getComponentName(), a);
9104            if (DEBUG_SHOW_INFO)
9105                Log.v(
9106                TAG, "  " + type + " " +
9107                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9108            if (DEBUG_SHOW_INFO)
9109                Log.v(TAG, "    Class=" + a.info.name);
9110            final int NI = a.intents.size();
9111            for (int j=0; j<NI; j++) {
9112                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9113                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9114                    intent.setPriority(0);
9115                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9116                            + a.className + " with priority > 0, forcing to 0");
9117                }
9118                if (DEBUG_SHOW_INFO) {
9119                    Log.v(TAG, "    IntentFilter:");
9120                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9121                }
9122                if (!intent.debugCheck()) {
9123                    Log.w(TAG, "==> For Activity " + a.info.name);
9124                }
9125                addFilter(intent);
9126            }
9127        }
9128
9129        public final void removeActivity(PackageParser.Activity a, String type) {
9130            mActivities.remove(a.getComponentName());
9131            if (DEBUG_SHOW_INFO) {
9132                Log.v(TAG, "  " + type + " "
9133                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9134                                : a.info.name) + ":");
9135                Log.v(TAG, "    Class=" + a.info.name);
9136            }
9137            final int NI = a.intents.size();
9138            for (int j=0; j<NI; j++) {
9139                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9140                if (DEBUG_SHOW_INFO) {
9141                    Log.v(TAG, "    IntentFilter:");
9142                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9143                }
9144                removeFilter(intent);
9145            }
9146        }
9147
9148        @Override
9149        protected boolean allowFilterResult(
9150                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9151            ActivityInfo filterAi = filter.activity.info;
9152            for (int i=dest.size()-1; i>=0; i--) {
9153                ActivityInfo destAi = dest.get(i).activityInfo;
9154                if (destAi.name == filterAi.name
9155                        && destAi.packageName == filterAi.packageName) {
9156                    return false;
9157                }
9158            }
9159            return true;
9160        }
9161
9162        @Override
9163        protected ActivityIntentInfo[] newArray(int size) {
9164            return new ActivityIntentInfo[size];
9165        }
9166
9167        @Override
9168        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9169            if (!sUserManager.exists(userId)) return true;
9170            PackageParser.Package p = filter.activity.owner;
9171            if (p != null) {
9172                PackageSetting ps = (PackageSetting)p.mExtras;
9173                if (ps != null) {
9174                    // System apps are never considered stopped for purposes of
9175                    // filtering, because there may be no way for the user to
9176                    // actually re-launch them.
9177                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9178                            && ps.getStopped(userId);
9179                }
9180            }
9181            return false;
9182        }
9183
9184        @Override
9185        protected boolean isPackageForFilter(String packageName,
9186                PackageParser.ActivityIntentInfo info) {
9187            return packageName.equals(info.activity.owner.packageName);
9188        }
9189
9190        @Override
9191        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9192                int match, int userId) {
9193            if (!sUserManager.exists(userId)) return null;
9194            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9195                return null;
9196            }
9197            final PackageParser.Activity activity = info.activity;
9198            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9199            if (ps == null) {
9200                return null;
9201            }
9202            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9203                    ps.readUserState(userId), userId);
9204            if (ai == null) {
9205                return null;
9206            }
9207            final ResolveInfo res = new ResolveInfo();
9208            res.activityInfo = ai;
9209            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9210                res.filter = info;
9211            }
9212            if (info != null) {
9213                res.handleAllWebDataURI = info.handleAllWebDataURI();
9214            }
9215            res.priority = info.getPriority();
9216            res.preferredOrder = activity.owner.mPreferredOrder;
9217            //System.out.println("Result: " + res.activityInfo.className +
9218            //                   " = " + res.priority);
9219            res.match = match;
9220            res.isDefault = info.hasDefault;
9221            res.labelRes = info.labelRes;
9222            res.nonLocalizedLabel = info.nonLocalizedLabel;
9223            if (userNeedsBadging(userId)) {
9224                res.noResourceId = true;
9225            } else {
9226                res.icon = info.icon;
9227            }
9228            res.iconResourceId = info.icon;
9229            res.system = res.activityInfo.applicationInfo.isSystemApp();
9230            return res;
9231        }
9232
9233        @Override
9234        protected void sortResults(List<ResolveInfo> results) {
9235            Collections.sort(results, mResolvePrioritySorter);
9236        }
9237
9238        @Override
9239        protected void dumpFilter(PrintWriter out, String prefix,
9240                PackageParser.ActivityIntentInfo filter) {
9241            out.print(prefix); out.print(
9242                    Integer.toHexString(System.identityHashCode(filter.activity)));
9243                    out.print(' ');
9244                    filter.activity.printComponentShortName(out);
9245                    out.print(" filter ");
9246                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9247        }
9248
9249        @Override
9250        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9251            return filter.activity;
9252        }
9253
9254        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9255            PackageParser.Activity activity = (PackageParser.Activity)label;
9256            out.print(prefix); out.print(
9257                    Integer.toHexString(System.identityHashCode(activity)));
9258                    out.print(' ');
9259                    activity.printComponentShortName(out);
9260            if (count > 1) {
9261                out.print(" ("); out.print(count); out.print(" filters)");
9262            }
9263            out.println();
9264        }
9265
9266//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9267//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9268//            final List<ResolveInfo> retList = Lists.newArrayList();
9269//            while (i.hasNext()) {
9270//                final ResolveInfo resolveInfo = i.next();
9271//                if (isEnabledLP(resolveInfo.activityInfo)) {
9272//                    retList.add(resolveInfo);
9273//                }
9274//            }
9275//            return retList;
9276//        }
9277
9278        // Keys are String (activity class name), values are Activity.
9279        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9280                = new ArrayMap<ComponentName, PackageParser.Activity>();
9281        private int mFlags;
9282    }
9283
9284    private final class ServiceIntentResolver
9285            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9286        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9287                boolean defaultOnly, int userId) {
9288            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9289            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9290        }
9291
9292        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9293                int userId) {
9294            if (!sUserManager.exists(userId)) return null;
9295            mFlags = flags;
9296            return super.queryIntent(intent, resolvedType,
9297                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9298        }
9299
9300        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9301                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9302            if (!sUserManager.exists(userId)) return null;
9303            if (packageServices == null) {
9304                return null;
9305            }
9306            mFlags = flags;
9307            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9308            final int N = packageServices.size();
9309            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9310                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9311
9312            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9313            for (int i = 0; i < N; ++i) {
9314                intentFilters = packageServices.get(i).intents;
9315                if (intentFilters != null && intentFilters.size() > 0) {
9316                    PackageParser.ServiceIntentInfo[] array =
9317                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9318                    intentFilters.toArray(array);
9319                    listCut.add(array);
9320                }
9321            }
9322            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9323        }
9324
9325        public final void addService(PackageParser.Service s) {
9326            mServices.put(s.getComponentName(), s);
9327            if (DEBUG_SHOW_INFO) {
9328                Log.v(TAG, "  "
9329                        + (s.info.nonLocalizedLabel != null
9330                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9331                Log.v(TAG, "    Class=" + s.info.name);
9332            }
9333            final int NI = s.intents.size();
9334            int j;
9335            for (j=0; j<NI; j++) {
9336                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9337                if (DEBUG_SHOW_INFO) {
9338                    Log.v(TAG, "    IntentFilter:");
9339                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9340                }
9341                if (!intent.debugCheck()) {
9342                    Log.w(TAG, "==> For Service " + s.info.name);
9343                }
9344                addFilter(intent);
9345            }
9346        }
9347
9348        public final void removeService(PackageParser.Service s) {
9349            mServices.remove(s.getComponentName());
9350            if (DEBUG_SHOW_INFO) {
9351                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9352                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9353                Log.v(TAG, "    Class=" + s.info.name);
9354            }
9355            final int NI = s.intents.size();
9356            int j;
9357            for (j=0; j<NI; j++) {
9358                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9359                if (DEBUG_SHOW_INFO) {
9360                    Log.v(TAG, "    IntentFilter:");
9361                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9362                }
9363                removeFilter(intent);
9364            }
9365        }
9366
9367        @Override
9368        protected boolean allowFilterResult(
9369                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9370            ServiceInfo filterSi = filter.service.info;
9371            for (int i=dest.size()-1; i>=0; i--) {
9372                ServiceInfo destAi = dest.get(i).serviceInfo;
9373                if (destAi.name == filterSi.name
9374                        && destAi.packageName == filterSi.packageName) {
9375                    return false;
9376                }
9377            }
9378            return true;
9379        }
9380
9381        @Override
9382        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9383            return new PackageParser.ServiceIntentInfo[size];
9384        }
9385
9386        @Override
9387        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9388            if (!sUserManager.exists(userId)) return true;
9389            PackageParser.Package p = filter.service.owner;
9390            if (p != null) {
9391                PackageSetting ps = (PackageSetting)p.mExtras;
9392                if (ps != null) {
9393                    // System apps are never considered stopped for purposes of
9394                    // filtering, because there may be no way for the user to
9395                    // actually re-launch them.
9396                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9397                            && ps.getStopped(userId);
9398                }
9399            }
9400            return false;
9401        }
9402
9403        @Override
9404        protected boolean isPackageForFilter(String packageName,
9405                PackageParser.ServiceIntentInfo info) {
9406            return packageName.equals(info.service.owner.packageName);
9407        }
9408
9409        @Override
9410        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9411                int match, int userId) {
9412            if (!sUserManager.exists(userId)) return null;
9413            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9414            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9415                return null;
9416            }
9417            final PackageParser.Service service = info.service;
9418            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9419            if (ps == null) {
9420                return null;
9421            }
9422            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9423                    ps.readUserState(userId), userId);
9424            if (si == null) {
9425                return null;
9426            }
9427            final ResolveInfo res = new ResolveInfo();
9428            res.serviceInfo = si;
9429            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9430                res.filter = filter;
9431            }
9432            res.priority = info.getPriority();
9433            res.preferredOrder = service.owner.mPreferredOrder;
9434            res.match = match;
9435            res.isDefault = info.hasDefault;
9436            res.labelRes = info.labelRes;
9437            res.nonLocalizedLabel = info.nonLocalizedLabel;
9438            res.icon = info.icon;
9439            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9440            return res;
9441        }
9442
9443        @Override
9444        protected void sortResults(List<ResolveInfo> results) {
9445            Collections.sort(results, mResolvePrioritySorter);
9446        }
9447
9448        @Override
9449        protected void dumpFilter(PrintWriter out, String prefix,
9450                PackageParser.ServiceIntentInfo filter) {
9451            out.print(prefix); out.print(
9452                    Integer.toHexString(System.identityHashCode(filter.service)));
9453                    out.print(' ');
9454                    filter.service.printComponentShortName(out);
9455                    out.print(" filter ");
9456                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9457        }
9458
9459        @Override
9460        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9461            return filter.service;
9462        }
9463
9464        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9465            PackageParser.Service service = (PackageParser.Service)label;
9466            out.print(prefix); out.print(
9467                    Integer.toHexString(System.identityHashCode(service)));
9468                    out.print(' ');
9469                    service.printComponentShortName(out);
9470            if (count > 1) {
9471                out.print(" ("); out.print(count); out.print(" filters)");
9472            }
9473            out.println();
9474        }
9475
9476//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9477//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9478//            final List<ResolveInfo> retList = Lists.newArrayList();
9479//            while (i.hasNext()) {
9480//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9481//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9482//                    retList.add(resolveInfo);
9483//                }
9484//            }
9485//            return retList;
9486//        }
9487
9488        // Keys are String (activity class name), values are Activity.
9489        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9490                = new ArrayMap<ComponentName, PackageParser.Service>();
9491        private int mFlags;
9492    };
9493
9494    private final class ProviderIntentResolver
9495            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9496        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9497                boolean defaultOnly, int userId) {
9498            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9499            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9500        }
9501
9502        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9503                int userId) {
9504            if (!sUserManager.exists(userId))
9505                return null;
9506            mFlags = flags;
9507            return super.queryIntent(intent, resolvedType,
9508                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9509        }
9510
9511        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9512                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9513            if (!sUserManager.exists(userId))
9514                return null;
9515            if (packageProviders == null) {
9516                return null;
9517            }
9518            mFlags = flags;
9519            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9520            final int N = packageProviders.size();
9521            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9522                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9523
9524            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9525            for (int i = 0; i < N; ++i) {
9526                intentFilters = packageProviders.get(i).intents;
9527                if (intentFilters != null && intentFilters.size() > 0) {
9528                    PackageParser.ProviderIntentInfo[] array =
9529                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9530                    intentFilters.toArray(array);
9531                    listCut.add(array);
9532                }
9533            }
9534            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9535        }
9536
9537        public final void addProvider(PackageParser.Provider p) {
9538            if (mProviders.containsKey(p.getComponentName())) {
9539                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9540                return;
9541            }
9542
9543            mProviders.put(p.getComponentName(), p);
9544            if (DEBUG_SHOW_INFO) {
9545                Log.v(TAG, "  "
9546                        + (p.info.nonLocalizedLabel != null
9547                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9548                Log.v(TAG, "    Class=" + p.info.name);
9549            }
9550            final int NI = p.intents.size();
9551            int j;
9552            for (j = 0; j < NI; j++) {
9553                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9554                if (DEBUG_SHOW_INFO) {
9555                    Log.v(TAG, "    IntentFilter:");
9556                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9557                }
9558                if (!intent.debugCheck()) {
9559                    Log.w(TAG, "==> For Provider " + p.info.name);
9560                }
9561                addFilter(intent);
9562            }
9563        }
9564
9565        public final void removeProvider(PackageParser.Provider p) {
9566            mProviders.remove(p.getComponentName());
9567            if (DEBUG_SHOW_INFO) {
9568                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9569                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9570                Log.v(TAG, "    Class=" + p.info.name);
9571            }
9572            final int NI = p.intents.size();
9573            int j;
9574            for (j = 0; j < NI; j++) {
9575                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9576                if (DEBUG_SHOW_INFO) {
9577                    Log.v(TAG, "    IntentFilter:");
9578                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9579                }
9580                removeFilter(intent);
9581            }
9582        }
9583
9584        @Override
9585        protected boolean allowFilterResult(
9586                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9587            ProviderInfo filterPi = filter.provider.info;
9588            for (int i = dest.size() - 1; i >= 0; i--) {
9589                ProviderInfo destPi = dest.get(i).providerInfo;
9590                if (destPi.name == filterPi.name
9591                        && destPi.packageName == filterPi.packageName) {
9592                    return false;
9593                }
9594            }
9595            return true;
9596        }
9597
9598        @Override
9599        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9600            return new PackageParser.ProviderIntentInfo[size];
9601        }
9602
9603        @Override
9604        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9605            if (!sUserManager.exists(userId))
9606                return true;
9607            PackageParser.Package p = filter.provider.owner;
9608            if (p != null) {
9609                PackageSetting ps = (PackageSetting) p.mExtras;
9610                if (ps != null) {
9611                    // System apps are never considered stopped for purposes of
9612                    // filtering, because there may be no way for the user to
9613                    // actually re-launch them.
9614                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9615                            && ps.getStopped(userId);
9616                }
9617            }
9618            return false;
9619        }
9620
9621        @Override
9622        protected boolean isPackageForFilter(String packageName,
9623                PackageParser.ProviderIntentInfo info) {
9624            return packageName.equals(info.provider.owner.packageName);
9625        }
9626
9627        @Override
9628        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9629                int match, int userId) {
9630            if (!sUserManager.exists(userId))
9631                return null;
9632            final PackageParser.ProviderIntentInfo info = filter;
9633            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9634                return null;
9635            }
9636            final PackageParser.Provider provider = info.provider;
9637            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9638            if (ps == null) {
9639                return null;
9640            }
9641            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9642                    ps.readUserState(userId), userId);
9643            if (pi == null) {
9644                return null;
9645            }
9646            final ResolveInfo res = new ResolveInfo();
9647            res.providerInfo = pi;
9648            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9649                res.filter = filter;
9650            }
9651            res.priority = info.getPriority();
9652            res.preferredOrder = provider.owner.mPreferredOrder;
9653            res.match = match;
9654            res.isDefault = info.hasDefault;
9655            res.labelRes = info.labelRes;
9656            res.nonLocalizedLabel = info.nonLocalizedLabel;
9657            res.icon = info.icon;
9658            res.system = res.providerInfo.applicationInfo.isSystemApp();
9659            return res;
9660        }
9661
9662        @Override
9663        protected void sortResults(List<ResolveInfo> results) {
9664            Collections.sort(results, mResolvePrioritySorter);
9665        }
9666
9667        @Override
9668        protected void dumpFilter(PrintWriter out, String prefix,
9669                PackageParser.ProviderIntentInfo filter) {
9670            out.print(prefix);
9671            out.print(
9672                    Integer.toHexString(System.identityHashCode(filter.provider)));
9673            out.print(' ');
9674            filter.provider.printComponentShortName(out);
9675            out.print(" filter ");
9676            out.println(Integer.toHexString(System.identityHashCode(filter)));
9677        }
9678
9679        @Override
9680        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9681            return filter.provider;
9682        }
9683
9684        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9685            PackageParser.Provider provider = (PackageParser.Provider)label;
9686            out.print(prefix); out.print(
9687                    Integer.toHexString(System.identityHashCode(provider)));
9688                    out.print(' ');
9689                    provider.printComponentShortName(out);
9690            if (count > 1) {
9691                out.print(" ("); out.print(count); out.print(" filters)");
9692            }
9693            out.println();
9694        }
9695
9696        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9697                = new ArrayMap<ComponentName, PackageParser.Provider>();
9698        private int mFlags;
9699    }
9700
9701    private static final class EphemeralIntentResolver
9702            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9703        @Override
9704        protected EphemeralResolveIntentInfo[] newArray(int size) {
9705            return new EphemeralResolveIntentInfo[size];
9706        }
9707
9708        @Override
9709        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9710            return true;
9711        }
9712
9713        @Override
9714        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9715                int userId) {
9716            if (!sUserManager.exists(userId)) {
9717                return null;
9718            }
9719            return info.getEphemeralResolveInfo();
9720        }
9721    }
9722
9723    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9724            new Comparator<ResolveInfo>() {
9725        public int compare(ResolveInfo r1, ResolveInfo r2) {
9726            int v1 = r1.priority;
9727            int v2 = r2.priority;
9728            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9729            if (v1 != v2) {
9730                return (v1 > v2) ? -1 : 1;
9731            }
9732            v1 = r1.preferredOrder;
9733            v2 = r2.preferredOrder;
9734            if (v1 != v2) {
9735                return (v1 > v2) ? -1 : 1;
9736            }
9737            if (r1.isDefault != r2.isDefault) {
9738                return r1.isDefault ? -1 : 1;
9739            }
9740            v1 = r1.match;
9741            v2 = r2.match;
9742            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9743            if (v1 != v2) {
9744                return (v1 > v2) ? -1 : 1;
9745            }
9746            if (r1.system != r2.system) {
9747                return r1.system ? -1 : 1;
9748            }
9749            if (r1.activityInfo != null) {
9750                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9751            }
9752            if (r1.serviceInfo != null) {
9753                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9754            }
9755            if (r1.providerInfo != null) {
9756                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9757            }
9758            return 0;
9759        }
9760    };
9761
9762    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9763            new Comparator<ProviderInfo>() {
9764        public int compare(ProviderInfo p1, ProviderInfo p2) {
9765            final int v1 = p1.initOrder;
9766            final int v2 = p2.initOrder;
9767            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9768        }
9769    };
9770
9771    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9772            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9773            final int[] userIds) {
9774        mHandler.post(new Runnable() {
9775            @Override
9776            public void run() {
9777                try {
9778                    final IActivityManager am = ActivityManagerNative.getDefault();
9779                    if (am == null) return;
9780                    final int[] resolvedUserIds;
9781                    if (userIds == null) {
9782                        resolvedUserIds = am.getRunningUserIds();
9783                    } else {
9784                        resolvedUserIds = userIds;
9785                    }
9786                    for (int id : resolvedUserIds) {
9787                        final Intent intent = new Intent(action,
9788                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9789                        if (extras != null) {
9790                            intent.putExtras(extras);
9791                        }
9792                        if (targetPkg != null) {
9793                            intent.setPackage(targetPkg);
9794                        }
9795                        // Modify the UID when posting to other users
9796                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9797                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9798                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9799                            intent.putExtra(Intent.EXTRA_UID, uid);
9800                        }
9801                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9802                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9803                        if (DEBUG_BROADCASTS) {
9804                            RuntimeException here = new RuntimeException("here");
9805                            here.fillInStackTrace();
9806                            Slog.d(TAG, "Sending to user " + id + ": "
9807                                    + intent.toShortString(false, true, false, false)
9808                                    + " " + intent.getExtras(), here);
9809                        }
9810                        am.broadcastIntent(null, intent, null, finishedReceiver,
9811                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9812                                null, finishedReceiver != null, false, id);
9813                    }
9814                } catch (RemoteException ex) {
9815                }
9816            }
9817        });
9818    }
9819
9820    /**
9821     * Check if the external storage media is available. This is true if there
9822     * is a mounted external storage medium or if the external storage is
9823     * emulated.
9824     */
9825    private boolean isExternalMediaAvailable() {
9826        return mMediaMounted || Environment.isExternalStorageEmulated();
9827    }
9828
9829    @Override
9830    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9831        // writer
9832        synchronized (mPackages) {
9833            if (!isExternalMediaAvailable()) {
9834                // If the external storage is no longer mounted at this point,
9835                // the caller may not have been able to delete all of this
9836                // packages files and can not delete any more.  Bail.
9837                return null;
9838            }
9839            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9840            if (lastPackage != null) {
9841                pkgs.remove(lastPackage);
9842            }
9843            if (pkgs.size() > 0) {
9844                return pkgs.get(0);
9845            }
9846        }
9847        return null;
9848    }
9849
9850    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9851        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9852                userId, andCode ? 1 : 0, packageName);
9853        if (mSystemReady) {
9854            msg.sendToTarget();
9855        } else {
9856            if (mPostSystemReadyMessages == null) {
9857                mPostSystemReadyMessages = new ArrayList<>();
9858            }
9859            mPostSystemReadyMessages.add(msg);
9860        }
9861    }
9862
9863    void startCleaningPackages() {
9864        // reader
9865        synchronized (mPackages) {
9866            if (!isExternalMediaAvailable()) {
9867                return;
9868            }
9869            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9870                return;
9871            }
9872        }
9873        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9874        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9875        IActivityManager am = ActivityManagerNative.getDefault();
9876        if (am != null) {
9877            try {
9878                am.startService(null, intent, null, mContext.getOpPackageName(),
9879                        UserHandle.USER_SYSTEM);
9880            } catch (RemoteException e) {
9881            }
9882        }
9883    }
9884
9885    @Override
9886    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9887            int installFlags, String installerPackageName, VerificationParams verificationParams,
9888            String packageAbiOverride) {
9889        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9890                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9891    }
9892
9893    @Override
9894    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9895            int installFlags, String installerPackageName, VerificationParams verificationParams,
9896            String packageAbiOverride, int userId) {
9897        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9898
9899        final int callingUid = Binder.getCallingUid();
9900        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9901
9902        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9903            try {
9904                if (observer != null) {
9905                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9906                }
9907            } catch (RemoteException re) {
9908            }
9909            return;
9910        }
9911
9912        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9913            installFlags |= PackageManager.INSTALL_FROM_ADB;
9914
9915        } else {
9916            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9917            // about installerPackageName.
9918
9919            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9920            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9921        }
9922
9923        UserHandle user;
9924        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9925            user = UserHandle.ALL;
9926        } else {
9927            user = new UserHandle(userId);
9928        }
9929
9930        // Only system components can circumvent runtime permissions when installing.
9931        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9932                && mContext.checkCallingOrSelfPermission(Manifest.permission
9933                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9934            throw new SecurityException("You need the "
9935                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9936                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9937        }
9938
9939        verificationParams.setInstallerUid(callingUid);
9940
9941        final File originFile = new File(originPath);
9942        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9943
9944        final Message msg = mHandler.obtainMessage(INIT_COPY);
9945        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9946                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9947        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9948        msg.obj = params;
9949
9950        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9951                System.identityHashCode(msg.obj));
9952        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9953                System.identityHashCode(msg.obj));
9954
9955        mHandler.sendMessage(msg);
9956    }
9957
9958    void installStage(String packageName, File stagedDir, String stagedCid,
9959            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9960            String installerPackageName, int installerUid, UserHandle user) {
9961        if (DEBUG_EPHEMERAL) {
9962            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9963                Slog.d(TAG, "Ephemeral install of " + packageName);
9964            }
9965        }
9966        final VerificationParams verifParams = new VerificationParams(
9967                null, sessionParams.originatingUri, sessionParams.referrerUri,
9968                sessionParams.originatingUid);
9969        verifParams.setInstallerUid(installerUid);
9970
9971        final OriginInfo origin;
9972        if (stagedDir != null) {
9973            origin = OriginInfo.fromStagedFile(stagedDir);
9974        } else {
9975            origin = OriginInfo.fromStagedContainer(stagedCid);
9976        }
9977
9978        final Message msg = mHandler.obtainMessage(INIT_COPY);
9979        final InstallParams params = new InstallParams(origin, null, observer,
9980                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9981                verifParams, user, sessionParams.abiOverride,
9982                sessionParams.grantedRuntimePermissions);
9983        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9984        msg.obj = params;
9985
9986        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9987                System.identityHashCode(msg.obj));
9988        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9989                System.identityHashCode(msg.obj));
9990
9991        mHandler.sendMessage(msg);
9992    }
9993
9994    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9995        Bundle extras = new Bundle(1);
9996        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9997
9998        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9999                packageName, extras, 0, null, null, new int[] {userId});
10000        try {
10001            IActivityManager am = ActivityManagerNative.getDefault();
10002            final boolean isSystem =
10003                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10004            if (isSystem && am.isUserRunning(userId, 0)) {
10005                // The just-installed/enabled app is bundled on the system, so presumed
10006                // to be able to run automatically without needing an explicit launch.
10007                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10008                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10009                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10010                        .setPackage(packageName);
10011                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10012                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10013            }
10014        } catch (RemoteException e) {
10015            // shouldn't happen
10016            Slog.w(TAG, "Unable to bootstrap installed package", e);
10017        }
10018    }
10019
10020    @Override
10021    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10022            int userId) {
10023        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10024        PackageSetting pkgSetting;
10025        final int uid = Binder.getCallingUid();
10026        enforceCrossUserPermission(uid, userId, true, true,
10027                "setApplicationHiddenSetting for user " + userId);
10028
10029        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10030            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10031            return false;
10032        }
10033
10034        long callingId = Binder.clearCallingIdentity();
10035        try {
10036            boolean sendAdded = false;
10037            boolean sendRemoved = false;
10038            // writer
10039            synchronized (mPackages) {
10040                pkgSetting = mSettings.mPackages.get(packageName);
10041                if (pkgSetting == null) {
10042                    return false;
10043                }
10044                if (pkgSetting.getHidden(userId) != hidden) {
10045                    pkgSetting.setHidden(hidden, userId);
10046                    mSettings.writePackageRestrictionsLPr(userId);
10047                    if (hidden) {
10048                        sendRemoved = true;
10049                    } else {
10050                        sendAdded = true;
10051                    }
10052                }
10053            }
10054            if (sendAdded) {
10055                sendPackageAddedForUser(packageName, pkgSetting, userId);
10056                return true;
10057            }
10058            if (sendRemoved) {
10059                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10060                        "hiding pkg");
10061                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10062                return true;
10063            }
10064        } finally {
10065            Binder.restoreCallingIdentity(callingId);
10066        }
10067        return false;
10068    }
10069
10070    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10071            int userId) {
10072        final PackageRemovedInfo info = new PackageRemovedInfo();
10073        info.removedPackage = packageName;
10074        info.removedUsers = new int[] {userId};
10075        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10076        info.sendBroadcast(false, false, false);
10077    }
10078
10079    /**
10080     * Returns true if application is not found or there was an error. Otherwise it returns
10081     * the hidden state of the package for the given user.
10082     */
10083    @Override
10084    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10085        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10086        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10087                false, "getApplicationHidden for user " + userId);
10088        PackageSetting pkgSetting;
10089        long callingId = Binder.clearCallingIdentity();
10090        try {
10091            // writer
10092            synchronized (mPackages) {
10093                pkgSetting = mSettings.mPackages.get(packageName);
10094                if (pkgSetting == null) {
10095                    return true;
10096                }
10097                return pkgSetting.getHidden(userId);
10098            }
10099        } finally {
10100            Binder.restoreCallingIdentity(callingId);
10101        }
10102    }
10103
10104    /**
10105     * @hide
10106     */
10107    @Override
10108    public int installExistingPackageAsUser(String packageName, int userId) {
10109        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10110                null);
10111        PackageSetting pkgSetting;
10112        final int uid = Binder.getCallingUid();
10113        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10114                + userId);
10115        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10116            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10117        }
10118
10119        long callingId = Binder.clearCallingIdentity();
10120        try {
10121            boolean installed = false;
10122
10123            // writer
10124            synchronized (mPackages) {
10125                pkgSetting = mSettings.mPackages.get(packageName);
10126                if (pkgSetting == null) {
10127                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10128                }
10129                if (!pkgSetting.getInstalled(userId)) {
10130                    pkgSetting.setInstalled(true, userId);
10131                    pkgSetting.setHidden(false, userId);
10132                    mSettings.writePackageRestrictionsLPr(userId);
10133                    if (pkgSetting.pkg != null) {
10134                        prepareAppDataAfterInstall(pkgSetting.pkg);
10135                    }
10136                    installed = true;
10137                }
10138            }
10139
10140            if (installed) {
10141                sendPackageAddedForUser(packageName, pkgSetting, userId);
10142            }
10143        } finally {
10144            Binder.restoreCallingIdentity(callingId);
10145        }
10146
10147        return PackageManager.INSTALL_SUCCEEDED;
10148    }
10149
10150    boolean isUserRestricted(int userId, String restrictionKey) {
10151        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10152        if (restrictions.getBoolean(restrictionKey, false)) {
10153            Log.w(TAG, "User is restricted: " + restrictionKey);
10154            return true;
10155        }
10156        return false;
10157    }
10158
10159    @Override
10160    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10162        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10163                "setPackageSuspended for user " + userId);
10164
10165        long callingId = Binder.clearCallingIdentity();
10166        try {
10167            synchronized (mPackages) {
10168                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10169                if (pkgSetting != null) {
10170                    if (pkgSetting.getSuspended(userId) != suspended) {
10171                        pkgSetting.setSuspended(suspended, userId);
10172                        mSettings.writePackageRestrictionsLPr(userId);
10173                    }
10174
10175                    // TODO:
10176                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10177                    // * remove app from recents (kill app it if it is running)
10178                    // * erase existing notifications for this app
10179                    return true;
10180                }
10181
10182                return false;
10183            }
10184        } finally {
10185            Binder.restoreCallingIdentity(callingId);
10186        }
10187    }
10188
10189    @Override
10190    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10191        mContext.enforceCallingOrSelfPermission(
10192                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10193                "Only package verification agents can verify applications");
10194
10195        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10196        final PackageVerificationResponse response = new PackageVerificationResponse(
10197                verificationCode, Binder.getCallingUid());
10198        msg.arg1 = id;
10199        msg.obj = response;
10200        mHandler.sendMessage(msg);
10201    }
10202
10203    @Override
10204    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10205            long millisecondsToDelay) {
10206        mContext.enforceCallingOrSelfPermission(
10207                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10208                "Only package verification agents can extend verification timeouts");
10209
10210        final PackageVerificationState state = mPendingVerification.get(id);
10211        final PackageVerificationResponse response = new PackageVerificationResponse(
10212                verificationCodeAtTimeout, Binder.getCallingUid());
10213
10214        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10215            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10216        }
10217        if (millisecondsToDelay < 0) {
10218            millisecondsToDelay = 0;
10219        }
10220        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10221                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10222            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10223        }
10224
10225        if ((state != null) && !state.timeoutExtended()) {
10226            state.extendTimeout();
10227
10228            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10229            msg.arg1 = id;
10230            msg.obj = response;
10231            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10232        }
10233    }
10234
10235    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10236            int verificationCode, UserHandle user) {
10237        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10238        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10239        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10240        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10241        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10242
10243        mContext.sendBroadcastAsUser(intent, user,
10244                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10245    }
10246
10247    private ComponentName matchComponentForVerifier(String packageName,
10248            List<ResolveInfo> receivers) {
10249        ActivityInfo targetReceiver = null;
10250
10251        final int NR = receivers.size();
10252        for (int i = 0; i < NR; i++) {
10253            final ResolveInfo info = receivers.get(i);
10254            if (info.activityInfo == null) {
10255                continue;
10256            }
10257
10258            if (packageName.equals(info.activityInfo.packageName)) {
10259                targetReceiver = info.activityInfo;
10260                break;
10261            }
10262        }
10263
10264        if (targetReceiver == null) {
10265            return null;
10266        }
10267
10268        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10269    }
10270
10271    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10272            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10273        if (pkgInfo.verifiers.length == 0) {
10274            return null;
10275        }
10276
10277        final int N = pkgInfo.verifiers.length;
10278        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10279        for (int i = 0; i < N; i++) {
10280            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10281
10282            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10283                    receivers);
10284            if (comp == null) {
10285                continue;
10286            }
10287
10288            final int verifierUid = getUidForVerifier(verifierInfo);
10289            if (verifierUid == -1) {
10290                continue;
10291            }
10292
10293            if (DEBUG_VERIFY) {
10294                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10295                        + " with the correct signature");
10296            }
10297            sufficientVerifiers.add(comp);
10298            verificationState.addSufficientVerifier(verifierUid);
10299        }
10300
10301        return sufficientVerifiers;
10302    }
10303
10304    private int getUidForVerifier(VerifierInfo verifierInfo) {
10305        synchronized (mPackages) {
10306            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10307            if (pkg == null) {
10308                return -1;
10309            } else if (pkg.mSignatures.length != 1) {
10310                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10311                        + " has more than one signature; ignoring");
10312                return -1;
10313            }
10314
10315            /*
10316             * If the public key of the package's signature does not match
10317             * our expected public key, then this is a different package and
10318             * we should skip.
10319             */
10320
10321            final byte[] expectedPublicKey;
10322            try {
10323                final Signature verifierSig = pkg.mSignatures[0];
10324                final PublicKey publicKey = verifierSig.getPublicKey();
10325                expectedPublicKey = publicKey.getEncoded();
10326            } catch (CertificateException e) {
10327                return -1;
10328            }
10329
10330            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10331
10332            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10333                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10334                        + " does not have the expected public key; ignoring");
10335                return -1;
10336            }
10337
10338            return pkg.applicationInfo.uid;
10339        }
10340    }
10341
10342    @Override
10343    public void finishPackageInstall(int token) {
10344        enforceSystemOrRoot("Only the system is allowed to finish installs");
10345
10346        if (DEBUG_INSTALL) {
10347            Slog.v(TAG, "BM finishing package install for " + token);
10348        }
10349        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10350
10351        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10352        mHandler.sendMessage(msg);
10353    }
10354
10355    /**
10356     * Get the verification agent timeout.
10357     *
10358     * @return verification timeout in milliseconds
10359     */
10360    private long getVerificationTimeout() {
10361        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10362                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10363                DEFAULT_VERIFICATION_TIMEOUT);
10364    }
10365
10366    /**
10367     * Get the default verification agent response code.
10368     *
10369     * @return default verification response code
10370     */
10371    private int getDefaultVerificationResponse() {
10372        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10373                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10374                DEFAULT_VERIFICATION_RESPONSE);
10375    }
10376
10377    /**
10378     * Check whether or not package verification has been enabled.
10379     *
10380     * @return true if verification should be performed
10381     */
10382    private boolean isVerificationEnabled(int userId, int installFlags) {
10383        if (!DEFAULT_VERIFY_ENABLE) {
10384            return false;
10385        }
10386        // Ephemeral apps don't get the full verification treatment
10387        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10388            if (DEBUG_EPHEMERAL) {
10389                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10390            }
10391            return false;
10392        }
10393
10394        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10395
10396        // Check if installing from ADB
10397        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10398            // Do not run verification in a test harness environment
10399            if (ActivityManager.isRunningInTestHarness()) {
10400                return false;
10401            }
10402            if (ensureVerifyAppsEnabled) {
10403                return true;
10404            }
10405            // Check if the developer does not want package verification for ADB installs
10406            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10407                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10408                return false;
10409            }
10410        }
10411
10412        if (ensureVerifyAppsEnabled) {
10413            return true;
10414        }
10415
10416        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10417                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10418    }
10419
10420    @Override
10421    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10422            throws RemoteException {
10423        mContext.enforceCallingOrSelfPermission(
10424                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10425                "Only intentfilter verification agents can verify applications");
10426
10427        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10428        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10429                Binder.getCallingUid(), verificationCode, failedDomains);
10430        msg.arg1 = id;
10431        msg.obj = response;
10432        mHandler.sendMessage(msg);
10433    }
10434
10435    @Override
10436    public int getIntentVerificationStatus(String packageName, int userId) {
10437        synchronized (mPackages) {
10438            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10439        }
10440    }
10441
10442    @Override
10443    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10444        mContext.enforceCallingOrSelfPermission(
10445                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10446
10447        boolean result = false;
10448        synchronized (mPackages) {
10449            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10450        }
10451        if (result) {
10452            scheduleWritePackageRestrictionsLocked(userId);
10453        }
10454        return result;
10455    }
10456
10457    @Override
10458    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10459        synchronized (mPackages) {
10460            return mSettings.getIntentFilterVerificationsLPr(packageName);
10461        }
10462    }
10463
10464    @Override
10465    public List<IntentFilter> getAllIntentFilters(String packageName) {
10466        if (TextUtils.isEmpty(packageName)) {
10467            return Collections.<IntentFilter>emptyList();
10468        }
10469        synchronized (mPackages) {
10470            PackageParser.Package pkg = mPackages.get(packageName);
10471            if (pkg == null || pkg.activities == null) {
10472                return Collections.<IntentFilter>emptyList();
10473            }
10474            final int count = pkg.activities.size();
10475            ArrayList<IntentFilter> result = new ArrayList<>();
10476            for (int n=0; n<count; n++) {
10477                PackageParser.Activity activity = pkg.activities.get(n);
10478                if (activity.intents != null && activity.intents.size() > 0) {
10479                    result.addAll(activity.intents);
10480                }
10481            }
10482            return result;
10483        }
10484    }
10485
10486    @Override
10487    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10488        mContext.enforceCallingOrSelfPermission(
10489                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10490
10491        synchronized (mPackages) {
10492            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10493            if (packageName != null) {
10494                result |= updateIntentVerificationStatus(packageName,
10495                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10496                        userId);
10497                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10498                        packageName, userId);
10499            }
10500            return result;
10501        }
10502    }
10503
10504    @Override
10505    public String getDefaultBrowserPackageName(int userId) {
10506        synchronized (mPackages) {
10507            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10508        }
10509    }
10510
10511    /**
10512     * Get the "allow unknown sources" setting.
10513     *
10514     * @return the current "allow unknown sources" setting
10515     */
10516    private int getUnknownSourcesSettings() {
10517        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10518                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10519                -1);
10520    }
10521
10522    @Override
10523    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10524        final int uid = Binder.getCallingUid();
10525        // writer
10526        synchronized (mPackages) {
10527            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10528            if (targetPackageSetting == null) {
10529                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10530            }
10531
10532            PackageSetting installerPackageSetting;
10533            if (installerPackageName != null) {
10534                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10535                if (installerPackageSetting == null) {
10536                    throw new IllegalArgumentException("Unknown installer package: "
10537                            + installerPackageName);
10538                }
10539            } else {
10540                installerPackageSetting = null;
10541            }
10542
10543            Signature[] callerSignature;
10544            Object obj = mSettings.getUserIdLPr(uid);
10545            if (obj != null) {
10546                if (obj instanceof SharedUserSetting) {
10547                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10548                } else if (obj instanceof PackageSetting) {
10549                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10550                } else {
10551                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10552                }
10553            } else {
10554                throw new SecurityException("Unknown calling UID: " + uid);
10555            }
10556
10557            // Verify: can't set installerPackageName to a package that is
10558            // not signed with the same cert as the caller.
10559            if (installerPackageSetting != null) {
10560                if (compareSignatures(callerSignature,
10561                        installerPackageSetting.signatures.mSignatures)
10562                        != PackageManager.SIGNATURE_MATCH) {
10563                    throw new SecurityException(
10564                            "Caller does not have same cert as new installer package "
10565                            + installerPackageName);
10566                }
10567            }
10568
10569            // Verify: if target already has an installer package, it must
10570            // be signed with the same cert as the caller.
10571            if (targetPackageSetting.installerPackageName != null) {
10572                PackageSetting setting = mSettings.mPackages.get(
10573                        targetPackageSetting.installerPackageName);
10574                // If the currently set package isn't valid, then it's always
10575                // okay to change it.
10576                if (setting != null) {
10577                    if (compareSignatures(callerSignature,
10578                            setting.signatures.mSignatures)
10579                            != PackageManager.SIGNATURE_MATCH) {
10580                        throw new SecurityException(
10581                                "Caller does not have same cert as old installer package "
10582                                + targetPackageSetting.installerPackageName);
10583                    }
10584                }
10585            }
10586
10587            // Okay!
10588            targetPackageSetting.installerPackageName = installerPackageName;
10589            scheduleWriteSettingsLocked();
10590        }
10591    }
10592
10593    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10594        // Queue up an async operation since the package installation may take a little while.
10595        mHandler.post(new Runnable() {
10596            public void run() {
10597                mHandler.removeCallbacks(this);
10598                 // Result object to be returned
10599                PackageInstalledInfo res = new PackageInstalledInfo();
10600                res.returnCode = currentStatus;
10601                res.uid = -1;
10602                res.pkg = null;
10603                res.removedInfo = new PackageRemovedInfo();
10604                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10605                    args.doPreInstall(res.returnCode);
10606                    synchronized (mInstallLock) {
10607                        installPackageTracedLI(args, res);
10608                    }
10609                    args.doPostInstall(res.returnCode, res.uid);
10610                }
10611
10612                // A restore should be performed at this point if (a) the install
10613                // succeeded, (b) the operation is not an update, and (c) the new
10614                // package has not opted out of backup participation.
10615                final boolean update = res.removedInfo.removedPackage != null;
10616                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10617                boolean doRestore = !update
10618                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10619
10620                // Set up the post-install work request bookkeeping.  This will be used
10621                // and cleaned up by the post-install event handling regardless of whether
10622                // there's a restore pass performed.  Token values are >= 1.
10623                int token;
10624                if (mNextInstallToken < 0) mNextInstallToken = 1;
10625                token = mNextInstallToken++;
10626
10627                PostInstallData data = new PostInstallData(args, res);
10628                mRunningInstalls.put(token, data);
10629                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10630
10631                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10632                    // Pass responsibility to the Backup Manager.  It will perform a
10633                    // restore if appropriate, then pass responsibility back to the
10634                    // Package Manager to run the post-install observer callbacks
10635                    // and broadcasts.
10636                    IBackupManager bm = IBackupManager.Stub.asInterface(
10637                            ServiceManager.getService(Context.BACKUP_SERVICE));
10638                    if (bm != null) {
10639                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10640                                + " to BM for possible restore");
10641                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10642                        try {
10643                            // TODO: http://b/22388012
10644                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10645                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10646                            } else {
10647                                doRestore = false;
10648                            }
10649                        } catch (RemoteException e) {
10650                            // can't happen; the backup manager is local
10651                        } catch (Exception e) {
10652                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10653                            doRestore = false;
10654                        }
10655                    } else {
10656                        Slog.e(TAG, "Backup Manager not found!");
10657                        doRestore = false;
10658                    }
10659                }
10660
10661                if (!doRestore) {
10662                    // No restore possible, or the Backup Manager was mysteriously not
10663                    // available -- just fire the post-install work request directly.
10664                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10665
10666                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10667
10668                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10669                    mHandler.sendMessage(msg);
10670                }
10671            }
10672        });
10673    }
10674
10675    private abstract class HandlerParams {
10676        private static final int MAX_RETRIES = 4;
10677
10678        /**
10679         * Number of times startCopy() has been attempted and had a non-fatal
10680         * error.
10681         */
10682        private int mRetries = 0;
10683
10684        /** User handle for the user requesting the information or installation. */
10685        private final UserHandle mUser;
10686        String traceMethod;
10687        int traceCookie;
10688
10689        HandlerParams(UserHandle user) {
10690            mUser = user;
10691        }
10692
10693        UserHandle getUser() {
10694            return mUser;
10695        }
10696
10697        HandlerParams setTraceMethod(String traceMethod) {
10698            this.traceMethod = traceMethod;
10699            return this;
10700        }
10701
10702        HandlerParams setTraceCookie(int traceCookie) {
10703            this.traceCookie = traceCookie;
10704            return this;
10705        }
10706
10707        final boolean startCopy() {
10708            boolean res;
10709            try {
10710                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10711
10712                if (++mRetries > MAX_RETRIES) {
10713                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10714                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10715                    handleServiceError();
10716                    return false;
10717                } else {
10718                    handleStartCopy();
10719                    res = true;
10720                }
10721            } catch (RemoteException e) {
10722                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10723                mHandler.sendEmptyMessage(MCS_RECONNECT);
10724                res = false;
10725            }
10726            handleReturnCode();
10727            return res;
10728        }
10729
10730        final void serviceError() {
10731            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10732            handleServiceError();
10733            handleReturnCode();
10734        }
10735
10736        abstract void handleStartCopy() throws RemoteException;
10737        abstract void handleServiceError();
10738        abstract void handleReturnCode();
10739    }
10740
10741    class MeasureParams extends HandlerParams {
10742        private final PackageStats mStats;
10743        private boolean mSuccess;
10744
10745        private final IPackageStatsObserver mObserver;
10746
10747        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10748            super(new UserHandle(stats.userHandle));
10749            mObserver = observer;
10750            mStats = stats;
10751        }
10752
10753        @Override
10754        public String toString() {
10755            return "MeasureParams{"
10756                + Integer.toHexString(System.identityHashCode(this))
10757                + " " + mStats.packageName + "}";
10758        }
10759
10760        @Override
10761        void handleStartCopy() throws RemoteException {
10762            synchronized (mInstallLock) {
10763                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10764            }
10765
10766            if (mSuccess) {
10767                final boolean mounted;
10768                if (Environment.isExternalStorageEmulated()) {
10769                    mounted = true;
10770                } else {
10771                    final String status = Environment.getExternalStorageState();
10772                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10773                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10774                }
10775
10776                if (mounted) {
10777                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10778
10779                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10780                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10781
10782                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10783                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10784
10785                    // Always subtract cache size, since it's a subdirectory
10786                    mStats.externalDataSize -= mStats.externalCacheSize;
10787
10788                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10789                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10790
10791                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10792                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10793                }
10794            }
10795        }
10796
10797        @Override
10798        void handleReturnCode() {
10799            if (mObserver != null) {
10800                try {
10801                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10802                } catch (RemoteException e) {
10803                    Slog.i(TAG, "Observer no longer exists.");
10804                }
10805            }
10806        }
10807
10808        @Override
10809        void handleServiceError() {
10810            Slog.e(TAG, "Could not measure application " + mStats.packageName
10811                            + " external storage");
10812        }
10813    }
10814
10815    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10816            throws RemoteException {
10817        long result = 0;
10818        for (File path : paths) {
10819            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10820        }
10821        return result;
10822    }
10823
10824    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10825        for (File path : paths) {
10826            try {
10827                mcs.clearDirectory(path.getAbsolutePath());
10828            } catch (RemoteException e) {
10829            }
10830        }
10831    }
10832
10833    static class OriginInfo {
10834        /**
10835         * Location where install is coming from, before it has been
10836         * copied/renamed into place. This could be a single monolithic APK
10837         * file, or a cluster directory. This location may be untrusted.
10838         */
10839        final File file;
10840        final String cid;
10841
10842        /**
10843         * Flag indicating that {@link #file} or {@link #cid} has already been
10844         * staged, meaning downstream users don't need to defensively copy the
10845         * contents.
10846         */
10847        final boolean staged;
10848
10849        /**
10850         * Flag indicating that {@link #file} or {@link #cid} is an already
10851         * installed app that is being moved.
10852         */
10853        final boolean existing;
10854
10855        final String resolvedPath;
10856        final File resolvedFile;
10857
10858        static OriginInfo fromNothing() {
10859            return new OriginInfo(null, null, false, false);
10860        }
10861
10862        static OriginInfo fromUntrustedFile(File file) {
10863            return new OriginInfo(file, null, false, false);
10864        }
10865
10866        static OriginInfo fromExistingFile(File file) {
10867            return new OriginInfo(file, null, false, true);
10868        }
10869
10870        static OriginInfo fromStagedFile(File file) {
10871            return new OriginInfo(file, null, true, false);
10872        }
10873
10874        static OriginInfo fromStagedContainer(String cid) {
10875            return new OriginInfo(null, cid, true, false);
10876        }
10877
10878        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10879            this.file = file;
10880            this.cid = cid;
10881            this.staged = staged;
10882            this.existing = existing;
10883
10884            if (cid != null) {
10885                resolvedPath = PackageHelper.getSdDir(cid);
10886                resolvedFile = new File(resolvedPath);
10887            } else if (file != null) {
10888                resolvedPath = file.getAbsolutePath();
10889                resolvedFile = file;
10890            } else {
10891                resolvedPath = null;
10892                resolvedFile = null;
10893            }
10894        }
10895    }
10896
10897    static class MoveInfo {
10898        final int moveId;
10899        final String fromUuid;
10900        final String toUuid;
10901        final String packageName;
10902        final String dataAppName;
10903        final int appId;
10904        final String seinfo;
10905
10906        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10907                String dataAppName, int appId, String seinfo) {
10908            this.moveId = moveId;
10909            this.fromUuid = fromUuid;
10910            this.toUuid = toUuid;
10911            this.packageName = packageName;
10912            this.dataAppName = dataAppName;
10913            this.appId = appId;
10914            this.seinfo = seinfo;
10915        }
10916    }
10917
10918    class InstallParams extends HandlerParams {
10919        final OriginInfo origin;
10920        final MoveInfo move;
10921        final IPackageInstallObserver2 observer;
10922        int installFlags;
10923        final String installerPackageName;
10924        final String volumeUuid;
10925        final VerificationParams verificationParams;
10926        private InstallArgs mArgs;
10927        private int mRet;
10928        final String packageAbiOverride;
10929        final String[] grantedRuntimePermissions;
10930
10931        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10932                int installFlags, String installerPackageName, String volumeUuid,
10933                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10934                String[] grantedPermissions) {
10935            super(user);
10936            this.origin = origin;
10937            this.move = move;
10938            this.observer = observer;
10939            this.installFlags = installFlags;
10940            this.installerPackageName = installerPackageName;
10941            this.volumeUuid = volumeUuid;
10942            this.verificationParams = verificationParams;
10943            this.packageAbiOverride = packageAbiOverride;
10944            this.grantedRuntimePermissions = grantedPermissions;
10945        }
10946
10947        @Override
10948        public String toString() {
10949            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10950                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10951        }
10952
10953        private int installLocationPolicy(PackageInfoLite pkgLite) {
10954            String packageName = pkgLite.packageName;
10955            int installLocation = pkgLite.installLocation;
10956            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10957            // reader
10958            synchronized (mPackages) {
10959                PackageParser.Package pkg = mPackages.get(packageName);
10960                if (pkg != null) {
10961                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10962                        // Check for downgrading.
10963                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10964                            try {
10965                                checkDowngrade(pkg, pkgLite);
10966                            } catch (PackageManagerException e) {
10967                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10968                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10969                            }
10970                        }
10971                        // Check for updated system application.
10972                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10973                            if (onSd) {
10974                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10975                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10976                            }
10977                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10978                        } else {
10979                            if (onSd) {
10980                                // Install flag overrides everything.
10981                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10982                            }
10983                            // If current upgrade specifies particular preference
10984                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10985                                // Application explicitly specified internal.
10986                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10987                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10988                                // App explictly prefers external. Let policy decide
10989                            } else {
10990                                // Prefer previous location
10991                                if (isExternal(pkg)) {
10992                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10993                                }
10994                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10995                            }
10996                        }
10997                    } else {
10998                        // Invalid install. Return error code
10999                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11000                    }
11001                }
11002            }
11003            // All the special cases have been taken care of.
11004            // Return result based on recommended install location.
11005            if (onSd) {
11006                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11007            }
11008            return pkgLite.recommendedInstallLocation;
11009        }
11010
11011        /*
11012         * Invoke remote method to get package information and install
11013         * location values. Override install location based on default
11014         * policy if needed and then create install arguments based
11015         * on the install location.
11016         */
11017        public void handleStartCopy() throws RemoteException {
11018            int ret = PackageManager.INSTALL_SUCCEEDED;
11019
11020            // If we're already staged, we've firmly committed to an install location
11021            if (origin.staged) {
11022                if (origin.file != null) {
11023                    installFlags |= PackageManager.INSTALL_INTERNAL;
11024                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11025                } else if (origin.cid != null) {
11026                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11027                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11028                } else {
11029                    throw new IllegalStateException("Invalid stage location");
11030                }
11031            }
11032
11033            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11034            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11035            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11036            PackageInfoLite pkgLite = null;
11037
11038            if (onInt && onSd) {
11039                // Check if both bits are set.
11040                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11041                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11042            } else if (onSd && ephemeral) {
11043                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11044                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11045            } else {
11046                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11047                        packageAbiOverride);
11048
11049                if (DEBUG_EPHEMERAL && ephemeral) {
11050                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11051                }
11052
11053                /*
11054                 * If we have too little free space, try to free cache
11055                 * before giving up.
11056                 */
11057                if (!origin.staged && pkgLite.recommendedInstallLocation
11058                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11059                    // TODO: focus freeing disk space on the target device
11060                    final StorageManager storage = StorageManager.from(mContext);
11061                    final long lowThreshold = storage.getStorageLowBytes(
11062                            Environment.getDataDirectory());
11063
11064                    final long sizeBytes = mContainerService.calculateInstalledSize(
11065                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11066
11067                    try {
11068                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11069                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11070                                installFlags, packageAbiOverride);
11071                    } catch (InstallerException e) {
11072                        Slog.w(TAG, "Failed to free cache", e);
11073                    }
11074
11075                    /*
11076                     * The cache free must have deleted the file we
11077                     * downloaded to install.
11078                     *
11079                     * TODO: fix the "freeCache" call to not delete
11080                     *       the file we care about.
11081                     */
11082                    if (pkgLite.recommendedInstallLocation
11083                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11084                        pkgLite.recommendedInstallLocation
11085                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11086                    }
11087                }
11088            }
11089
11090            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11091                int loc = pkgLite.recommendedInstallLocation;
11092                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11093                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11094                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11095                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11096                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11097                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11098                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11099                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11100                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11101                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11102                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11103                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11104                } else {
11105                    // Override with defaults if needed.
11106                    loc = installLocationPolicy(pkgLite);
11107                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11108                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11109                    } else if (!onSd && !onInt) {
11110                        // Override install location with flags
11111                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11112                            // Set the flag to install on external media.
11113                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11114                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11115                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11116                            if (DEBUG_EPHEMERAL) {
11117                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11118                            }
11119                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11120                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11121                                    |PackageManager.INSTALL_INTERNAL);
11122                        } else {
11123                            // Make sure the flag for installing on external
11124                            // media is unset
11125                            installFlags |= PackageManager.INSTALL_INTERNAL;
11126                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11127                        }
11128                    }
11129                }
11130            }
11131
11132            final InstallArgs args = createInstallArgs(this);
11133            mArgs = args;
11134
11135            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11136                // TODO: http://b/22976637
11137                // Apps installed for "all" users use the device owner to verify the app
11138                UserHandle verifierUser = getUser();
11139                if (verifierUser == UserHandle.ALL) {
11140                    verifierUser = UserHandle.SYSTEM;
11141                }
11142
11143                /*
11144                 * Determine if we have any installed package verifiers. If we
11145                 * do, then we'll defer to them to verify the packages.
11146                 */
11147                final int requiredUid = mRequiredVerifierPackage == null ? -1
11148                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11149                                verifierUser.getIdentifier());
11150                if (!origin.existing && requiredUid != -1
11151                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11152                    final Intent verification = new Intent(
11153                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11154                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11155                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11156                            PACKAGE_MIME_TYPE);
11157                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11158
11159                    // Query all live verifiers based on current user state
11160                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11161                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11162
11163                    if (DEBUG_VERIFY) {
11164                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11165                                + verification.toString() + " with " + pkgLite.verifiers.length
11166                                + " optional verifiers");
11167                    }
11168
11169                    final int verificationId = mPendingVerificationToken++;
11170
11171                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11172
11173                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11174                            installerPackageName);
11175
11176                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11177                            installFlags);
11178
11179                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11180                            pkgLite.packageName);
11181
11182                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11183                            pkgLite.versionCode);
11184
11185                    if (verificationParams != null) {
11186                        if (verificationParams.getVerificationURI() != null) {
11187                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11188                                 verificationParams.getVerificationURI());
11189                        }
11190                        if (verificationParams.getOriginatingURI() != null) {
11191                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11192                                  verificationParams.getOriginatingURI());
11193                        }
11194                        if (verificationParams.getReferrer() != null) {
11195                            verification.putExtra(Intent.EXTRA_REFERRER,
11196                                  verificationParams.getReferrer());
11197                        }
11198                        if (verificationParams.getOriginatingUid() >= 0) {
11199                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11200                                  verificationParams.getOriginatingUid());
11201                        }
11202                        if (verificationParams.getInstallerUid() >= 0) {
11203                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11204                                  verificationParams.getInstallerUid());
11205                        }
11206                    }
11207
11208                    final PackageVerificationState verificationState = new PackageVerificationState(
11209                            requiredUid, args);
11210
11211                    mPendingVerification.append(verificationId, verificationState);
11212
11213                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11214                            receivers, verificationState);
11215
11216                    /*
11217                     * If any sufficient verifiers were listed in the package
11218                     * manifest, attempt to ask them.
11219                     */
11220                    if (sufficientVerifiers != null) {
11221                        final int N = sufficientVerifiers.size();
11222                        if (N == 0) {
11223                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11224                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11225                        } else {
11226                            for (int i = 0; i < N; i++) {
11227                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11228
11229                                final Intent sufficientIntent = new Intent(verification);
11230                                sufficientIntent.setComponent(verifierComponent);
11231                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11232                            }
11233                        }
11234                    }
11235
11236                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11237                            mRequiredVerifierPackage, receivers);
11238                    if (ret == PackageManager.INSTALL_SUCCEEDED
11239                            && mRequiredVerifierPackage != null) {
11240                        Trace.asyncTraceBegin(
11241                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11242                        /*
11243                         * Send the intent to the required verification agent,
11244                         * but only start the verification timeout after the
11245                         * target BroadcastReceivers have run.
11246                         */
11247                        verification.setComponent(requiredVerifierComponent);
11248                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11249                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11250                                new BroadcastReceiver() {
11251                                    @Override
11252                                    public void onReceive(Context context, Intent intent) {
11253                                        final Message msg = mHandler
11254                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11255                                        msg.arg1 = verificationId;
11256                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11257                                    }
11258                                }, null, 0, null, null);
11259
11260                        /*
11261                         * We don't want the copy to proceed until verification
11262                         * succeeds, so null out this field.
11263                         */
11264                        mArgs = null;
11265                    }
11266                } else {
11267                    /*
11268                     * No package verification is enabled, so immediately start
11269                     * the remote call to initiate copy using temporary file.
11270                     */
11271                    ret = args.copyApk(mContainerService, true);
11272                }
11273            }
11274
11275            mRet = ret;
11276        }
11277
11278        @Override
11279        void handleReturnCode() {
11280            // If mArgs is null, then MCS couldn't be reached. When it
11281            // reconnects, it will try again to install. At that point, this
11282            // will succeed.
11283            if (mArgs != null) {
11284                processPendingInstall(mArgs, mRet);
11285            }
11286        }
11287
11288        @Override
11289        void handleServiceError() {
11290            mArgs = createInstallArgs(this);
11291            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11292        }
11293
11294        public boolean isForwardLocked() {
11295            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11296        }
11297    }
11298
11299    /**
11300     * Used during creation of InstallArgs
11301     *
11302     * @param installFlags package installation flags
11303     * @return true if should be installed on external storage
11304     */
11305    private static boolean installOnExternalAsec(int installFlags) {
11306        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11307            return false;
11308        }
11309        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11310            return true;
11311        }
11312        return false;
11313    }
11314
11315    /**
11316     * Used during creation of InstallArgs
11317     *
11318     * @param installFlags package installation flags
11319     * @return true if should be installed as forward locked
11320     */
11321    private static boolean installForwardLocked(int installFlags) {
11322        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11323    }
11324
11325    private InstallArgs createInstallArgs(InstallParams params) {
11326        if (params.move != null) {
11327            return new MoveInstallArgs(params);
11328        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11329            return new AsecInstallArgs(params);
11330        } else {
11331            return new FileInstallArgs(params);
11332        }
11333    }
11334
11335    /**
11336     * Create args that describe an existing installed package. Typically used
11337     * when cleaning up old installs, or used as a move source.
11338     */
11339    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11340            String resourcePath, String[] instructionSets) {
11341        final boolean isInAsec;
11342        if (installOnExternalAsec(installFlags)) {
11343            /* Apps on SD card are always in ASEC containers. */
11344            isInAsec = true;
11345        } else if (installForwardLocked(installFlags)
11346                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11347            /*
11348             * Forward-locked apps are only in ASEC containers if they're the
11349             * new style
11350             */
11351            isInAsec = true;
11352        } else {
11353            isInAsec = false;
11354        }
11355
11356        if (isInAsec) {
11357            return new AsecInstallArgs(codePath, instructionSets,
11358                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11359        } else {
11360            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11361        }
11362    }
11363
11364    static abstract class InstallArgs {
11365        /** @see InstallParams#origin */
11366        final OriginInfo origin;
11367        /** @see InstallParams#move */
11368        final MoveInfo move;
11369
11370        final IPackageInstallObserver2 observer;
11371        // Always refers to PackageManager flags only
11372        final int installFlags;
11373        final String installerPackageName;
11374        final String volumeUuid;
11375        final UserHandle user;
11376        final String abiOverride;
11377        final String[] installGrantPermissions;
11378        /** If non-null, drop an async trace when the install completes */
11379        final String traceMethod;
11380        final int traceCookie;
11381
11382        // The list of instruction sets supported by this app. This is currently
11383        // only used during the rmdex() phase to clean up resources. We can get rid of this
11384        // if we move dex files under the common app path.
11385        /* nullable */ String[] instructionSets;
11386
11387        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11388                int installFlags, String installerPackageName, String volumeUuid,
11389                UserHandle user, String[] instructionSets,
11390                String abiOverride, String[] installGrantPermissions,
11391                String traceMethod, int traceCookie) {
11392            this.origin = origin;
11393            this.move = move;
11394            this.installFlags = installFlags;
11395            this.observer = observer;
11396            this.installerPackageName = installerPackageName;
11397            this.volumeUuid = volumeUuid;
11398            this.user = user;
11399            this.instructionSets = instructionSets;
11400            this.abiOverride = abiOverride;
11401            this.installGrantPermissions = installGrantPermissions;
11402            this.traceMethod = traceMethod;
11403            this.traceCookie = traceCookie;
11404        }
11405
11406        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11407        abstract int doPreInstall(int status);
11408
11409        /**
11410         * Rename package into final resting place. All paths on the given
11411         * scanned package should be updated to reflect the rename.
11412         */
11413        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11414        abstract int doPostInstall(int status, int uid);
11415
11416        /** @see PackageSettingBase#codePathString */
11417        abstract String getCodePath();
11418        /** @see PackageSettingBase#resourcePathString */
11419        abstract String getResourcePath();
11420
11421        // Need installer lock especially for dex file removal.
11422        abstract void cleanUpResourcesLI();
11423        abstract boolean doPostDeleteLI(boolean delete);
11424
11425        /**
11426         * Called before the source arguments are copied. This is used mostly
11427         * for MoveParams when it needs to read the source file to put it in the
11428         * destination.
11429         */
11430        int doPreCopy() {
11431            return PackageManager.INSTALL_SUCCEEDED;
11432        }
11433
11434        /**
11435         * Called after the source arguments are copied. This is used mostly for
11436         * MoveParams when it needs to read the source file to put it in the
11437         * destination.
11438         *
11439         * @return
11440         */
11441        int doPostCopy(int uid) {
11442            return PackageManager.INSTALL_SUCCEEDED;
11443        }
11444
11445        protected boolean isFwdLocked() {
11446            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11447        }
11448
11449        protected boolean isExternalAsec() {
11450            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11451        }
11452
11453        protected boolean isEphemeral() {
11454            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11455        }
11456
11457        UserHandle getUser() {
11458            return user;
11459        }
11460    }
11461
11462    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11463        if (!allCodePaths.isEmpty()) {
11464            if (instructionSets == null) {
11465                throw new IllegalStateException("instructionSet == null");
11466            }
11467            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11468            for (String codePath : allCodePaths) {
11469                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11470                    try {
11471                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11472                    } catch (InstallerException ignored) {
11473                    }
11474                }
11475            }
11476        }
11477    }
11478
11479    /**
11480     * Logic to handle installation of non-ASEC applications, including copying
11481     * and renaming logic.
11482     */
11483    class FileInstallArgs extends InstallArgs {
11484        private File codeFile;
11485        private File resourceFile;
11486
11487        // Example topology:
11488        // /data/app/com.example/base.apk
11489        // /data/app/com.example/split_foo.apk
11490        // /data/app/com.example/lib/arm/libfoo.so
11491        // /data/app/com.example/lib/arm64/libfoo.so
11492        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11493
11494        /** New install */
11495        FileInstallArgs(InstallParams params) {
11496            super(params.origin, params.move, params.observer, params.installFlags,
11497                    params.installerPackageName, params.volumeUuid,
11498                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11499                    params.grantedRuntimePermissions,
11500                    params.traceMethod, params.traceCookie);
11501            if (isFwdLocked()) {
11502                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11503            }
11504        }
11505
11506        /** Existing install */
11507        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11508            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11509                    null, null, null, 0);
11510            this.codeFile = (codePath != null) ? new File(codePath) : null;
11511            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11512        }
11513
11514        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11515            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11516            try {
11517                return doCopyApk(imcs, temp);
11518            } finally {
11519                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11520            }
11521        }
11522
11523        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11524            if (origin.staged) {
11525                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11526                codeFile = origin.file;
11527                resourceFile = origin.file;
11528                return PackageManager.INSTALL_SUCCEEDED;
11529            }
11530
11531            try {
11532                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11533                final File tempDir =
11534                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11535                codeFile = tempDir;
11536                resourceFile = tempDir;
11537            } catch (IOException e) {
11538                Slog.w(TAG, "Failed to create copy file: " + e);
11539                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11540            }
11541
11542            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11543                @Override
11544                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11545                    if (!FileUtils.isValidExtFilename(name)) {
11546                        throw new IllegalArgumentException("Invalid filename: " + name);
11547                    }
11548                    try {
11549                        final File file = new File(codeFile, name);
11550                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11551                                O_RDWR | O_CREAT, 0644);
11552                        Os.chmod(file.getAbsolutePath(), 0644);
11553                        return new ParcelFileDescriptor(fd);
11554                    } catch (ErrnoException e) {
11555                        throw new RemoteException("Failed to open: " + e.getMessage());
11556                    }
11557                }
11558            };
11559
11560            int ret = PackageManager.INSTALL_SUCCEEDED;
11561            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11562            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11563                Slog.e(TAG, "Failed to copy package");
11564                return ret;
11565            }
11566
11567            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11568            NativeLibraryHelper.Handle handle = null;
11569            try {
11570                handle = NativeLibraryHelper.Handle.create(codeFile);
11571                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11572                        abiOverride);
11573            } catch (IOException e) {
11574                Slog.e(TAG, "Copying native libraries failed", e);
11575                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11576            } finally {
11577                IoUtils.closeQuietly(handle);
11578            }
11579
11580            return ret;
11581        }
11582
11583        int doPreInstall(int status) {
11584            if (status != PackageManager.INSTALL_SUCCEEDED) {
11585                cleanUp();
11586            }
11587            return status;
11588        }
11589
11590        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11591            if (status != PackageManager.INSTALL_SUCCEEDED) {
11592                cleanUp();
11593                return false;
11594            }
11595
11596            final File targetDir = codeFile.getParentFile();
11597            final File beforeCodeFile = codeFile;
11598            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11599
11600            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11601            try {
11602                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11603            } catch (ErrnoException e) {
11604                Slog.w(TAG, "Failed to rename", e);
11605                return false;
11606            }
11607
11608            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11609                Slog.w(TAG, "Failed to restorecon");
11610                return false;
11611            }
11612
11613            // Reflect the rename internally
11614            codeFile = afterCodeFile;
11615            resourceFile = afterCodeFile;
11616
11617            // Reflect the rename in scanned details
11618            pkg.codePath = afterCodeFile.getAbsolutePath();
11619            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11620                    pkg.baseCodePath);
11621            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11622                    pkg.splitCodePaths);
11623
11624            // Reflect the rename in app info
11625            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11626            pkg.applicationInfo.setCodePath(pkg.codePath);
11627            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11628            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11629            pkg.applicationInfo.setResourcePath(pkg.codePath);
11630            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11631            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11632
11633            return true;
11634        }
11635
11636        int doPostInstall(int status, int uid) {
11637            if (status != PackageManager.INSTALL_SUCCEEDED) {
11638                cleanUp();
11639            }
11640            return status;
11641        }
11642
11643        @Override
11644        String getCodePath() {
11645            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11646        }
11647
11648        @Override
11649        String getResourcePath() {
11650            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11651        }
11652
11653        private boolean cleanUp() {
11654            if (codeFile == null || !codeFile.exists()) {
11655                return false;
11656            }
11657
11658            removeCodePathLI(codeFile);
11659
11660            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11661                resourceFile.delete();
11662            }
11663
11664            return true;
11665        }
11666
11667        void cleanUpResourcesLI() {
11668            // Try enumerating all code paths before deleting
11669            List<String> allCodePaths = Collections.EMPTY_LIST;
11670            if (codeFile != null && codeFile.exists()) {
11671                try {
11672                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11673                    allCodePaths = pkg.getAllCodePaths();
11674                } catch (PackageParserException e) {
11675                    // Ignored; we tried our best
11676                }
11677            }
11678
11679            cleanUp();
11680            removeDexFiles(allCodePaths, instructionSets);
11681        }
11682
11683        boolean doPostDeleteLI(boolean delete) {
11684            // XXX err, shouldn't we respect the delete flag?
11685            cleanUpResourcesLI();
11686            return true;
11687        }
11688    }
11689
11690    private boolean isAsecExternal(String cid) {
11691        final String asecPath = PackageHelper.getSdFilesystem(cid);
11692        return !asecPath.startsWith(mAsecInternalPath);
11693    }
11694
11695    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11696            PackageManagerException {
11697        if (copyRet < 0) {
11698            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11699                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11700                throw new PackageManagerException(copyRet, message);
11701            }
11702        }
11703    }
11704
11705    /**
11706     * Extract the MountService "container ID" from the full code path of an
11707     * .apk.
11708     */
11709    static String cidFromCodePath(String fullCodePath) {
11710        int eidx = fullCodePath.lastIndexOf("/");
11711        String subStr1 = fullCodePath.substring(0, eidx);
11712        int sidx = subStr1.lastIndexOf("/");
11713        return subStr1.substring(sidx+1, eidx);
11714    }
11715
11716    /**
11717     * Logic to handle installation of ASEC applications, including copying and
11718     * renaming logic.
11719     */
11720    class AsecInstallArgs extends InstallArgs {
11721        static final String RES_FILE_NAME = "pkg.apk";
11722        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11723
11724        String cid;
11725        String packagePath;
11726        String resourcePath;
11727
11728        /** New install */
11729        AsecInstallArgs(InstallParams params) {
11730            super(params.origin, params.move, params.observer, params.installFlags,
11731                    params.installerPackageName, params.volumeUuid,
11732                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11733                    params.grantedRuntimePermissions,
11734                    params.traceMethod, params.traceCookie);
11735        }
11736
11737        /** Existing install */
11738        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11739                        boolean isExternal, boolean isForwardLocked) {
11740            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11741                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11742                    instructionSets, null, null, null, 0);
11743            // Hackily pretend we're still looking at a full code path
11744            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11745                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11746            }
11747
11748            // Extract cid from fullCodePath
11749            int eidx = fullCodePath.lastIndexOf("/");
11750            String subStr1 = fullCodePath.substring(0, eidx);
11751            int sidx = subStr1.lastIndexOf("/");
11752            cid = subStr1.substring(sidx+1, eidx);
11753            setMountPath(subStr1);
11754        }
11755
11756        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11757            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11758                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11759                    instructionSets, null, null, null, 0);
11760            this.cid = cid;
11761            setMountPath(PackageHelper.getSdDir(cid));
11762        }
11763
11764        void createCopyFile() {
11765            cid = mInstallerService.allocateExternalStageCidLegacy();
11766        }
11767
11768        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11769            if (origin.staged && origin.cid != null) {
11770                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11771                cid = origin.cid;
11772                setMountPath(PackageHelper.getSdDir(cid));
11773                return PackageManager.INSTALL_SUCCEEDED;
11774            }
11775
11776            if (temp) {
11777                createCopyFile();
11778            } else {
11779                /*
11780                 * Pre-emptively destroy the container since it's destroyed if
11781                 * copying fails due to it existing anyway.
11782                 */
11783                PackageHelper.destroySdDir(cid);
11784            }
11785
11786            final String newMountPath = imcs.copyPackageToContainer(
11787                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11788                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11789
11790            if (newMountPath != null) {
11791                setMountPath(newMountPath);
11792                return PackageManager.INSTALL_SUCCEEDED;
11793            } else {
11794                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11795            }
11796        }
11797
11798        @Override
11799        String getCodePath() {
11800            return packagePath;
11801        }
11802
11803        @Override
11804        String getResourcePath() {
11805            return resourcePath;
11806        }
11807
11808        int doPreInstall(int status) {
11809            if (status != PackageManager.INSTALL_SUCCEEDED) {
11810                // Destroy container
11811                PackageHelper.destroySdDir(cid);
11812            } else {
11813                boolean mounted = PackageHelper.isContainerMounted(cid);
11814                if (!mounted) {
11815                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11816                            Process.SYSTEM_UID);
11817                    if (newMountPath != null) {
11818                        setMountPath(newMountPath);
11819                    } else {
11820                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11821                    }
11822                }
11823            }
11824            return status;
11825        }
11826
11827        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11828            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11829            String newMountPath = null;
11830            if (PackageHelper.isContainerMounted(cid)) {
11831                // Unmount the container
11832                if (!PackageHelper.unMountSdDir(cid)) {
11833                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11834                    return false;
11835                }
11836            }
11837            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11838                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11839                        " which might be stale. Will try to clean up.");
11840                // Clean up the stale container and proceed to recreate.
11841                if (!PackageHelper.destroySdDir(newCacheId)) {
11842                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11843                    return false;
11844                }
11845                // Successfully cleaned up stale container. Try to rename again.
11846                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11847                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11848                            + " inspite of cleaning it up.");
11849                    return false;
11850                }
11851            }
11852            if (!PackageHelper.isContainerMounted(newCacheId)) {
11853                Slog.w(TAG, "Mounting container " + newCacheId);
11854                newMountPath = PackageHelper.mountSdDir(newCacheId,
11855                        getEncryptKey(), Process.SYSTEM_UID);
11856            } else {
11857                newMountPath = PackageHelper.getSdDir(newCacheId);
11858            }
11859            if (newMountPath == null) {
11860                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11861                return false;
11862            }
11863            Log.i(TAG, "Succesfully renamed " + cid +
11864                    " to " + newCacheId +
11865                    " at new path: " + newMountPath);
11866            cid = newCacheId;
11867
11868            final File beforeCodeFile = new File(packagePath);
11869            setMountPath(newMountPath);
11870            final File afterCodeFile = new File(packagePath);
11871
11872            // Reflect the rename in scanned details
11873            pkg.codePath = afterCodeFile.getAbsolutePath();
11874            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11875                    pkg.baseCodePath);
11876            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11877                    pkg.splitCodePaths);
11878
11879            // Reflect the rename in app info
11880            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11881            pkg.applicationInfo.setCodePath(pkg.codePath);
11882            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11883            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11884            pkg.applicationInfo.setResourcePath(pkg.codePath);
11885            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11886            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11887
11888            return true;
11889        }
11890
11891        private void setMountPath(String mountPath) {
11892            final File mountFile = new File(mountPath);
11893
11894            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11895            if (monolithicFile.exists()) {
11896                packagePath = monolithicFile.getAbsolutePath();
11897                if (isFwdLocked()) {
11898                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11899                } else {
11900                    resourcePath = packagePath;
11901                }
11902            } else {
11903                packagePath = mountFile.getAbsolutePath();
11904                resourcePath = packagePath;
11905            }
11906        }
11907
11908        int doPostInstall(int status, int uid) {
11909            if (status != PackageManager.INSTALL_SUCCEEDED) {
11910                cleanUp();
11911            } else {
11912                final int groupOwner;
11913                final String protectedFile;
11914                if (isFwdLocked()) {
11915                    groupOwner = UserHandle.getSharedAppGid(uid);
11916                    protectedFile = RES_FILE_NAME;
11917                } else {
11918                    groupOwner = -1;
11919                    protectedFile = null;
11920                }
11921
11922                if (uid < Process.FIRST_APPLICATION_UID
11923                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11924                    Slog.e(TAG, "Failed to finalize " + cid);
11925                    PackageHelper.destroySdDir(cid);
11926                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11927                }
11928
11929                boolean mounted = PackageHelper.isContainerMounted(cid);
11930                if (!mounted) {
11931                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11932                }
11933            }
11934            return status;
11935        }
11936
11937        private void cleanUp() {
11938            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11939
11940            // Destroy secure container
11941            PackageHelper.destroySdDir(cid);
11942        }
11943
11944        private List<String> getAllCodePaths() {
11945            final File codeFile = new File(getCodePath());
11946            if (codeFile != null && codeFile.exists()) {
11947                try {
11948                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11949                    return pkg.getAllCodePaths();
11950                } catch (PackageParserException e) {
11951                    // Ignored; we tried our best
11952                }
11953            }
11954            return Collections.EMPTY_LIST;
11955        }
11956
11957        void cleanUpResourcesLI() {
11958            // Enumerate all code paths before deleting
11959            cleanUpResourcesLI(getAllCodePaths());
11960        }
11961
11962        private void cleanUpResourcesLI(List<String> allCodePaths) {
11963            cleanUp();
11964            removeDexFiles(allCodePaths, instructionSets);
11965        }
11966
11967        String getPackageName() {
11968            return getAsecPackageName(cid);
11969        }
11970
11971        boolean doPostDeleteLI(boolean delete) {
11972            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11973            final List<String> allCodePaths = getAllCodePaths();
11974            boolean mounted = PackageHelper.isContainerMounted(cid);
11975            if (mounted) {
11976                // Unmount first
11977                if (PackageHelper.unMountSdDir(cid)) {
11978                    mounted = false;
11979                }
11980            }
11981            if (!mounted && delete) {
11982                cleanUpResourcesLI(allCodePaths);
11983            }
11984            return !mounted;
11985        }
11986
11987        @Override
11988        int doPreCopy() {
11989            if (isFwdLocked()) {
11990                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
11991                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
11992                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11993                }
11994            }
11995
11996            return PackageManager.INSTALL_SUCCEEDED;
11997        }
11998
11999        @Override
12000        int doPostCopy(int uid) {
12001            if (isFwdLocked()) {
12002                if (uid < Process.FIRST_APPLICATION_UID
12003                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12004                                RES_FILE_NAME)) {
12005                    Slog.e(TAG, "Failed to finalize " + cid);
12006                    PackageHelper.destroySdDir(cid);
12007                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12008                }
12009            }
12010
12011            return PackageManager.INSTALL_SUCCEEDED;
12012        }
12013    }
12014
12015    /**
12016     * Logic to handle movement of existing installed applications.
12017     */
12018    class MoveInstallArgs extends InstallArgs {
12019        private File codeFile;
12020        private File resourceFile;
12021
12022        /** New install */
12023        MoveInstallArgs(InstallParams params) {
12024            super(params.origin, params.move, params.observer, params.installFlags,
12025                    params.installerPackageName, params.volumeUuid,
12026                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12027                    params.grantedRuntimePermissions,
12028                    params.traceMethod, params.traceCookie);
12029        }
12030
12031        int copyApk(IMediaContainerService imcs, boolean temp) {
12032            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12033                    + move.fromUuid + " to " + move.toUuid);
12034            synchronized (mInstaller) {
12035                try {
12036                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12037                            move.dataAppName, move.appId, move.seinfo);
12038                } catch (InstallerException e) {
12039                    Slog.w(TAG, "Failed to move app", e);
12040                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12041                }
12042            }
12043
12044            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12045            resourceFile = codeFile;
12046            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12047
12048            return PackageManager.INSTALL_SUCCEEDED;
12049        }
12050
12051        int doPreInstall(int status) {
12052            if (status != PackageManager.INSTALL_SUCCEEDED) {
12053                cleanUp(move.toUuid);
12054            }
12055            return status;
12056        }
12057
12058        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12059            if (status != PackageManager.INSTALL_SUCCEEDED) {
12060                cleanUp(move.toUuid);
12061                return false;
12062            }
12063
12064            // Reflect the move in app info
12065            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12066            pkg.applicationInfo.setCodePath(pkg.codePath);
12067            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12068            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12069            pkg.applicationInfo.setResourcePath(pkg.codePath);
12070            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12071            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12072
12073            return true;
12074        }
12075
12076        int doPostInstall(int status, int uid) {
12077            if (status == PackageManager.INSTALL_SUCCEEDED) {
12078                cleanUp(move.fromUuid);
12079            } else {
12080                cleanUp(move.toUuid);
12081            }
12082            return status;
12083        }
12084
12085        @Override
12086        String getCodePath() {
12087            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12088        }
12089
12090        @Override
12091        String getResourcePath() {
12092            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12093        }
12094
12095        private boolean cleanUp(String volumeUuid) {
12096            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12097                    move.dataAppName);
12098            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12099            synchronized (mInstallLock) {
12100                // Clean up both app data and code
12101                removeDataDirsLI(volumeUuid, move.packageName);
12102                removeCodePathLI(codeFile);
12103            }
12104            return true;
12105        }
12106
12107        void cleanUpResourcesLI() {
12108            throw new UnsupportedOperationException();
12109        }
12110
12111        boolean doPostDeleteLI(boolean delete) {
12112            throw new UnsupportedOperationException();
12113        }
12114    }
12115
12116    static String getAsecPackageName(String packageCid) {
12117        int idx = packageCid.lastIndexOf("-");
12118        if (idx == -1) {
12119            return packageCid;
12120        }
12121        return packageCid.substring(0, idx);
12122    }
12123
12124    // Utility method used to create code paths based on package name and available index.
12125    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12126        String idxStr = "";
12127        int idx = 1;
12128        // Fall back to default value of idx=1 if prefix is not
12129        // part of oldCodePath
12130        if (oldCodePath != null) {
12131            String subStr = oldCodePath;
12132            // Drop the suffix right away
12133            if (suffix != null && subStr.endsWith(suffix)) {
12134                subStr = subStr.substring(0, subStr.length() - suffix.length());
12135            }
12136            // If oldCodePath already contains prefix find out the
12137            // ending index to either increment or decrement.
12138            int sidx = subStr.lastIndexOf(prefix);
12139            if (sidx != -1) {
12140                subStr = subStr.substring(sidx + prefix.length());
12141                if (subStr != null) {
12142                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12143                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12144                    }
12145                    try {
12146                        idx = Integer.parseInt(subStr);
12147                        if (idx <= 1) {
12148                            idx++;
12149                        } else {
12150                            idx--;
12151                        }
12152                    } catch(NumberFormatException e) {
12153                    }
12154                }
12155            }
12156        }
12157        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12158        return prefix + idxStr;
12159    }
12160
12161    private File getNextCodePath(File targetDir, String packageName) {
12162        int suffix = 1;
12163        File result;
12164        do {
12165            result = new File(targetDir, packageName + "-" + suffix);
12166            suffix++;
12167        } while (result.exists());
12168        return result;
12169    }
12170
12171    // Utility method that returns the relative package path with respect
12172    // to the installation directory. Like say for /data/data/com.test-1.apk
12173    // string com.test-1 is returned.
12174    static String deriveCodePathName(String codePath) {
12175        if (codePath == null) {
12176            return null;
12177        }
12178        final File codeFile = new File(codePath);
12179        final String name = codeFile.getName();
12180        if (codeFile.isDirectory()) {
12181            return name;
12182        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12183            final int lastDot = name.lastIndexOf('.');
12184            return name.substring(0, lastDot);
12185        } else {
12186            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12187            return null;
12188        }
12189    }
12190
12191    static class PackageInstalledInfo {
12192        String name;
12193        int uid;
12194        // The set of users that originally had this package installed.
12195        int[] origUsers;
12196        // The set of users that now have this package installed.
12197        int[] newUsers;
12198        PackageParser.Package pkg;
12199        int returnCode;
12200        String returnMsg;
12201        PackageRemovedInfo removedInfo;
12202
12203        public void setError(int code, String msg) {
12204            returnCode = code;
12205            returnMsg = msg;
12206            Slog.w(TAG, msg);
12207        }
12208
12209        public void setError(String msg, PackageParserException e) {
12210            returnCode = e.error;
12211            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12212            Slog.w(TAG, msg, e);
12213        }
12214
12215        public void setError(String msg, PackageManagerException e) {
12216            returnCode = e.error;
12217            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12218            Slog.w(TAG, msg, e);
12219        }
12220
12221        // In some error cases we want to convey more info back to the observer
12222        String origPackage;
12223        String origPermission;
12224    }
12225
12226    /*
12227     * Install a non-existing package.
12228     */
12229    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12230            UserHandle user, String installerPackageName, String volumeUuid,
12231            PackageInstalledInfo res) {
12232        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12233
12234        // Remember this for later, in case we need to rollback this install
12235        String pkgName = pkg.packageName;
12236
12237        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12238        // TODO: b/23350563
12239        final boolean dataDirExists = Environment
12240                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12241
12242        synchronized(mPackages) {
12243            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12244                // A package with the same name is already installed, though
12245                // it has been renamed to an older name.  The package we
12246                // are trying to install should be installed as an update to
12247                // the existing one, but that has not been requested, so bail.
12248                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12249                        + " without first uninstalling package running as "
12250                        + mSettings.mRenamedPackages.get(pkgName));
12251                return;
12252            }
12253            if (mPackages.containsKey(pkgName)) {
12254                // Don't allow installation over an existing package with the same name.
12255                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12256                        + " without first uninstalling.");
12257                return;
12258            }
12259        }
12260
12261        try {
12262            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12263                    System.currentTimeMillis(), user);
12264
12265            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12266            prepareAppDataAfterInstall(newPackage);
12267
12268            // delete the partially installed application. the data directory will have to be
12269            // restored if it was already existing
12270            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12271                // remove package from internal structures.  Note that we want deletePackageX to
12272                // delete the package data and cache directories that it created in
12273                // scanPackageLocked, unless those directories existed before we even tried to
12274                // install.
12275                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12276                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12277                                res.removedInfo, true);
12278            }
12279
12280        } catch (PackageManagerException e) {
12281            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12282        }
12283
12284        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12285    }
12286
12287    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12288        // Can't rotate keys during boot or if sharedUser.
12289        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12290                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12291            return false;
12292        }
12293        // app is using upgradeKeySets; make sure all are valid
12294        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12295        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12296        for (int i = 0; i < upgradeKeySets.length; i++) {
12297            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12298                Slog.wtf(TAG, "Package "
12299                         + (oldPs.name != null ? oldPs.name : "<null>")
12300                         + " contains upgrade-key-set reference to unknown key-set: "
12301                         + upgradeKeySets[i]
12302                         + " reverting to signatures check.");
12303                return false;
12304            }
12305        }
12306        return true;
12307    }
12308
12309    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12310        // Upgrade keysets are being used.  Determine if new package has a superset of the
12311        // required keys.
12312        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12313        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12314        for (int i = 0; i < upgradeKeySets.length; i++) {
12315            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12316            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12317                return true;
12318            }
12319        }
12320        return false;
12321    }
12322
12323    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12324            UserHandle user, String installerPackageName, String volumeUuid,
12325            PackageInstalledInfo res) {
12326        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12327
12328        final PackageParser.Package oldPackage;
12329        final String pkgName = pkg.packageName;
12330        final int[] allUsers;
12331        final boolean[] perUserInstalled;
12332
12333        // First find the old package info and check signatures
12334        synchronized(mPackages) {
12335            oldPackage = mPackages.get(pkgName);
12336            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12337            if (isEphemeral && !oldIsEphemeral) {
12338                // can't downgrade from full to ephemeral
12339                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12340                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12341                return;
12342            }
12343            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12344            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12345            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12346                if(!checkUpgradeKeySetLP(ps, pkg)) {
12347                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12348                            "New package not signed by keys specified by upgrade-keysets: "
12349                            + pkgName);
12350                    return;
12351                }
12352            } else {
12353                // default to original signature matching
12354                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12355                    != PackageManager.SIGNATURE_MATCH) {
12356                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12357                            "New package has a different signature: " + pkgName);
12358                    return;
12359                }
12360            }
12361
12362            // In case of rollback, remember per-user/profile install state
12363            allUsers = sUserManager.getUserIds();
12364            perUserInstalled = new boolean[allUsers.length];
12365            for (int i = 0; i < allUsers.length; i++) {
12366                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12367            }
12368        }
12369
12370        boolean sysPkg = (isSystemApp(oldPackage));
12371        if (sysPkg) {
12372            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12373                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12374        } else {
12375            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12376                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12377        }
12378    }
12379
12380    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12381            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12382            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12383            String volumeUuid, PackageInstalledInfo res) {
12384        String pkgName = deletedPackage.packageName;
12385        boolean deletedPkg = true;
12386        boolean updatedSettings = false;
12387
12388        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12389                + deletedPackage);
12390        long origUpdateTime;
12391        if (pkg.mExtras != null) {
12392            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12393        } else {
12394            origUpdateTime = 0;
12395        }
12396
12397        // First delete the existing package while retaining the data directory
12398        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12399                res.removedInfo, true)) {
12400            // If the existing package wasn't successfully deleted
12401            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12402            deletedPkg = false;
12403        } else {
12404            // Successfully deleted the old package; proceed with replace.
12405
12406            // If deleted package lived in a container, give users a chance to
12407            // relinquish resources before killing.
12408            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12409                if (DEBUG_INSTALL) {
12410                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12411                }
12412                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12413                final ArrayList<String> pkgList = new ArrayList<String>(1);
12414                pkgList.add(deletedPackage.applicationInfo.packageName);
12415                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12416            }
12417
12418            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12419            try {
12420                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12421                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12422                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12423                        perUserInstalled, res, user);
12424                prepareAppDataAfterInstall(newPackage);
12425                updatedSettings = true;
12426            } catch (PackageManagerException e) {
12427                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12428            }
12429        }
12430
12431        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12432            // remove package from internal structures.  Note that we want deletePackageX to
12433            // delete the package data and cache directories that it created in
12434            // scanPackageLocked, unless those directories existed before we even tried to
12435            // install.
12436            if(updatedSettings) {
12437                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12438                deletePackageLI(
12439                        pkgName, null, true, allUsers, perUserInstalled,
12440                        PackageManager.DELETE_KEEP_DATA,
12441                                res.removedInfo, true);
12442            }
12443            // Since we failed to install the new package we need to restore the old
12444            // package that we deleted.
12445            if (deletedPkg) {
12446                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12447                File restoreFile = new File(deletedPackage.codePath);
12448                // Parse old package
12449                boolean oldExternal = isExternal(deletedPackage);
12450                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12451                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12452                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12453                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12454                try {
12455                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12456                            null);
12457                } catch (PackageManagerException e) {
12458                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12459                            + e.getMessage());
12460                    return;
12461                }
12462                // Restore of old package succeeded. Update permissions.
12463                // writer
12464                synchronized (mPackages) {
12465                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12466                            UPDATE_PERMISSIONS_ALL);
12467                    // can downgrade to reader
12468                    mSettings.writeLPr();
12469                }
12470                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12471            }
12472        }
12473    }
12474
12475    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12476            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12477            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12478            String volumeUuid, PackageInstalledInfo res) {
12479        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12480                + ", old=" + deletedPackage);
12481        boolean disabledSystem = false;
12482        boolean updatedSettings = false;
12483        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12484        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12485                != 0) {
12486            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12487        }
12488        String packageName = deletedPackage.packageName;
12489        if (packageName == null) {
12490            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12491                    "Attempt to delete null packageName.");
12492            return;
12493        }
12494        PackageParser.Package oldPkg;
12495        PackageSetting oldPkgSetting;
12496        // reader
12497        synchronized (mPackages) {
12498            oldPkg = mPackages.get(packageName);
12499            oldPkgSetting = mSettings.mPackages.get(packageName);
12500            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12501                    (oldPkgSetting == null)) {
12502                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12503                        "Couldn't find package " + packageName + " information");
12504                return;
12505            }
12506        }
12507
12508        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12509
12510        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12511        res.removedInfo.removedPackage = packageName;
12512        // Remove existing system package
12513        removePackageLI(oldPkgSetting, true);
12514        // writer
12515        synchronized (mPackages) {
12516            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12517            if (!disabledSystem && deletedPackage != null) {
12518                // We didn't need to disable the .apk as a current system package,
12519                // which means we are replacing another update that is already
12520                // installed.  We need to make sure to delete the older one's .apk.
12521                res.removedInfo.args = createInstallArgsForExisting(0,
12522                        deletedPackage.applicationInfo.getCodePath(),
12523                        deletedPackage.applicationInfo.getResourcePath(),
12524                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12525            } else {
12526                res.removedInfo.args = null;
12527            }
12528        }
12529
12530        // Successfully disabled the old package. Now proceed with re-installation
12531        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12532
12533        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12534        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12535
12536        PackageParser.Package newPackage = null;
12537        try {
12538            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12539            if (newPackage.mExtras != null) {
12540                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12541                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12542                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12543
12544                // is the update attempting to change shared user? that isn't going to work...
12545                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12546                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12547                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12548                            + " to " + newPkgSetting.sharedUser);
12549                    updatedSettings = true;
12550                }
12551            }
12552
12553            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12554                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12555                        perUserInstalled, res, user);
12556                prepareAppDataAfterInstall(newPackage);
12557                updatedSettings = true;
12558            }
12559
12560        } catch (PackageManagerException e) {
12561            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12562        }
12563
12564        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12565            // Re installation failed. Restore old information
12566            // Remove new pkg information
12567            if (newPackage != null) {
12568                removeInstalledPackageLI(newPackage, true);
12569            }
12570            // Add back the old system package
12571            try {
12572                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12573            } catch (PackageManagerException e) {
12574                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12575            }
12576            // Restore the old system information in Settings
12577            synchronized (mPackages) {
12578                if (disabledSystem) {
12579                    mSettings.enableSystemPackageLPw(packageName);
12580                }
12581                if (updatedSettings) {
12582                    mSettings.setInstallerPackageName(packageName,
12583                            oldPkgSetting.installerPackageName);
12584                }
12585                mSettings.writeLPr();
12586            }
12587        }
12588    }
12589
12590    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12591        // Collect all used permissions in the UID
12592        ArraySet<String> usedPermissions = new ArraySet<>();
12593        final int packageCount = su.packages.size();
12594        for (int i = 0; i < packageCount; i++) {
12595            PackageSetting ps = su.packages.valueAt(i);
12596            if (ps.pkg == null) {
12597                continue;
12598            }
12599            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12600            for (int j = 0; j < requestedPermCount; j++) {
12601                String permission = ps.pkg.requestedPermissions.get(j);
12602                BasePermission bp = mSettings.mPermissions.get(permission);
12603                if (bp != null) {
12604                    usedPermissions.add(permission);
12605                }
12606            }
12607        }
12608
12609        PermissionsState permissionsState = su.getPermissionsState();
12610        // Prune install permissions
12611        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12612        final int installPermCount = installPermStates.size();
12613        for (int i = installPermCount - 1; i >= 0;  i--) {
12614            PermissionState permissionState = installPermStates.get(i);
12615            if (!usedPermissions.contains(permissionState.getName())) {
12616                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12617                if (bp != null) {
12618                    permissionsState.revokeInstallPermission(bp);
12619                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12620                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12621                }
12622            }
12623        }
12624
12625        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12626
12627        // Prune runtime permissions
12628        for (int userId : allUserIds) {
12629            List<PermissionState> runtimePermStates = permissionsState
12630                    .getRuntimePermissionStates(userId);
12631            final int runtimePermCount = runtimePermStates.size();
12632            for (int i = runtimePermCount - 1; i >= 0; i--) {
12633                PermissionState permissionState = runtimePermStates.get(i);
12634                if (!usedPermissions.contains(permissionState.getName())) {
12635                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12636                    if (bp != null) {
12637                        permissionsState.revokeRuntimePermission(bp, userId);
12638                        permissionsState.updatePermissionFlags(bp, userId,
12639                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12640                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12641                                runtimePermissionChangedUserIds, userId);
12642                    }
12643                }
12644            }
12645        }
12646
12647        return runtimePermissionChangedUserIds;
12648    }
12649
12650    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12651            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12652            UserHandle user) {
12653        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12654
12655        String pkgName = newPackage.packageName;
12656        synchronized (mPackages) {
12657            //write settings. the installStatus will be incomplete at this stage.
12658            //note that the new package setting would have already been
12659            //added to mPackages. It hasn't been persisted yet.
12660            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12661            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12662            mSettings.writeLPr();
12663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12664        }
12665
12666        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12667        synchronized (mPackages) {
12668            updatePermissionsLPw(newPackage.packageName, newPackage,
12669                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12670                            ? UPDATE_PERMISSIONS_ALL : 0));
12671            // For system-bundled packages, we assume that installing an upgraded version
12672            // of the package implies that the user actually wants to run that new code,
12673            // so we enable the package.
12674            PackageSetting ps = mSettings.mPackages.get(pkgName);
12675            if (ps != null) {
12676                if (isSystemApp(newPackage)) {
12677                    // NB: implicit assumption that system package upgrades apply to all users
12678                    if (DEBUG_INSTALL) {
12679                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12680                    }
12681                    if (res.origUsers != null) {
12682                        for (int userHandle : res.origUsers) {
12683                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12684                                    userHandle, installerPackageName);
12685                        }
12686                    }
12687                    // Also convey the prior install/uninstall state
12688                    if (allUsers != null && perUserInstalled != null) {
12689                        for (int i = 0; i < allUsers.length; i++) {
12690                            if (DEBUG_INSTALL) {
12691                                Slog.d(TAG, "    user " + allUsers[i]
12692                                        + " => " + perUserInstalled[i]);
12693                            }
12694                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12695                        }
12696                        // these install state changes will be persisted in the
12697                        // upcoming call to mSettings.writeLPr().
12698                    }
12699                }
12700                // It's implied that when a user requests installation, they want the app to be
12701                // installed and enabled.
12702                int userId = user.getIdentifier();
12703                if (userId != UserHandle.USER_ALL) {
12704                    ps.setInstalled(true, userId);
12705                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12706                }
12707            }
12708            res.name = pkgName;
12709            res.uid = newPackage.applicationInfo.uid;
12710            res.pkg = newPackage;
12711            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12712            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12713            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12714            //to update install status
12715            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12716            mSettings.writeLPr();
12717            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12718        }
12719
12720        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12721    }
12722
12723    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12724        try {
12725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12726            installPackageLI(args, res);
12727        } finally {
12728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12729        }
12730    }
12731
12732    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12733        final int installFlags = args.installFlags;
12734        final String installerPackageName = args.installerPackageName;
12735        final String volumeUuid = args.volumeUuid;
12736        final File tmpPackageFile = new File(args.getCodePath());
12737        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12738        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12739                || (args.volumeUuid != null));
12740        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12741        boolean replace = false;
12742        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12743        if (args.move != null) {
12744            // moving a complete application; perfom an initial scan on the new install location
12745            scanFlags |= SCAN_INITIAL;
12746        }
12747        // Result object to be returned
12748        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12749
12750        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12751
12752        // Sanity check
12753        if (ephemeral && (forwardLocked || onExternal)) {
12754            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12755                    + " external=" + onExternal);
12756            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12757            return;
12758        }
12759
12760        // Retrieve PackageSettings and parse package
12761        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12762                | PackageParser.PARSE_ENFORCE_CODE
12763                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12764                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12765                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12766        PackageParser pp = new PackageParser();
12767        pp.setSeparateProcesses(mSeparateProcesses);
12768        pp.setDisplayMetrics(mMetrics);
12769
12770        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12771        final PackageParser.Package pkg;
12772        try {
12773            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12774        } catch (PackageParserException e) {
12775            res.setError("Failed parse during installPackageLI", e);
12776            return;
12777        } finally {
12778            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12779        }
12780
12781        // Mark that we have an install time CPU ABI override.
12782        pkg.cpuAbiOverride = args.abiOverride;
12783
12784        String pkgName = res.name = pkg.packageName;
12785        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12786            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12787                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12788                return;
12789            }
12790        }
12791
12792        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12793        try {
12794            pp.collectCertificates(pkg, parseFlags);
12795        } catch (PackageParserException e) {
12796            res.setError("Failed collect during installPackageLI", e);
12797            return;
12798        } finally {
12799            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12800        }
12801
12802        // Get rid of all references to package scan path via parser.
12803        pp = null;
12804        String oldCodePath = null;
12805        boolean systemApp = false;
12806        synchronized (mPackages) {
12807            // Check if installing already existing package
12808            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12809                String oldName = mSettings.mRenamedPackages.get(pkgName);
12810                if (pkg.mOriginalPackages != null
12811                        && pkg.mOriginalPackages.contains(oldName)
12812                        && mPackages.containsKey(oldName)) {
12813                    // This package is derived from an original package,
12814                    // and this device has been updating from that original
12815                    // name.  We must continue using the original name, so
12816                    // rename the new package here.
12817                    pkg.setPackageName(oldName);
12818                    pkgName = pkg.packageName;
12819                    replace = true;
12820                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12821                            + oldName + " pkgName=" + pkgName);
12822                } else if (mPackages.containsKey(pkgName)) {
12823                    // This package, under its official name, already exists
12824                    // on the device; we should replace it.
12825                    replace = true;
12826                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12827                }
12828
12829                // Prevent apps opting out from runtime permissions
12830                if (replace) {
12831                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12832                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12833                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12834                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12835                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12836                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12837                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12838                                        + " doesn't support runtime permissions but the old"
12839                                        + " target SDK " + oldTargetSdk + " does.");
12840                        return;
12841                    }
12842                }
12843            }
12844
12845            PackageSetting ps = mSettings.mPackages.get(pkgName);
12846            if (ps != null) {
12847                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12848
12849                // Quick sanity check that we're signed correctly if updating;
12850                // we'll check this again later when scanning, but we want to
12851                // bail early here before tripping over redefined permissions.
12852                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12853                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12854                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12855                                + pkg.packageName + " upgrade keys do not match the "
12856                                + "previously installed version");
12857                        return;
12858                    }
12859                } else {
12860                    try {
12861                        verifySignaturesLP(ps, pkg);
12862                    } catch (PackageManagerException e) {
12863                        res.setError(e.error, e.getMessage());
12864                        return;
12865                    }
12866                }
12867
12868                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12869                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12870                    systemApp = (ps.pkg.applicationInfo.flags &
12871                            ApplicationInfo.FLAG_SYSTEM) != 0;
12872                }
12873                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12874            }
12875
12876            // Check whether the newly-scanned package wants to define an already-defined perm
12877            int N = pkg.permissions.size();
12878            for (int i = N-1; i >= 0; i--) {
12879                PackageParser.Permission perm = pkg.permissions.get(i);
12880                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12881                if (bp != null) {
12882                    // If the defining package is signed with our cert, it's okay.  This
12883                    // also includes the "updating the same package" case, of course.
12884                    // "updating same package" could also involve key-rotation.
12885                    final boolean sigsOk;
12886                    if (bp.sourcePackage.equals(pkg.packageName)
12887                            && (bp.packageSetting instanceof PackageSetting)
12888                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12889                                    scanFlags))) {
12890                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12891                    } else {
12892                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12893                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12894                    }
12895                    if (!sigsOk) {
12896                        // If the owning package is the system itself, we log but allow
12897                        // install to proceed; we fail the install on all other permission
12898                        // redefinitions.
12899                        if (!bp.sourcePackage.equals("android")) {
12900                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12901                                    + pkg.packageName + " attempting to redeclare permission "
12902                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12903                            res.origPermission = perm.info.name;
12904                            res.origPackage = bp.sourcePackage;
12905                            return;
12906                        } else {
12907                            Slog.w(TAG, "Package " + pkg.packageName
12908                                    + " attempting to redeclare system permission "
12909                                    + perm.info.name + "; ignoring new declaration");
12910                            pkg.permissions.remove(i);
12911                        }
12912                    }
12913                }
12914            }
12915
12916        }
12917
12918        if (systemApp) {
12919            if (onExternal) {
12920                // Abort update; system app can't be replaced with app on sdcard
12921                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12922                        "Cannot install updates to system apps on sdcard");
12923                return;
12924            } else if (ephemeral) {
12925                // Abort update; system app can't be replaced with an ephemeral app
12926                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12927                        "Cannot update a system app with an ephemeral app");
12928                return;
12929            }
12930        }
12931
12932        if (args.move != null) {
12933            // We did an in-place move, so dex is ready to roll
12934            scanFlags |= SCAN_NO_DEX;
12935            scanFlags |= SCAN_MOVE;
12936
12937            synchronized (mPackages) {
12938                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12939                if (ps == null) {
12940                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12941                            "Missing settings for moved package " + pkgName);
12942                }
12943
12944                // We moved the entire application as-is, so bring over the
12945                // previously derived ABI information.
12946                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12947                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12948            }
12949
12950        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12951            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12952            scanFlags |= SCAN_NO_DEX;
12953
12954            try {
12955                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12956                        true /* extract libs */);
12957            } catch (PackageManagerException pme) {
12958                Slog.e(TAG, "Error deriving application ABI", pme);
12959                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12960                return;
12961            }
12962        }
12963
12964        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12965            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12966            return;
12967        }
12968
12969        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12970
12971        if (replace) {
12972            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12973                    installerPackageName, volumeUuid, res);
12974        } else {
12975            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12976                    args.user, installerPackageName, volumeUuid, res);
12977        }
12978        synchronized (mPackages) {
12979            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12980            if (ps != null) {
12981                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12982            }
12983        }
12984    }
12985
12986    private void startIntentFilterVerifications(int userId, boolean replacing,
12987            PackageParser.Package pkg) {
12988        if (mIntentFilterVerifierComponent == null) {
12989            Slog.w(TAG, "No IntentFilter verification will not be done as "
12990                    + "there is no IntentFilterVerifier available!");
12991            return;
12992        }
12993
12994        final int verifierUid = getPackageUid(
12995                mIntentFilterVerifierComponent.getPackageName(),
12996                MATCH_DEBUG_TRIAGED_MISSING,
12997                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12998
12999        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13000        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13001        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13002        mHandler.sendMessage(msg);
13003    }
13004
13005    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13006            PackageParser.Package pkg) {
13007        int size = pkg.activities.size();
13008        if (size == 0) {
13009            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13010                    "No activity, so no need to verify any IntentFilter!");
13011            return;
13012        }
13013
13014        final boolean hasDomainURLs = hasDomainURLs(pkg);
13015        if (!hasDomainURLs) {
13016            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13017                    "No domain URLs, so no need to verify any IntentFilter!");
13018            return;
13019        }
13020
13021        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13022                + " if any IntentFilter from the " + size
13023                + " Activities needs verification ...");
13024
13025        int count = 0;
13026        final String packageName = pkg.packageName;
13027
13028        synchronized (mPackages) {
13029            // If this is a new install and we see that we've already run verification for this
13030            // package, we have nothing to do: it means the state was restored from backup.
13031            if (!replacing) {
13032                IntentFilterVerificationInfo ivi =
13033                        mSettings.getIntentFilterVerificationLPr(packageName);
13034                if (ivi != null) {
13035                    if (DEBUG_DOMAIN_VERIFICATION) {
13036                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13037                                + ivi.getStatusString());
13038                    }
13039                    return;
13040                }
13041            }
13042
13043            // If any filters need to be verified, then all need to be.
13044            boolean needToVerify = false;
13045            for (PackageParser.Activity a : pkg.activities) {
13046                for (ActivityIntentInfo filter : a.intents) {
13047                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13048                        if (DEBUG_DOMAIN_VERIFICATION) {
13049                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13050                        }
13051                        needToVerify = true;
13052                        break;
13053                    }
13054                }
13055            }
13056
13057            if (needToVerify) {
13058                final int verificationId = mIntentFilterVerificationToken++;
13059                for (PackageParser.Activity a : pkg.activities) {
13060                    for (ActivityIntentInfo filter : a.intents) {
13061                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13062                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13063                                    "Verification needed for IntentFilter:" + filter.toString());
13064                            mIntentFilterVerifier.addOneIntentFilterVerification(
13065                                    verifierUid, userId, verificationId, filter, packageName);
13066                            count++;
13067                        }
13068                    }
13069                }
13070            }
13071        }
13072
13073        if (count > 0) {
13074            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13075                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13076                    +  " for userId:" + userId);
13077            mIntentFilterVerifier.startVerifications(userId);
13078        } else {
13079            if (DEBUG_DOMAIN_VERIFICATION) {
13080                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13081            }
13082        }
13083    }
13084
13085    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13086        final ComponentName cn  = filter.activity.getComponentName();
13087        final String packageName = cn.getPackageName();
13088
13089        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13090                packageName);
13091        if (ivi == null) {
13092            return true;
13093        }
13094        int status = ivi.getStatus();
13095        switch (status) {
13096            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13097            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13098                return true;
13099
13100            default:
13101                // Nothing to do
13102                return false;
13103        }
13104    }
13105
13106    private static boolean isMultiArch(ApplicationInfo info) {
13107        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13108    }
13109
13110    private static boolean isExternal(PackageParser.Package pkg) {
13111        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13112    }
13113
13114    private static boolean isExternal(PackageSetting ps) {
13115        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13116    }
13117
13118    private static boolean isEphemeral(PackageParser.Package pkg) {
13119        return pkg.applicationInfo.isEphemeralApp();
13120    }
13121
13122    private static boolean isEphemeral(PackageSetting ps) {
13123        return ps.pkg != null && isEphemeral(ps.pkg);
13124    }
13125
13126    private static boolean isSystemApp(PackageParser.Package pkg) {
13127        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13128    }
13129
13130    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13131        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13132    }
13133
13134    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13135        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13136    }
13137
13138    private static boolean isSystemApp(PackageSetting ps) {
13139        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13140    }
13141
13142    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13143        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13144    }
13145
13146    private int packageFlagsToInstallFlags(PackageSetting ps) {
13147        int installFlags = 0;
13148        if (isEphemeral(ps)) {
13149            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13150        }
13151        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13152            // This existing package was an external ASEC install when we have
13153            // the external flag without a UUID
13154            installFlags |= PackageManager.INSTALL_EXTERNAL;
13155        }
13156        if (ps.isForwardLocked()) {
13157            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13158        }
13159        return installFlags;
13160    }
13161
13162    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13163        if (isExternal(pkg)) {
13164            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13165                return StorageManager.UUID_PRIMARY_PHYSICAL;
13166            } else {
13167                return pkg.volumeUuid;
13168            }
13169        } else {
13170            return StorageManager.UUID_PRIVATE_INTERNAL;
13171        }
13172    }
13173
13174    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13175        if (isExternal(pkg)) {
13176            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13177                return mSettings.getExternalVersion();
13178            } else {
13179                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13180            }
13181        } else {
13182            return mSettings.getInternalVersion();
13183        }
13184    }
13185
13186    private void deleteTempPackageFiles() {
13187        final FilenameFilter filter = new FilenameFilter() {
13188            public boolean accept(File dir, String name) {
13189                return name.startsWith("vmdl") && name.endsWith(".tmp");
13190            }
13191        };
13192        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13193            file.delete();
13194        }
13195    }
13196
13197    @Override
13198    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13199            int flags) {
13200        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13201                flags);
13202    }
13203
13204    @Override
13205    public void deletePackage(final String packageName,
13206            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13207        mContext.enforceCallingOrSelfPermission(
13208                android.Manifest.permission.DELETE_PACKAGES, null);
13209        Preconditions.checkNotNull(packageName);
13210        Preconditions.checkNotNull(observer);
13211        final int uid = Binder.getCallingUid();
13212        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13213        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13214        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13215            mContext.enforceCallingOrSelfPermission(
13216                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13217                    "deletePackage for user " + userId);
13218        }
13219
13220        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13221            try {
13222                observer.onPackageDeleted(packageName,
13223                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13224            } catch (RemoteException re) {
13225            }
13226            return;
13227        }
13228
13229        for (int currentUserId : users) {
13230            if (getBlockUninstallForUser(packageName, currentUserId)) {
13231                try {
13232                    observer.onPackageDeleted(packageName,
13233                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13234                } catch (RemoteException re) {
13235                }
13236                return;
13237            }
13238        }
13239
13240        if (DEBUG_REMOVE) {
13241            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13242        }
13243        // Queue up an async operation since the package deletion may take a little while.
13244        mHandler.post(new Runnable() {
13245            public void run() {
13246                mHandler.removeCallbacks(this);
13247                final int returnCode = deletePackageX(packageName, userId, flags);
13248                try {
13249                    observer.onPackageDeleted(packageName, returnCode, null);
13250                } catch (RemoteException e) {
13251                    Log.i(TAG, "Observer no longer exists.");
13252                } //end catch
13253            } //end run
13254        });
13255    }
13256
13257    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13258        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13259                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13260        try {
13261            if (dpm != null) {
13262                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13263                        /* callingUserOnly =*/ false);
13264                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13265                        : deviceOwnerComponentName.getPackageName();
13266                // Does the package contains the device owner?
13267                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13268                // this check is probably not needed, since DO should be registered as a device
13269                // admin on some user too. (Original bug for this: b/17657954)
13270                if (packageName.equals(deviceOwnerPackageName)) {
13271                    return true;
13272                }
13273                // Does it contain a device admin for any user?
13274                int[] users;
13275                if (userId == UserHandle.USER_ALL) {
13276                    users = sUserManager.getUserIds();
13277                } else {
13278                    users = new int[]{userId};
13279                }
13280                for (int i = 0; i < users.length; ++i) {
13281                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13282                        return true;
13283                    }
13284                }
13285            }
13286        } catch (RemoteException e) {
13287        }
13288        return false;
13289    }
13290
13291    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13292        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13293    }
13294
13295    /**
13296     *  This method is an internal method that could be get invoked either
13297     *  to delete an installed package or to clean up a failed installation.
13298     *  After deleting an installed package, a broadcast is sent to notify any
13299     *  listeners that the package has been installed. For cleaning up a failed
13300     *  installation, the broadcast is not necessary since the package's
13301     *  installation wouldn't have sent the initial broadcast either
13302     *  The key steps in deleting a package are
13303     *  deleting the package information in internal structures like mPackages,
13304     *  deleting the packages base directories through installd
13305     *  updating mSettings to reflect current status
13306     *  persisting settings for later use
13307     *  sending a broadcast if necessary
13308     */
13309    private int deletePackageX(String packageName, int userId, int flags) {
13310        final PackageRemovedInfo info = new PackageRemovedInfo();
13311        final boolean res;
13312
13313        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13314                ? UserHandle.ALL : new UserHandle(userId);
13315
13316        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13317            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13318            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13319        }
13320
13321        boolean removedForAllUsers = false;
13322        boolean systemUpdate = false;
13323
13324        PackageParser.Package uninstalledPkg;
13325
13326        // for the uninstall-updates case and restricted profiles, remember the per-
13327        // userhandle installed state
13328        int[] allUsers;
13329        boolean[] perUserInstalled;
13330        synchronized (mPackages) {
13331            uninstalledPkg = mPackages.get(packageName);
13332            PackageSetting ps = mSettings.mPackages.get(packageName);
13333            allUsers = sUserManager.getUserIds();
13334            perUserInstalled = new boolean[allUsers.length];
13335            for (int i = 0; i < allUsers.length; i++) {
13336                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13337            }
13338        }
13339
13340        synchronized (mInstallLock) {
13341            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13342            res = deletePackageLI(packageName, removeForUser,
13343                    true, allUsers, perUserInstalled,
13344                    flags | REMOVE_CHATTY, info, true);
13345            systemUpdate = info.isRemovedPackageSystemUpdate;
13346            synchronized (mPackages) {
13347                if (res) {
13348                    if (!systemUpdate && mPackages.get(packageName) == null) {
13349                        removedForAllUsers = true;
13350                    }
13351                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13352                }
13353            }
13354            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13355                    + " removedForAllUsers=" + removedForAllUsers);
13356        }
13357
13358        if (res) {
13359            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13360
13361            // If the removed package was a system update, the old system package
13362            // was re-enabled; we need to broadcast this information
13363            if (systemUpdate) {
13364                Bundle extras = new Bundle(1);
13365                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13366                        ? info.removedAppId : info.uid);
13367                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13368
13369                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13370                        extras, 0, null, null, null);
13371                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13372                        extras, 0, null, null, null);
13373                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13374                        null, 0, packageName, null, null);
13375            }
13376        }
13377        // Force a gc here.
13378        Runtime.getRuntime().gc();
13379        // Delete the resources here after sending the broadcast to let
13380        // other processes clean up before deleting resources.
13381        if (info.args != null) {
13382            synchronized (mInstallLock) {
13383                info.args.doPostDeleteLI(true);
13384            }
13385        }
13386
13387        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13388    }
13389
13390    class PackageRemovedInfo {
13391        String removedPackage;
13392        int uid = -1;
13393        int removedAppId = -1;
13394        int[] removedUsers = null;
13395        boolean isRemovedPackageSystemUpdate = false;
13396        // Clean up resources deleted packages.
13397        InstallArgs args = null;
13398
13399        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13400            Bundle extras = new Bundle(1);
13401            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13402            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13403            if (replacing) {
13404                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13405            }
13406            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13407            if (removedPackage != null) {
13408                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13409                        extras, 0, null, null, removedUsers);
13410                if (fullRemove && !replacing) {
13411                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13412                            extras, 0, null, null, removedUsers);
13413                }
13414            }
13415            if (removedAppId >= 0) {
13416                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13417                        removedUsers);
13418            }
13419        }
13420    }
13421
13422    /*
13423     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13424     * flag is not set, the data directory is removed as well.
13425     * make sure this flag is set for partially installed apps. If not its meaningless to
13426     * delete a partially installed application.
13427     */
13428    private void removePackageDataLI(PackageSetting ps,
13429            int[] allUserHandles, boolean[] perUserInstalled,
13430            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13431        String packageName = ps.name;
13432        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13433        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13434        // Retrieve object to delete permissions for shared user later on
13435        final PackageSetting deletedPs;
13436        // reader
13437        synchronized (mPackages) {
13438            deletedPs = mSettings.mPackages.get(packageName);
13439            if (outInfo != null) {
13440                outInfo.removedPackage = packageName;
13441                outInfo.removedUsers = deletedPs != null
13442                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13443                        : null;
13444            }
13445        }
13446        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13447            removeDataDirsLI(ps.volumeUuid, packageName);
13448            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13449        }
13450        // writer
13451        synchronized (mPackages) {
13452            if (deletedPs != null) {
13453                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13454                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13455                    clearDefaultBrowserIfNeeded(packageName);
13456                    if (outInfo != null) {
13457                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13458                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13459                    }
13460                    updatePermissionsLPw(deletedPs.name, null, 0);
13461                    if (deletedPs.sharedUser != null) {
13462                        // Remove permissions associated with package. Since runtime
13463                        // permissions are per user we have to kill the removed package
13464                        // or packages running under the shared user of the removed
13465                        // package if revoking the permissions requested only by the removed
13466                        // package is successful and this causes a change in gids.
13467                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13468                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13469                                    userId);
13470                            if (userIdToKill == UserHandle.USER_ALL
13471                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13472                                // If gids changed for this user, kill all affected packages.
13473                                mHandler.post(new Runnable() {
13474                                    @Override
13475                                    public void run() {
13476                                        // This has to happen with no lock held.
13477                                        killApplication(deletedPs.name, deletedPs.appId,
13478                                                KILL_APP_REASON_GIDS_CHANGED);
13479                                    }
13480                                });
13481                                break;
13482                            }
13483                        }
13484                    }
13485                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13486                }
13487                // make sure to preserve per-user disabled state if this removal was just
13488                // a downgrade of a system app to the factory package
13489                if (allUserHandles != null && perUserInstalled != null) {
13490                    if (DEBUG_REMOVE) {
13491                        Slog.d(TAG, "Propagating install state across downgrade");
13492                    }
13493                    for (int i = 0; i < allUserHandles.length; i++) {
13494                        if (DEBUG_REMOVE) {
13495                            Slog.d(TAG, "    user " + allUserHandles[i]
13496                                    + " => " + perUserInstalled[i]);
13497                        }
13498                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13499                    }
13500                }
13501            }
13502            // can downgrade to reader
13503            if (writeSettings) {
13504                // Save settings now
13505                mSettings.writeLPr();
13506            }
13507        }
13508        if (outInfo != null) {
13509            // A user ID was deleted here. Go through all users and remove it
13510            // from KeyStore.
13511            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13512        }
13513    }
13514
13515    static boolean locationIsPrivileged(File path) {
13516        try {
13517            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13518                    .getCanonicalPath();
13519            return path.getCanonicalPath().startsWith(privilegedAppDir);
13520        } catch (IOException e) {
13521            Slog.e(TAG, "Unable to access code path " + path);
13522        }
13523        return false;
13524    }
13525
13526    /*
13527     * Tries to delete system package.
13528     */
13529    private boolean deleteSystemPackageLI(PackageSetting newPs,
13530            int[] allUserHandles, boolean[] perUserInstalled,
13531            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13532        final boolean applyUserRestrictions
13533                = (allUserHandles != null) && (perUserInstalled != null);
13534        PackageSetting disabledPs = null;
13535        // Confirm if the system package has been updated
13536        // An updated system app can be deleted. This will also have to restore
13537        // the system pkg from system partition
13538        // reader
13539        synchronized (mPackages) {
13540            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13541        }
13542        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13543                + " disabledPs=" + disabledPs);
13544        if (disabledPs == null) {
13545            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13546            return false;
13547        } else if (DEBUG_REMOVE) {
13548            Slog.d(TAG, "Deleting system pkg from data partition");
13549        }
13550        if (DEBUG_REMOVE) {
13551            if (applyUserRestrictions) {
13552                Slog.d(TAG, "Remembering install states:");
13553                for (int i = 0; i < allUserHandles.length; i++) {
13554                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13555                }
13556            }
13557        }
13558        // Delete the updated package
13559        outInfo.isRemovedPackageSystemUpdate = true;
13560        if (disabledPs.versionCode < newPs.versionCode) {
13561            // Delete data for downgrades
13562            flags &= ~PackageManager.DELETE_KEEP_DATA;
13563        } else {
13564            // Preserve data by setting flag
13565            flags |= PackageManager.DELETE_KEEP_DATA;
13566        }
13567        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13568                allUserHandles, perUserInstalled, outInfo, writeSettings);
13569        if (!ret) {
13570            return false;
13571        }
13572        // writer
13573        synchronized (mPackages) {
13574            // Reinstate the old system package
13575            mSettings.enableSystemPackageLPw(newPs.name);
13576            // Remove any native libraries from the upgraded package.
13577            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13578        }
13579        // Install the system package
13580        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13581        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13582        if (locationIsPrivileged(disabledPs.codePath)) {
13583            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13584        }
13585
13586        final PackageParser.Package newPkg;
13587        try {
13588            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13589        } catch (PackageManagerException e) {
13590            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13591            return false;
13592        }
13593
13594        prepareAppDataAfterInstall(newPkg);
13595
13596        // writer
13597        synchronized (mPackages) {
13598            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13599
13600            // Propagate the permissions state as we do not want to drop on the floor
13601            // runtime permissions. The update permissions method below will take
13602            // care of removing obsolete permissions and grant install permissions.
13603            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13604            updatePermissionsLPw(newPkg.packageName, newPkg,
13605                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13606
13607            if (applyUserRestrictions) {
13608                if (DEBUG_REMOVE) {
13609                    Slog.d(TAG, "Propagating install state across reinstall");
13610                }
13611                for (int i = 0; i < allUserHandles.length; i++) {
13612                    if (DEBUG_REMOVE) {
13613                        Slog.d(TAG, "    user " + allUserHandles[i]
13614                                + " => " + perUserInstalled[i]);
13615                    }
13616                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13617
13618                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13619                }
13620                // Regardless of writeSettings we need to ensure that this restriction
13621                // state propagation is persisted
13622                mSettings.writeAllUsersPackageRestrictionsLPr();
13623            }
13624            // can downgrade to reader here
13625            if (writeSettings) {
13626                mSettings.writeLPr();
13627            }
13628        }
13629        return true;
13630    }
13631
13632    private boolean deleteInstalledPackageLI(PackageSetting ps,
13633            boolean deleteCodeAndResources, int flags,
13634            int[] allUserHandles, boolean[] perUserInstalled,
13635            PackageRemovedInfo outInfo, boolean writeSettings) {
13636        if (outInfo != null) {
13637            outInfo.uid = ps.appId;
13638        }
13639
13640        // Delete package data from internal structures and also remove data if flag is set
13641        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13642
13643        // Delete application code and resources
13644        if (deleteCodeAndResources && (outInfo != null)) {
13645            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13646                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13647            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13648        }
13649        return true;
13650    }
13651
13652    @Override
13653    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13654            int userId) {
13655        mContext.enforceCallingOrSelfPermission(
13656                android.Manifest.permission.DELETE_PACKAGES, null);
13657        synchronized (mPackages) {
13658            PackageSetting ps = mSettings.mPackages.get(packageName);
13659            if (ps == null) {
13660                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13661                return false;
13662            }
13663            if (!ps.getInstalled(userId)) {
13664                // Can't block uninstall for an app that is not installed or enabled.
13665                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13666                return false;
13667            }
13668            ps.setBlockUninstall(blockUninstall, userId);
13669            mSettings.writePackageRestrictionsLPr(userId);
13670        }
13671        return true;
13672    }
13673
13674    @Override
13675    public boolean getBlockUninstallForUser(String packageName, int userId) {
13676        synchronized (mPackages) {
13677            PackageSetting ps = mSettings.mPackages.get(packageName);
13678            if (ps == null) {
13679                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13680                return false;
13681            }
13682            return ps.getBlockUninstall(userId);
13683        }
13684    }
13685
13686    @Override
13687    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13688        int callingUid = Binder.getCallingUid();
13689        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13690            throw new SecurityException(
13691                    "setRequiredForSystemUser can only be run by the system or root");
13692        }
13693        synchronized (mPackages) {
13694            PackageSetting ps = mSettings.mPackages.get(packageName);
13695            if (ps == null) {
13696                Log.w(TAG, "Package doesn't exist: " + packageName);
13697                return false;
13698            }
13699            if (systemUserApp) {
13700                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13701            } else {
13702                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13703            }
13704            mSettings.writeLPr();
13705        }
13706        return true;
13707    }
13708
13709    /*
13710     * This method handles package deletion in general
13711     */
13712    private boolean deletePackageLI(String packageName, UserHandle user,
13713            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13714            int flags, PackageRemovedInfo outInfo,
13715            boolean writeSettings) {
13716        if (packageName == null) {
13717            Slog.w(TAG, "Attempt to delete null packageName.");
13718            return false;
13719        }
13720        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13721        PackageSetting ps;
13722        boolean dataOnly = false;
13723        int removeUser = -1;
13724        int appId = -1;
13725        synchronized (mPackages) {
13726            ps = mSettings.mPackages.get(packageName);
13727            if (ps == null) {
13728                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13729                return false;
13730            }
13731            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13732                    && user.getIdentifier() != UserHandle.USER_ALL) {
13733                // The caller is asking that the package only be deleted for a single
13734                // user.  To do this, we just mark its uninstalled state and delete
13735                // its data.  If this is a system app, we only allow this to happen if
13736                // they have set the special DELETE_SYSTEM_APP which requests different
13737                // semantics than normal for uninstalling system apps.
13738                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13739                final int userId = user.getIdentifier();
13740                ps.setUserState(userId,
13741                        COMPONENT_ENABLED_STATE_DEFAULT,
13742                        false, //installed
13743                        true,  //stopped
13744                        true,  //notLaunched
13745                        false, //hidden
13746                        false, //suspended
13747                        null, null, null,
13748                        false, // blockUninstall
13749                        ps.readUserState(userId).domainVerificationStatus, 0);
13750                if (!isSystemApp(ps)) {
13751                    // Do not uninstall the APK if an app should be cached
13752                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13753                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13754                        // Other user still have this package installed, so all
13755                        // we need to do is clear this user's data and save that
13756                        // it is uninstalled.
13757                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13758                        removeUser = user.getIdentifier();
13759                        appId = ps.appId;
13760                        scheduleWritePackageRestrictionsLocked(removeUser);
13761                    } else {
13762                        // We need to set it back to 'installed' so the uninstall
13763                        // broadcasts will be sent correctly.
13764                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13765                        ps.setInstalled(true, user.getIdentifier());
13766                    }
13767                } else {
13768                    // This is a system app, so we assume that the
13769                    // other users still have this package installed, so all
13770                    // we need to do is clear this user's data and save that
13771                    // it is uninstalled.
13772                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13773                    removeUser = user.getIdentifier();
13774                    appId = ps.appId;
13775                    scheduleWritePackageRestrictionsLocked(removeUser);
13776                }
13777            }
13778        }
13779
13780        if (removeUser >= 0) {
13781            // From above, we determined that we are deleting this only
13782            // for a single user.  Continue the work here.
13783            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13784            if (outInfo != null) {
13785                outInfo.removedPackage = packageName;
13786                outInfo.removedAppId = appId;
13787                outInfo.removedUsers = new int[] {removeUser};
13788            }
13789            // TODO: triage flags as part of 26466827
13790            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13791            try {
13792                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13793            } catch (InstallerException e) {
13794                Slog.w(TAG, "Failed to delete app data", e);
13795            }
13796            removeKeystoreDataIfNeeded(removeUser, appId);
13797            schedulePackageCleaning(packageName, removeUser, false);
13798            synchronized (mPackages) {
13799                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13800                    scheduleWritePackageRestrictionsLocked(removeUser);
13801                }
13802                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13803            }
13804            return true;
13805        }
13806
13807        if (dataOnly) {
13808            // Delete application data first
13809            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13810            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13811            return true;
13812        }
13813
13814        boolean ret = false;
13815        if (isSystemApp(ps)) {
13816            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13817            // When an updated system application is deleted we delete the existing resources as well and
13818            // fall back to existing code in system partition
13819            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13820                    flags, outInfo, writeSettings);
13821        } else {
13822            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13823            // Kill application pre-emptively especially for apps on sd.
13824            killApplication(packageName, ps.appId, "uninstall pkg");
13825            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13826                    allUserHandles, perUserInstalled,
13827                    outInfo, writeSettings);
13828        }
13829
13830        return ret;
13831    }
13832
13833    private final static class ClearStorageConnection implements ServiceConnection {
13834        IMediaContainerService mContainerService;
13835
13836        @Override
13837        public void onServiceConnected(ComponentName name, IBinder service) {
13838            synchronized (this) {
13839                mContainerService = IMediaContainerService.Stub.asInterface(service);
13840                notifyAll();
13841            }
13842        }
13843
13844        @Override
13845        public void onServiceDisconnected(ComponentName name) {
13846        }
13847    }
13848
13849    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13850        final boolean mounted;
13851        if (Environment.isExternalStorageEmulated()) {
13852            mounted = true;
13853        } else {
13854            final String status = Environment.getExternalStorageState();
13855
13856            mounted = status.equals(Environment.MEDIA_MOUNTED)
13857                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13858        }
13859
13860        if (!mounted) {
13861            return;
13862        }
13863
13864        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13865        int[] users;
13866        if (userId == UserHandle.USER_ALL) {
13867            users = sUserManager.getUserIds();
13868        } else {
13869            users = new int[] { userId };
13870        }
13871        final ClearStorageConnection conn = new ClearStorageConnection();
13872        if (mContext.bindServiceAsUser(
13873                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13874            try {
13875                for (int curUser : users) {
13876                    long timeout = SystemClock.uptimeMillis() + 5000;
13877                    synchronized (conn) {
13878                        long now = SystemClock.uptimeMillis();
13879                        while (conn.mContainerService == null && now < timeout) {
13880                            try {
13881                                conn.wait(timeout - now);
13882                            } catch (InterruptedException e) {
13883                            }
13884                        }
13885                    }
13886                    if (conn.mContainerService == null) {
13887                        return;
13888                    }
13889
13890                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13891                    clearDirectory(conn.mContainerService,
13892                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13893                    if (allData) {
13894                        clearDirectory(conn.mContainerService,
13895                                userEnv.buildExternalStorageAppDataDirs(packageName));
13896                        clearDirectory(conn.mContainerService,
13897                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13898                    }
13899                }
13900            } finally {
13901                mContext.unbindService(conn);
13902            }
13903        }
13904    }
13905
13906    @Override
13907    public void clearApplicationUserData(final String packageName,
13908            final IPackageDataObserver observer, final int userId) {
13909        mContext.enforceCallingOrSelfPermission(
13910                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13911        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13912        // Queue up an async operation since the package deletion may take a little while.
13913        mHandler.post(new Runnable() {
13914            public void run() {
13915                mHandler.removeCallbacks(this);
13916                final boolean succeeded;
13917                synchronized (mInstallLock) {
13918                    succeeded = clearApplicationUserDataLI(packageName, userId);
13919                }
13920                clearExternalStorageDataSync(packageName, userId, true);
13921                if (succeeded) {
13922                    // invoke DeviceStorageMonitor's update method to clear any notifications
13923                    DeviceStorageMonitorInternal
13924                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13925                    if (dsm != null) {
13926                        dsm.checkMemory();
13927                    }
13928                }
13929                if(observer != null) {
13930                    try {
13931                        observer.onRemoveCompleted(packageName, succeeded);
13932                    } catch (RemoteException e) {
13933                        Log.i(TAG, "Observer no longer exists.");
13934                    }
13935                } //end if observer
13936            } //end run
13937        });
13938    }
13939
13940    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13941        if (packageName == null) {
13942            Slog.w(TAG, "Attempt to delete null packageName.");
13943            return false;
13944        }
13945
13946        // Try finding details about the requested package
13947        PackageParser.Package pkg;
13948        synchronized (mPackages) {
13949            pkg = mPackages.get(packageName);
13950            if (pkg == null) {
13951                final PackageSetting ps = mSettings.mPackages.get(packageName);
13952                if (ps != null) {
13953                    pkg = ps.pkg;
13954                }
13955            }
13956
13957            if (pkg == null) {
13958                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13959                return false;
13960            }
13961
13962            PackageSetting ps = (PackageSetting) pkg.mExtras;
13963            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13964        }
13965
13966        // Always delete data directories for package, even if we found no other
13967        // record of app. This helps users recover from UID mismatches without
13968        // resorting to a full data wipe.
13969        // TODO: triage flags as part of 26466827
13970        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13971        try {
13972            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
13973        } catch (InstallerException e) {
13974            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
13975            return false;
13976        }
13977
13978        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
13979        removeKeystoreDataIfNeeded(userId, appId);
13980
13981        // Create a native library symlink only if we have native libraries
13982        // and if the native libraries are 32 bit libraries. We do not provide
13983        // this symlink for 64 bit libraries.
13984        if (pkg.applicationInfo.primaryCpuAbi != null &&
13985                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13986            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13987            try {
13988                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13989                        nativeLibPath, userId);
13990            } catch (InstallerException e) {
13991                Slog.w(TAG, "Failed linking native library dir", e);
13992                return false;
13993            }
13994        }
13995
13996        return true;
13997    }
13998
13999    /**
14000     * Reverts user permission state changes (permissions and flags) in
14001     * all packages for a given user.
14002     *
14003     * @param userId The device user for which to do a reset.
14004     */
14005    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14006        final int packageCount = mPackages.size();
14007        for (int i = 0; i < packageCount; i++) {
14008            PackageParser.Package pkg = mPackages.valueAt(i);
14009            PackageSetting ps = (PackageSetting) pkg.mExtras;
14010            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14011        }
14012    }
14013
14014    /**
14015     * Reverts user permission state changes (permissions and flags).
14016     *
14017     * @param ps The package for which to reset.
14018     * @param userId The device user for which to do a reset.
14019     */
14020    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14021            final PackageSetting ps, final int userId) {
14022        if (ps.pkg == null) {
14023            return;
14024        }
14025
14026        // These are flags that can change base on user actions.
14027        final int userSettableMask = FLAG_PERMISSION_USER_SET
14028                | FLAG_PERMISSION_USER_FIXED
14029                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14030                | FLAG_PERMISSION_REVIEW_REQUIRED;
14031
14032        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14033                | FLAG_PERMISSION_POLICY_FIXED;
14034
14035        boolean writeInstallPermissions = false;
14036        boolean writeRuntimePermissions = false;
14037
14038        final int permissionCount = ps.pkg.requestedPermissions.size();
14039        for (int i = 0; i < permissionCount; i++) {
14040            String permission = ps.pkg.requestedPermissions.get(i);
14041
14042            BasePermission bp = mSettings.mPermissions.get(permission);
14043            if (bp == null) {
14044                continue;
14045            }
14046
14047            // If shared user we just reset the state to which only this app contributed.
14048            if (ps.sharedUser != null) {
14049                boolean used = false;
14050                final int packageCount = ps.sharedUser.packages.size();
14051                for (int j = 0; j < packageCount; j++) {
14052                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14053                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14054                            && pkg.pkg.requestedPermissions.contains(permission)) {
14055                        used = true;
14056                        break;
14057                    }
14058                }
14059                if (used) {
14060                    continue;
14061                }
14062            }
14063
14064            PermissionsState permissionsState = ps.getPermissionsState();
14065
14066            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14067
14068            // Always clear the user settable flags.
14069            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14070                    bp.name) != null;
14071            // If permission review is enabled and this is a legacy app, mark the
14072            // permission as requiring a review as this is the initial state.
14073            int flags = 0;
14074            if (Build.PERMISSIONS_REVIEW_REQUIRED
14075                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14076                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14077            }
14078            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14079                if (hasInstallState) {
14080                    writeInstallPermissions = true;
14081                } else {
14082                    writeRuntimePermissions = true;
14083                }
14084            }
14085
14086            // Below is only runtime permission handling.
14087            if (!bp.isRuntime()) {
14088                continue;
14089            }
14090
14091            // Never clobber system or policy.
14092            if ((oldFlags & policyOrSystemFlags) != 0) {
14093                continue;
14094            }
14095
14096            // If this permission was granted by default, make sure it is.
14097            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14098                if (permissionsState.grantRuntimePermission(bp, userId)
14099                        != PERMISSION_OPERATION_FAILURE) {
14100                    writeRuntimePermissions = true;
14101                }
14102            // If permission review is enabled the permissions for a legacy apps
14103            // are represented as constantly granted runtime ones, so don't revoke.
14104            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14105                // Otherwise, reset the permission.
14106                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14107                switch (revokeResult) {
14108                    case PERMISSION_OPERATION_SUCCESS: {
14109                        writeRuntimePermissions = true;
14110                    } break;
14111
14112                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14113                        writeRuntimePermissions = true;
14114                        final int appId = ps.appId;
14115                        mHandler.post(new Runnable() {
14116                            @Override
14117                            public void run() {
14118                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14119                            }
14120                        });
14121                    } break;
14122                }
14123            }
14124        }
14125
14126        // Synchronously write as we are taking permissions away.
14127        if (writeRuntimePermissions) {
14128            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14129        }
14130
14131        // Synchronously write as we are taking permissions away.
14132        if (writeInstallPermissions) {
14133            mSettings.writeLPr();
14134        }
14135    }
14136
14137    /**
14138     * Remove entries from the keystore daemon. Will only remove it if the
14139     * {@code appId} is valid.
14140     */
14141    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14142        if (appId < 0) {
14143            return;
14144        }
14145
14146        final KeyStore keyStore = KeyStore.getInstance();
14147        if (keyStore != null) {
14148            if (userId == UserHandle.USER_ALL) {
14149                for (final int individual : sUserManager.getUserIds()) {
14150                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14151                }
14152            } else {
14153                keyStore.clearUid(UserHandle.getUid(userId, appId));
14154            }
14155        } else {
14156            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14157        }
14158    }
14159
14160    @Override
14161    public void deleteApplicationCacheFiles(final String packageName,
14162            final IPackageDataObserver observer) {
14163        mContext.enforceCallingOrSelfPermission(
14164                android.Manifest.permission.DELETE_CACHE_FILES, null);
14165        // Queue up an async operation since the package deletion may take a little while.
14166        final int userId = UserHandle.getCallingUserId();
14167        mHandler.post(new Runnable() {
14168            public void run() {
14169                mHandler.removeCallbacks(this);
14170                final boolean succeded;
14171                synchronized (mInstallLock) {
14172                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14173                }
14174                clearExternalStorageDataSync(packageName, userId, false);
14175                if (observer != null) {
14176                    try {
14177                        observer.onRemoveCompleted(packageName, succeded);
14178                    } catch (RemoteException e) {
14179                        Log.i(TAG, "Observer no longer exists.");
14180                    }
14181                } //end if observer
14182            } //end run
14183        });
14184    }
14185
14186    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14187        if (packageName == null) {
14188            Slog.w(TAG, "Attempt to delete null packageName.");
14189            return false;
14190        }
14191        PackageParser.Package p;
14192        synchronized (mPackages) {
14193            p = mPackages.get(packageName);
14194        }
14195        if (p == null) {
14196            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14197            return false;
14198        }
14199        final ApplicationInfo applicationInfo = p.applicationInfo;
14200        if (applicationInfo == null) {
14201            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14202            return false;
14203        }
14204        // TODO: triage flags as part of 26466827
14205        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14206        try {
14207            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14208                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14209        } catch (InstallerException e) {
14210            Slog.w(TAG, "Couldn't remove cache files for package "
14211                    + packageName + " u" + userId, e);
14212            return false;
14213        }
14214        return true;
14215    }
14216
14217    @Override
14218    public void getPackageSizeInfo(final String packageName, int userHandle,
14219            final IPackageStatsObserver observer) {
14220        mContext.enforceCallingOrSelfPermission(
14221                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14222        if (packageName == null) {
14223            throw new IllegalArgumentException("Attempt to get size of null packageName");
14224        }
14225
14226        PackageStats stats = new PackageStats(packageName, userHandle);
14227
14228        /*
14229         * Queue up an async operation since the package measurement may take a
14230         * little while.
14231         */
14232        Message msg = mHandler.obtainMessage(INIT_COPY);
14233        msg.obj = new MeasureParams(stats, observer);
14234        mHandler.sendMessage(msg);
14235    }
14236
14237    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14238            PackageStats pStats) {
14239        if (packageName == null) {
14240            Slog.w(TAG, "Attempt to get size of null packageName.");
14241            return false;
14242        }
14243        PackageParser.Package p;
14244        boolean dataOnly = false;
14245        String libDirRoot = null;
14246        String asecPath = null;
14247        PackageSetting ps = null;
14248        synchronized (mPackages) {
14249            p = mPackages.get(packageName);
14250            ps = mSettings.mPackages.get(packageName);
14251            if(p == null) {
14252                dataOnly = true;
14253                if((ps == null) || (ps.pkg == null)) {
14254                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14255                    return false;
14256                }
14257                p = ps.pkg;
14258            }
14259            if (ps != null) {
14260                libDirRoot = ps.legacyNativeLibraryPathString;
14261            }
14262            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14263                final long token = Binder.clearCallingIdentity();
14264                try {
14265                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14266                    if (secureContainerId != null) {
14267                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14268                    }
14269                } finally {
14270                    Binder.restoreCallingIdentity(token);
14271                }
14272            }
14273        }
14274        String publicSrcDir = null;
14275        if(!dataOnly) {
14276            final ApplicationInfo applicationInfo = p.applicationInfo;
14277            if (applicationInfo == null) {
14278                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14279                return false;
14280            }
14281            if (p.isForwardLocked()) {
14282                publicSrcDir = applicationInfo.getBaseResourcePath();
14283            }
14284        }
14285        // TODO: extend to measure size of split APKs
14286        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14287        // not just the first level.
14288        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14289        // just the primary.
14290        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14291
14292        String apkPath;
14293        File packageDir = new File(p.codePath);
14294
14295        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14296            apkPath = packageDir.getAbsolutePath();
14297            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14298            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14299                libDirRoot = null;
14300            }
14301        } else {
14302            apkPath = p.baseCodePath;
14303        }
14304
14305        // TODO: triage flags as part of 26466827
14306        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14307        try {
14308            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14309                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14310        } catch (InstallerException e) {
14311            return false;
14312        }
14313
14314        // Fix-up for forward-locked applications in ASEC containers.
14315        if (!isExternal(p)) {
14316            pStats.codeSize += pStats.externalCodeSize;
14317            pStats.externalCodeSize = 0L;
14318        }
14319
14320        return true;
14321    }
14322
14323
14324    @Override
14325    public void addPackageToPreferred(String packageName) {
14326        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14327    }
14328
14329    @Override
14330    public void removePackageFromPreferred(String packageName) {
14331        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14332    }
14333
14334    @Override
14335    public List<PackageInfo> getPreferredPackages(int flags) {
14336        return new ArrayList<PackageInfo>();
14337    }
14338
14339    private int getUidTargetSdkVersionLockedLPr(int uid) {
14340        Object obj = mSettings.getUserIdLPr(uid);
14341        if (obj instanceof SharedUserSetting) {
14342            final SharedUserSetting sus = (SharedUserSetting) obj;
14343            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14344            final Iterator<PackageSetting> it = sus.packages.iterator();
14345            while (it.hasNext()) {
14346                final PackageSetting ps = it.next();
14347                if (ps.pkg != null) {
14348                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14349                    if (v < vers) vers = v;
14350                }
14351            }
14352            return vers;
14353        } else if (obj instanceof PackageSetting) {
14354            final PackageSetting ps = (PackageSetting) obj;
14355            if (ps.pkg != null) {
14356                return ps.pkg.applicationInfo.targetSdkVersion;
14357            }
14358        }
14359        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14360    }
14361
14362    @Override
14363    public void addPreferredActivity(IntentFilter filter, int match,
14364            ComponentName[] set, ComponentName activity, int userId) {
14365        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14366                "Adding preferred");
14367    }
14368
14369    private void addPreferredActivityInternal(IntentFilter filter, int match,
14370            ComponentName[] set, ComponentName activity, boolean always, int userId,
14371            String opname) {
14372        // writer
14373        int callingUid = Binder.getCallingUid();
14374        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14375        if (filter.countActions() == 0) {
14376            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14377            return;
14378        }
14379        synchronized (mPackages) {
14380            if (mContext.checkCallingOrSelfPermission(
14381                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14382                    != PackageManager.PERMISSION_GRANTED) {
14383                if (getUidTargetSdkVersionLockedLPr(callingUid)
14384                        < Build.VERSION_CODES.FROYO) {
14385                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14386                            + callingUid);
14387                    return;
14388                }
14389                mContext.enforceCallingOrSelfPermission(
14390                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14391            }
14392
14393            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14394            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14395                    + userId + ":");
14396            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14397            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14398            scheduleWritePackageRestrictionsLocked(userId);
14399        }
14400    }
14401
14402    @Override
14403    public void replacePreferredActivity(IntentFilter filter, int match,
14404            ComponentName[] set, ComponentName activity, int userId) {
14405        if (filter.countActions() != 1) {
14406            throw new IllegalArgumentException(
14407                    "replacePreferredActivity expects filter to have only 1 action.");
14408        }
14409        if (filter.countDataAuthorities() != 0
14410                || filter.countDataPaths() != 0
14411                || filter.countDataSchemes() > 1
14412                || filter.countDataTypes() != 0) {
14413            throw new IllegalArgumentException(
14414                    "replacePreferredActivity expects filter to have no data authorities, " +
14415                    "paths, or types; and at most one scheme.");
14416        }
14417
14418        final int callingUid = Binder.getCallingUid();
14419        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14420        synchronized (mPackages) {
14421            if (mContext.checkCallingOrSelfPermission(
14422                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14423                    != PackageManager.PERMISSION_GRANTED) {
14424                if (getUidTargetSdkVersionLockedLPr(callingUid)
14425                        < Build.VERSION_CODES.FROYO) {
14426                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14427                            + Binder.getCallingUid());
14428                    return;
14429                }
14430                mContext.enforceCallingOrSelfPermission(
14431                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14432            }
14433
14434            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14435            if (pir != null) {
14436                // Get all of the existing entries that exactly match this filter.
14437                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14438                if (existing != null && existing.size() == 1) {
14439                    PreferredActivity cur = existing.get(0);
14440                    if (DEBUG_PREFERRED) {
14441                        Slog.i(TAG, "Checking replace of preferred:");
14442                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14443                        if (!cur.mPref.mAlways) {
14444                            Slog.i(TAG, "  -- CUR; not mAlways!");
14445                        } else {
14446                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14447                            Slog.i(TAG, "  -- CUR: mSet="
14448                                    + Arrays.toString(cur.mPref.mSetComponents));
14449                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14450                            Slog.i(TAG, "  -- NEW: mMatch="
14451                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14452                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14453                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14454                        }
14455                    }
14456                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14457                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14458                            && cur.mPref.sameSet(set)) {
14459                        // Setting the preferred activity to what it happens to be already
14460                        if (DEBUG_PREFERRED) {
14461                            Slog.i(TAG, "Replacing with same preferred activity "
14462                                    + cur.mPref.mShortComponent + " for user "
14463                                    + userId + ":");
14464                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14465                        }
14466                        return;
14467                    }
14468                }
14469
14470                if (existing != null) {
14471                    if (DEBUG_PREFERRED) {
14472                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14473                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14474                    }
14475                    for (int i = 0; i < existing.size(); i++) {
14476                        PreferredActivity pa = existing.get(i);
14477                        if (DEBUG_PREFERRED) {
14478                            Slog.i(TAG, "Removing existing preferred activity "
14479                                    + pa.mPref.mComponent + ":");
14480                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14481                        }
14482                        pir.removeFilter(pa);
14483                    }
14484                }
14485            }
14486            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14487                    "Replacing preferred");
14488        }
14489    }
14490
14491    @Override
14492    public void clearPackagePreferredActivities(String packageName) {
14493        final int uid = Binder.getCallingUid();
14494        // writer
14495        synchronized (mPackages) {
14496            PackageParser.Package pkg = mPackages.get(packageName);
14497            if (pkg == null || pkg.applicationInfo.uid != uid) {
14498                if (mContext.checkCallingOrSelfPermission(
14499                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14500                        != PackageManager.PERMISSION_GRANTED) {
14501                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14502                            < Build.VERSION_CODES.FROYO) {
14503                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14504                                + Binder.getCallingUid());
14505                        return;
14506                    }
14507                    mContext.enforceCallingOrSelfPermission(
14508                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14509                }
14510            }
14511
14512            int user = UserHandle.getCallingUserId();
14513            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14514                scheduleWritePackageRestrictionsLocked(user);
14515            }
14516        }
14517    }
14518
14519    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14520    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14521        ArrayList<PreferredActivity> removed = null;
14522        boolean changed = false;
14523        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14524            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14525            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14526            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14527                continue;
14528            }
14529            Iterator<PreferredActivity> it = pir.filterIterator();
14530            while (it.hasNext()) {
14531                PreferredActivity pa = it.next();
14532                // Mark entry for removal only if it matches the package name
14533                // and the entry is of type "always".
14534                if (packageName == null ||
14535                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14536                                && pa.mPref.mAlways)) {
14537                    if (removed == null) {
14538                        removed = new ArrayList<PreferredActivity>();
14539                    }
14540                    removed.add(pa);
14541                }
14542            }
14543            if (removed != null) {
14544                for (int j=0; j<removed.size(); j++) {
14545                    PreferredActivity pa = removed.get(j);
14546                    pir.removeFilter(pa);
14547                }
14548                changed = true;
14549            }
14550        }
14551        return changed;
14552    }
14553
14554    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14555    private void clearIntentFilterVerificationsLPw(int userId) {
14556        final int packageCount = mPackages.size();
14557        for (int i = 0; i < packageCount; i++) {
14558            PackageParser.Package pkg = mPackages.valueAt(i);
14559            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14560        }
14561    }
14562
14563    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14564    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14565        if (userId == UserHandle.USER_ALL) {
14566            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14567                    sUserManager.getUserIds())) {
14568                for (int oneUserId : sUserManager.getUserIds()) {
14569                    scheduleWritePackageRestrictionsLocked(oneUserId);
14570                }
14571            }
14572        } else {
14573            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14574                scheduleWritePackageRestrictionsLocked(userId);
14575            }
14576        }
14577    }
14578
14579    void clearDefaultBrowserIfNeeded(String packageName) {
14580        for (int oneUserId : sUserManager.getUserIds()) {
14581            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14582            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14583            if (packageName.equals(defaultBrowserPackageName)) {
14584                setDefaultBrowserPackageName(null, oneUserId);
14585            }
14586        }
14587    }
14588
14589    @Override
14590    public void resetApplicationPreferences(int userId) {
14591        mContext.enforceCallingOrSelfPermission(
14592                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14593        // writer
14594        synchronized (mPackages) {
14595            final long identity = Binder.clearCallingIdentity();
14596            try {
14597                clearPackagePreferredActivitiesLPw(null, userId);
14598                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14599                // TODO: We have to reset the default SMS and Phone. This requires
14600                // significant refactoring to keep all default apps in the package
14601                // manager (cleaner but more work) or have the services provide
14602                // callbacks to the package manager to request a default app reset.
14603                applyFactoryDefaultBrowserLPw(userId);
14604                clearIntentFilterVerificationsLPw(userId);
14605                primeDomainVerificationsLPw(userId);
14606                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14607                scheduleWritePackageRestrictionsLocked(userId);
14608            } finally {
14609                Binder.restoreCallingIdentity(identity);
14610            }
14611        }
14612    }
14613
14614    @Override
14615    public int getPreferredActivities(List<IntentFilter> outFilters,
14616            List<ComponentName> outActivities, String packageName) {
14617
14618        int num = 0;
14619        final int userId = UserHandle.getCallingUserId();
14620        // reader
14621        synchronized (mPackages) {
14622            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14623            if (pir != null) {
14624                final Iterator<PreferredActivity> it = pir.filterIterator();
14625                while (it.hasNext()) {
14626                    final PreferredActivity pa = it.next();
14627                    if (packageName == null
14628                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14629                                    && pa.mPref.mAlways)) {
14630                        if (outFilters != null) {
14631                            outFilters.add(new IntentFilter(pa));
14632                        }
14633                        if (outActivities != null) {
14634                            outActivities.add(pa.mPref.mComponent);
14635                        }
14636                    }
14637                }
14638            }
14639        }
14640
14641        return num;
14642    }
14643
14644    @Override
14645    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14646            int userId) {
14647        int callingUid = Binder.getCallingUid();
14648        if (callingUid != Process.SYSTEM_UID) {
14649            throw new SecurityException(
14650                    "addPersistentPreferredActivity can only be run by the system");
14651        }
14652        if (filter.countActions() == 0) {
14653            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14654            return;
14655        }
14656        synchronized (mPackages) {
14657            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14658                    ":");
14659            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14660            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14661                    new PersistentPreferredActivity(filter, activity));
14662            scheduleWritePackageRestrictionsLocked(userId);
14663        }
14664    }
14665
14666    @Override
14667    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14668        int callingUid = Binder.getCallingUid();
14669        if (callingUid != Process.SYSTEM_UID) {
14670            throw new SecurityException(
14671                    "clearPackagePersistentPreferredActivities can only be run by the system");
14672        }
14673        ArrayList<PersistentPreferredActivity> removed = null;
14674        boolean changed = false;
14675        synchronized (mPackages) {
14676            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14677                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14678                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14679                        .valueAt(i);
14680                if (userId != thisUserId) {
14681                    continue;
14682                }
14683                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14684                while (it.hasNext()) {
14685                    PersistentPreferredActivity ppa = it.next();
14686                    // Mark entry for removal only if it matches the package name.
14687                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14688                        if (removed == null) {
14689                            removed = new ArrayList<PersistentPreferredActivity>();
14690                        }
14691                        removed.add(ppa);
14692                    }
14693                }
14694                if (removed != null) {
14695                    for (int j=0; j<removed.size(); j++) {
14696                        PersistentPreferredActivity ppa = removed.get(j);
14697                        ppir.removeFilter(ppa);
14698                    }
14699                    changed = true;
14700                }
14701            }
14702
14703            if (changed) {
14704                scheduleWritePackageRestrictionsLocked(userId);
14705            }
14706        }
14707    }
14708
14709    /**
14710     * Common machinery for picking apart a restored XML blob and passing
14711     * it to a caller-supplied functor to be applied to the running system.
14712     */
14713    private void restoreFromXml(XmlPullParser parser, int userId,
14714            String expectedStartTag, BlobXmlRestorer functor)
14715            throws IOException, XmlPullParserException {
14716        int type;
14717        while ((type = parser.next()) != XmlPullParser.START_TAG
14718                && type != XmlPullParser.END_DOCUMENT) {
14719        }
14720        if (type != XmlPullParser.START_TAG) {
14721            // oops didn't find a start tag?!
14722            if (DEBUG_BACKUP) {
14723                Slog.e(TAG, "Didn't find start tag during restore");
14724            }
14725            return;
14726        }
14727Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14728        // this is supposed to be TAG_PREFERRED_BACKUP
14729        if (!expectedStartTag.equals(parser.getName())) {
14730            if (DEBUG_BACKUP) {
14731                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14732            }
14733            return;
14734        }
14735
14736        // skip interfering stuff, then we're aligned with the backing implementation
14737        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14738Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14739        functor.apply(parser, userId);
14740    }
14741
14742    private interface BlobXmlRestorer {
14743        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14744    }
14745
14746    /**
14747     * Non-Binder method, support for the backup/restore mechanism: write the
14748     * full set of preferred activities in its canonical XML format.  Returns the
14749     * XML output as a byte array, or null if there is none.
14750     */
14751    @Override
14752    public byte[] getPreferredActivityBackup(int userId) {
14753        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14754            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14755        }
14756
14757        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14758        try {
14759            final XmlSerializer serializer = new FastXmlSerializer();
14760            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14761            serializer.startDocument(null, true);
14762            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14763
14764            synchronized (mPackages) {
14765                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14766            }
14767
14768            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14769            serializer.endDocument();
14770            serializer.flush();
14771        } catch (Exception e) {
14772            if (DEBUG_BACKUP) {
14773                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14774            }
14775            return null;
14776        }
14777
14778        return dataStream.toByteArray();
14779    }
14780
14781    @Override
14782    public void restorePreferredActivities(byte[] backup, int userId) {
14783        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14784            throw new SecurityException("Only the system may call restorePreferredActivities()");
14785        }
14786
14787        try {
14788            final XmlPullParser parser = Xml.newPullParser();
14789            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14790            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14791                    new BlobXmlRestorer() {
14792                        @Override
14793                        public void apply(XmlPullParser parser, int userId)
14794                                throws XmlPullParserException, IOException {
14795                            synchronized (mPackages) {
14796                                mSettings.readPreferredActivitiesLPw(parser, userId);
14797                            }
14798                        }
14799                    } );
14800        } catch (Exception e) {
14801            if (DEBUG_BACKUP) {
14802                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14803            }
14804        }
14805    }
14806
14807    /**
14808     * Non-Binder method, support for the backup/restore mechanism: write the
14809     * default browser (etc) settings in its canonical XML format.  Returns the default
14810     * browser XML representation as a byte array, or null if there is none.
14811     */
14812    @Override
14813    public byte[] getDefaultAppsBackup(int userId) {
14814        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14815            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14816        }
14817
14818        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14819        try {
14820            final XmlSerializer serializer = new FastXmlSerializer();
14821            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14822            serializer.startDocument(null, true);
14823            serializer.startTag(null, TAG_DEFAULT_APPS);
14824
14825            synchronized (mPackages) {
14826                mSettings.writeDefaultAppsLPr(serializer, userId);
14827            }
14828
14829            serializer.endTag(null, TAG_DEFAULT_APPS);
14830            serializer.endDocument();
14831            serializer.flush();
14832        } catch (Exception e) {
14833            if (DEBUG_BACKUP) {
14834                Slog.e(TAG, "Unable to write default apps for backup", e);
14835            }
14836            return null;
14837        }
14838
14839        return dataStream.toByteArray();
14840    }
14841
14842    @Override
14843    public void restoreDefaultApps(byte[] backup, int userId) {
14844        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14845            throw new SecurityException("Only the system may call restoreDefaultApps()");
14846        }
14847
14848        try {
14849            final XmlPullParser parser = Xml.newPullParser();
14850            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14851            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14852                    new BlobXmlRestorer() {
14853                        @Override
14854                        public void apply(XmlPullParser parser, int userId)
14855                                throws XmlPullParserException, IOException {
14856                            synchronized (mPackages) {
14857                                mSettings.readDefaultAppsLPw(parser, userId);
14858                            }
14859                        }
14860                    } );
14861        } catch (Exception e) {
14862            if (DEBUG_BACKUP) {
14863                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14864            }
14865        }
14866    }
14867
14868    @Override
14869    public byte[] getIntentFilterVerificationBackup(int userId) {
14870        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14871            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14872        }
14873
14874        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14875        try {
14876            final XmlSerializer serializer = new FastXmlSerializer();
14877            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14878            serializer.startDocument(null, true);
14879            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14880
14881            synchronized (mPackages) {
14882                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14883            }
14884
14885            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14886            serializer.endDocument();
14887            serializer.flush();
14888        } catch (Exception e) {
14889            if (DEBUG_BACKUP) {
14890                Slog.e(TAG, "Unable to write default apps for backup", e);
14891            }
14892            return null;
14893        }
14894
14895        return dataStream.toByteArray();
14896    }
14897
14898    @Override
14899    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14901            throw new SecurityException("Only the system may call restorePreferredActivities()");
14902        }
14903
14904        try {
14905            final XmlPullParser parser = Xml.newPullParser();
14906            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14907            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14908                    new BlobXmlRestorer() {
14909                        @Override
14910                        public void apply(XmlPullParser parser, int userId)
14911                                throws XmlPullParserException, IOException {
14912                            synchronized (mPackages) {
14913                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14914                                mSettings.writeLPr();
14915                            }
14916                        }
14917                    } );
14918        } catch (Exception e) {
14919            if (DEBUG_BACKUP) {
14920                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14921            }
14922        }
14923    }
14924
14925    @Override
14926    public byte[] getPermissionGrantBackup(int userId) {
14927        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14928            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
14929        }
14930
14931        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14932        try {
14933            final XmlSerializer serializer = new FastXmlSerializer();
14934            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14935            serializer.startDocument(null, true);
14936            serializer.startTag(null, TAG_PERMISSION_BACKUP);
14937
14938            synchronized (mPackages) {
14939                serializeRuntimePermissionGrantsLPr(serializer, userId);
14940            }
14941
14942            serializer.endTag(null, TAG_PERMISSION_BACKUP);
14943            serializer.endDocument();
14944            serializer.flush();
14945        } catch (Exception e) {
14946            if (DEBUG_BACKUP) {
14947                Slog.e(TAG, "Unable to write default apps for backup", e);
14948            }
14949            return null;
14950        }
14951
14952        return dataStream.toByteArray();
14953    }
14954
14955    @Override
14956    public void restorePermissionGrants(byte[] backup, int userId) {
14957        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14958            throw new SecurityException("Only the system may call restorePermissionGrants()");
14959        }
14960
14961        try {
14962            final XmlPullParser parser = Xml.newPullParser();
14963            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14964            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
14965                    new BlobXmlRestorer() {
14966                        @Override
14967                        public void apply(XmlPullParser parser, int userId)
14968                                throws XmlPullParserException, IOException {
14969                            synchronized (mPackages) {
14970                                processRestoredPermissionGrantsLPr(parser, userId);
14971                            }
14972                        }
14973                    } );
14974        } catch (Exception e) {
14975            if (DEBUG_BACKUP) {
14976                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14977            }
14978        }
14979    }
14980
14981    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
14982            throws IOException {
14983        serializer.startTag(null, TAG_ALL_GRANTS);
14984
14985        final int N = mSettings.mPackages.size();
14986        for (int i = 0; i < N; i++) {
14987            final PackageSetting ps = mSettings.mPackages.valueAt(i);
14988            boolean pkgGrantsKnown = false;
14989
14990            PermissionsState packagePerms = ps.getPermissionsState();
14991
14992            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
14993                final int grantFlags = state.getFlags();
14994                // only look at grants that are not system/policy fixed
14995                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
14996                    final boolean isGranted = state.isGranted();
14997                    // And only back up the user-twiddled state bits
14998                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
14999                        final String packageName = mSettings.mPackages.keyAt(i);
15000                        if (!pkgGrantsKnown) {
15001                            serializer.startTag(null, TAG_GRANT);
15002                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15003                            pkgGrantsKnown = true;
15004                        }
15005
15006                        final boolean userSet =
15007                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15008                        final boolean userFixed =
15009                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15010                        final boolean revoke =
15011                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15012
15013                        serializer.startTag(null, TAG_PERMISSION);
15014                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15015                        if (isGranted) {
15016                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15017                        }
15018                        if (userSet) {
15019                            serializer.attribute(null, ATTR_USER_SET, "true");
15020                        }
15021                        if (userFixed) {
15022                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15023                        }
15024                        if (revoke) {
15025                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15026                        }
15027                        serializer.endTag(null, TAG_PERMISSION);
15028                    }
15029                }
15030            }
15031
15032            if (pkgGrantsKnown) {
15033                serializer.endTag(null, TAG_GRANT);
15034            }
15035        }
15036
15037        serializer.endTag(null, TAG_ALL_GRANTS);
15038    }
15039
15040    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15041            throws XmlPullParserException, IOException {
15042        String pkgName = null;
15043        int outerDepth = parser.getDepth();
15044        int type;
15045        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15046                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15047            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15048                continue;
15049            }
15050
15051            final String tagName = parser.getName();
15052            if (tagName.equals(TAG_GRANT)) {
15053                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15054                if (DEBUG_BACKUP) {
15055                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15056                }
15057            } else if (tagName.equals(TAG_PERMISSION)) {
15058
15059                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15060                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15061
15062                int newFlagSet = 0;
15063                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15064                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15065                }
15066                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15067                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15068                }
15069                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15070                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15071                }
15072                if (DEBUG_BACKUP) {
15073                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15074                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15075                }
15076                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15077                if (ps != null) {
15078                    // Already installed so we apply the grant immediately
15079                    if (DEBUG_BACKUP) {
15080                        Slog.v(TAG, "        + already installed; applying");
15081                    }
15082                    PermissionsState perms = ps.getPermissionsState();
15083                    BasePermission bp = mSettings.mPermissions.get(permName);
15084                    if (bp != null) {
15085                        if (isGranted) {
15086                            perms.grantRuntimePermission(bp, userId);
15087                        }
15088                        if (newFlagSet != 0) {
15089                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15090                        }
15091                    }
15092                } else {
15093                    // Need to wait for post-restore install to apply the grant
15094                    if (DEBUG_BACKUP) {
15095                        Slog.v(TAG, "        - not yet installed; saving for later");
15096                    }
15097                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15098                            isGranted, newFlagSet, userId);
15099                }
15100            } else {
15101                PackageManagerService.reportSettingsProblem(Log.WARN,
15102                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15103                XmlUtils.skipCurrentTag(parser);
15104            }
15105        }
15106
15107        scheduleWriteSettingsLocked();
15108        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15109    }
15110
15111    @Override
15112    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15113            int sourceUserId, int targetUserId, int flags) {
15114        mContext.enforceCallingOrSelfPermission(
15115                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15116        int callingUid = Binder.getCallingUid();
15117        enforceOwnerRights(ownerPackage, callingUid);
15118        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15119        if (intentFilter.countActions() == 0) {
15120            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15121            return;
15122        }
15123        synchronized (mPackages) {
15124            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15125                    ownerPackage, targetUserId, flags);
15126            CrossProfileIntentResolver resolver =
15127                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15128            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15129            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15130            if (existing != null) {
15131                int size = existing.size();
15132                for (int i = 0; i < size; i++) {
15133                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15134                        return;
15135                    }
15136                }
15137            }
15138            resolver.addFilter(newFilter);
15139            scheduleWritePackageRestrictionsLocked(sourceUserId);
15140        }
15141    }
15142
15143    @Override
15144    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15145        mContext.enforceCallingOrSelfPermission(
15146                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15147        int callingUid = Binder.getCallingUid();
15148        enforceOwnerRights(ownerPackage, callingUid);
15149        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15150        synchronized (mPackages) {
15151            CrossProfileIntentResolver resolver =
15152                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15153            ArraySet<CrossProfileIntentFilter> set =
15154                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15155            for (CrossProfileIntentFilter filter : set) {
15156                if (filter.getOwnerPackage().equals(ownerPackage)) {
15157                    resolver.removeFilter(filter);
15158                }
15159            }
15160            scheduleWritePackageRestrictionsLocked(sourceUserId);
15161        }
15162    }
15163
15164    // Enforcing that callingUid is owning pkg on userId
15165    private void enforceOwnerRights(String pkg, int callingUid) {
15166        // The system owns everything.
15167        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15168            return;
15169        }
15170        int callingUserId = UserHandle.getUserId(callingUid);
15171        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15172        if (pi == null) {
15173            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15174                    + callingUserId);
15175        }
15176        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15177            throw new SecurityException("Calling uid " + callingUid
15178                    + " does not own package " + pkg);
15179        }
15180    }
15181
15182    @Override
15183    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15184        Intent intent = new Intent(Intent.ACTION_MAIN);
15185        intent.addCategory(Intent.CATEGORY_HOME);
15186
15187        final int callingUserId = UserHandle.getCallingUserId();
15188        List<ResolveInfo> list = queryIntentActivities(intent, null,
15189                PackageManager.GET_META_DATA, callingUserId);
15190        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15191                true, false, false, callingUserId);
15192
15193        allHomeCandidates.clear();
15194        if (list != null) {
15195            for (ResolveInfo ri : list) {
15196                allHomeCandidates.add(ri);
15197            }
15198        }
15199        return (preferred == null || preferred.activityInfo == null)
15200                ? null
15201                : new ComponentName(preferred.activityInfo.packageName,
15202                        preferred.activityInfo.name);
15203    }
15204
15205    @Override
15206    public void setApplicationEnabledSetting(String appPackageName,
15207            int newState, int flags, int userId, String callingPackage) {
15208        if (!sUserManager.exists(userId)) return;
15209        if (callingPackage == null) {
15210            callingPackage = Integer.toString(Binder.getCallingUid());
15211        }
15212        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15213    }
15214
15215    @Override
15216    public void setComponentEnabledSetting(ComponentName componentName,
15217            int newState, int flags, int userId) {
15218        if (!sUserManager.exists(userId)) return;
15219        setEnabledSetting(componentName.getPackageName(),
15220                componentName.getClassName(), newState, flags, userId, null);
15221    }
15222
15223    private void setEnabledSetting(final String packageName, String className, int newState,
15224            final int flags, int userId, String callingPackage) {
15225        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15226              || newState == COMPONENT_ENABLED_STATE_ENABLED
15227              || newState == COMPONENT_ENABLED_STATE_DISABLED
15228              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15229              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15230            throw new IllegalArgumentException("Invalid new component state: "
15231                    + newState);
15232        }
15233        PackageSetting pkgSetting;
15234        final int uid = Binder.getCallingUid();
15235        final int permission = mContext.checkCallingOrSelfPermission(
15236                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15237        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15238        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15239        boolean sendNow = false;
15240        boolean isApp = (className == null);
15241        String componentName = isApp ? packageName : className;
15242        int packageUid = -1;
15243        ArrayList<String> components;
15244
15245        // writer
15246        synchronized (mPackages) {
15247            pkgSetting = mSettings.mPackages.get(packageName);
15248            if (pkgSetting == null) {
15249                if (className == null) {
15250                    throw new IllegalArgumentException("Unknown package: " + packageName);
15251                }
15252                throw new IllegalArgumentException(
15253                        "Unknown component: " + packageName + "/" + className);
15254            }
15255            // Allow root and verify that userId is not being specified by a different user
15256            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15257                throw new SecurityException(
15258                        "Permission Denial: attempt to change component state from pid="
15259                        + Binder.getCallingPid()
15260                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15261            }
15262            if (className == null) {
15263                // We're dealing with an application/package level state change
15264                if (pkgSetting.getEnabled(userId) == newState) {
15265                    // Nothing to do
15266                    return;
15267                }
15268                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15269                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15270                    // Don't care about who enables an app.
15271                    callingPackage = null;
15272                }
15273                pkgSetting.setEnabled(newState, userId, callingPackage);
15274                // pkgSetting.pkg.mSetEnabled = newState;
15275            } else {
15276                // We're dealing with a component level state change
15277                // First, verify that this is a valid class name.
15278                PackageParser.Package pkg = pkgSetting.pkg;
15279                if (pkg == null || !pkg.hasComponentClassName(className)) {
15280                    if (pkg != null &&
15281                            pkg.applicationInfo.targetSdkVersion >=
15282                                    Build.VERSION_CODES.JELLY_BEAN) {
15283                        throw new IllegalArgumentException("Component class " + className
15284                                + " does not exist in " + packageName);
15285                    } else {
15286                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15287                                + className + " does not exist in " + packageName);
15288                    }
15289                }
15290                switch (newState) {
15291                case COMPONENT_ENABLED_STATE_ENABLED:
15292                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15293                        return;
15294                    }
15295                    break;
15296                case COMPONENT_ENABLED_STATE_DISABLED:
15297                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15298                        return;
15299                    }
15300                    break;
15301                case COMPONENT_ENABLED_STATE_DEFAULT:
15302                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15303                        return;
15304                    }
15305                    break;
15306                default:
15307                    Slog.e(TAG, "Invalid new component state: " + newState);
15308                    return;
15309                }
15310            }
15311            scheduleWritePackageRestrictionsLocked(userId);
15312            components = mPendingBroadcasts.get(userId, packageName);
15313            final boolean newPackage = components == null;
15314            if (newPackage) {
15315                components = new ArrayList<String>();
15316            }
15317            if (!components.contains(componentName)) {
15318                components.add(componentName);
15319            }
15320            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15321                sendNow = true;
15322                // Purge entry from pending broadcast list if another one exists already
15323                // since we are sending one right away.
15324                mPendingBroadcasts.remove(userId, packageName);
15325            } else {
15326                if (newPackage) {
15327                    mPendingBroadcasts.put(userId, packageName, components);
15328                }
15329                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15330                    // Schedule a message
15331                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15332                }
15333            }
15334        }
15335
15336        long callingId = Binder.clearCallingIdentity();
15337        try {
15338            if (sendNow) {
15339                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15340                sendPackageChangedBroadcast(packageName,
15341                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15342            }
15343        } finally {
15344            Binder.restoreCallingIdentity(callingId);
15345        }
15346    }
15347
15348    private void sendPackageChangedBroadcast(String packageName,
15349            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15350        if (DEBUG_INSTALL)
15351            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15352                    + componentNames);
15353        Bundle extras = new Bundle(4);
15354        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15355        String nameList[] = new String[componentNames.size()];
15356        componentNames.toArray(nameList);
15357        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15358        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15359        extras.putInt(Intent.EXTRA_UID, packageUid);
15360        // If this is not reporting a change of the overall package, then only send it
15361        // to registered receivers.  We don't want to launch a swath of apps for every
15362        // little component state change.
15363        final int flags = !componentNames.contains(packageName)
15364                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15365        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15366                new int[] {UserHandle.getUserId(packageUid)});
15367    }
15368
15369    @Override
15370    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15371        if (!sUserManager.exists(userId)) return;
15372        final int uid = Binder.getCallingUid();
15373        final int permission = mContext.checkCallingOrSelfPermission(
15374                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15375        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15376        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15377        // writer
15378        synchronized (mPackages) {
15379            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15380                    allowedByPermission, uid, userId)) {
15381                scheduleWritePackageRestrictionsLocked(userId);
15382            }
15383        }
15384    }
15385
15386    @Override
15387    public String getInstallerPackageName(String packageName) {
15388        // reader
15389        synchronized (mPackages) {
15390            return mSettings.getInstallerPackageNameLPr(packageName);
15391        }
15392    }
15393
15394    @Override
15395    public int getApplicationEnabledSetting(String packageName, int userId) {
15396        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15397        int uid = Binder.getCallingUid();
15398        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15399        // reader
15400        synchronized (mPackages) {
15401            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15402        }
15403    }
15404
15405    @Override
15406    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15407        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15408        int uid = Binder.getCallingUid();
15409        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15410        // reader
15411        synchronized (mPackages) {
15412            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15413        }
15414    }
15415
15416    @Override
15417    public void enterSafeMode() {
15418        enforceSystemOrRoot("Only the system can request entering safe mode");
15419
15420        if (!mSystemReady) {
15421            mSafeMode = true;
15422        }
15423    }
15424
15425    @Override
15426    public void systemReady() {
15427        mSystemReady = true;
15428
15429        // Read the compatibilty setting when the system is ready.
15430        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15431                mContext.getContentResolver(),
15432                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15433        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15434        if (DEBUG_SETTINGS) {
15435            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15436        }
15437
15438        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15439
15440        synchronized (mPackages) {
15441            // Verify that all of the preferred activity components actually
15442            // exist.  It is possible for applications to be updated and at
15443            // that point remove a previously declared activity component that
15444            // had been set as a preferred activity.  We try to clean this up
15445            // the next time we encounter that preferred activity, but it is
15446            // possible for the user flow to never be able to return to that
15447            // situation so here we do a sanity check to make sure we haven't
15448            // left any junk around.
15449            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15450            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15451                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15452                removed.clear();
15453                for (PreferredActivity pa : pir.filterSet()) {
15454                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15455                        removed.add(pa);
15456                    }
15457                }
15458                if (removed.size() > 0) {
15459                    for (int r=0; r<removed.size(); r++) {
15460                        PreferredActivity pa = removed.get(r);
15461                        Slog.w(TAG, "Removing dangling preferred activity: "
15462                                + pa.mPref.mComponent);
15463                        pir.removeFilter(pa);
15464                    }
15465                    mSettings.writePackageRestrictionsLPr(
15466                            mSettings.mPreferredActivities.keyAt(i));
15467                }
15468            }
15469
15470            for (int userId : UserManagerService.getInstance().getUserIds()) {
15471                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15472                    grantPermissionsUserIds = ArrayUtils.appendInt(
15473                            grantPermissionsUserIds, userId);
15474                }
15475            }
15476        }
15477        sUserManager.systemReady();
15478
15479        // If we upgraded grant all default permissions before kicking off.
15480        for (int userId : grantPermissionsUserIds) {
15481            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15482        }
15483
15484        // Kick off any messages waiting for system ready
15485        if (mPostSystemReadyMessages != null) {
15486            for (Message msg : mPostSystemReadyMessages) {
15487                msg.sendToTarget();
15488            }
15489            mPostSystemReadyMessages = null;
15490        }
15491
15492        // Watch for external volumes that come and go over time
15493        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15494        storage.registerListener(mStorageListener);
15495
15496        mInstallerService.systemReady();
15497        mPackageDexOptimizer.systemReady();
15498
15499        MountServiceInternal mountServiceInternal = LocalServices.getService(
15500                MountServiceInternal.class);
15501        mountServiceInternal.addExternalStoragePolicy(
15502                new MountServiceInternal.ExternalStorageMountPolicy() {
15503            @Override
15504            public int getMountMode(int uid, String packageName) {
15505                if (Process.isIsolated(uid)) {
15506                    return Zygote.MOUNT_EXTERNAL_NONE;
15507                }
15508                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15509                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15510                }
15511                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15512                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15513                }
15514                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15515                    return Zygote.MOUNT_EXTERNAL_READ;
15516                }
15517                return Zygote.MOUNT_EXTERNAL_WRITE;
15518            }
15519
15520            @Override
15521            public boolean hasExternalStorage(int uid, String packageName) {
15522                return true;
15523            }
15524        });
15525    }
15526
15527    @Override
15528    public boolean isSafeMode() {
15529        return mSafeMode;
15530    }
15531
15532    @Override
15533    public boolean hasSystemUidErrors() {
15534        return mHasSystemUidErrors;
15535    }
15536
15537    static String arrayToString(int[] array) {
15538        StringBuffer buf = new StringBuffer(128);
15539        buf.append('[');
15540        if (array != null) {
15541            for (int i=0; i<array.length; i++) {
15542                if (i > 0) buf.append(", ");
15543                buf.append(array[i]);
15544            }
15545        }
15546        buf.append(']');
15547        return buf.toString();
15548    }
15549
15550    static class DumpState {
15551        public static final int DUMP_LIBS = 1 << 0;
15552        public static final int DUMP_FEATURES = 1 << 1;
15553        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15554        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15555        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15556        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15557        public static final int DUMP_PERMISSIONS = 1 << 6;
15558        public static final int DUMP_PACKAGES = 1 << 7;
15559        public static final int DUMP_SHARED_USERS = 1 << 8;
15560        public static final int DUMP_MESSAGES = 1 << 9;
15561        public static final int DUMP_PROVIDERS = 1 << 10;
15562        public static final int DUMP_VERIFIERS = 1 << 11;
15563        public static final int DUMP_PREFERRED = 1 << 12;
15564        public static final int DUMP_PREFERRED_XML = 1 << 13;
15565        public static final int DUMP_KEYSETS = 1 << 14;
15566        public static final int DUMP_VERSION = 1 << 15;
15567        public static final int DUMP_INSTALLS = 1 << 16;
15568        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15569        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15570
15571        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15572
15573        private int mTypes;
15574
15575        private int mOptions;
15576
15577        private boolean mTitlePrinted;
15578
15579        private SharedUserSetting mSharedUser;
15580
15581        public boolean isDumping(int type) {
15582            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15583                return true;
15584            }
15585
15586            return (mTypes & type) != 0;
15587        }
15588
15589        public void setDump(int type) {
15590            mTypes |= type;
15591        }
15592
15593        public boolean isOptionEnabled(int option) {
15594            return (mOptions & option) != 0;
15595        }
15596
15597        public void setOptionEnabled(int option) {
15598            mOptions |= option;
15599        }
15600
15601        public boolean onTitlePrinted() {
15602            final boolean printed = mTitlePrinted;
15603            mTitlePrinted = true;
15604            return printed;
15605        }
15606
15607        public boolean getTitlePrinted() {
15608            return mTitlePrinted;
15609        }
15610
15611        public void setTitlePrinted(boolean enabled) {
15612            mTitlePrinted = enabled;
15613        }
15614
15615        public SharedUserSetting getSharedUser() {
15616            return mSharedUser;
15617        }
15618
15619        public void setSharedUser(SharedUserSetting user) {
15620            mSharedUser = user;
15621        }
15622    }
15623
15624    @Override
15625    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15626            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15627        (new PackageManagerShellCommand(this)).exec(
15628                this, in, out, err, args, resultReceiver);
15629    }
15630
15631    @Override
15632    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15633        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15634                != PackageManager.PERMISSION_GRANTED) {
15635            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15636                    + Binder.getCallingPid()
15637                    + ", uid=" + Binder.getCallingUid()
15638                    + " without permission "
15639                    + android.Manifest.permission.DUMP);
15640            return;
15641        }
15642
15643        DumpState dumpState = new DumpState();
15644        boolean fullPreferred = false;
15645        boolean checkin = false;
15646
15647        String packageName = null;
15648        ArraySet<String> permissionNames = null;
15649
15650        int opti = 0;
15651        while (opti < args.length) {
15652            String opt = args[opti];
15653            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15654                break;
15655            }
15656            opti++;
15657
15658            if ("-a".equals(opt)) {
15659                // Right now we only know how to print all.
15660            } else if ("-h".equals(opt)) {
15661                pw.println("Package manager dump options:");
15662                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15663                pw.println("    --checkin: dump for a checkin");
15664                pw.println("    -f: print details of intent filters");
15665                pw.println("    -h: print this help");
15666                pw.println("  cmd may be one of:");
15667                pw.println("    l[ibraries]: list known shared libraries");
15668                pw.println("    f[eatures]: list device features");
15669                pw.println("    k[eysets]: print known keysets");
15670                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15671                pw.println("    perm[issions]: dump permissions");
15672                pw.println("    permission [name ...]: dump declaration and use of given permission");
15673                pw.println("    pref[erred]: print preferred package settings");
15674                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15675                pw.println("    prov[iders]: dump content providers");
15676                pw.println("    p[ackages]: dump installed packages");
15677                pw.println("    s[hared-users]: dump shared user IDs");
15678                pw.println("    m[essages]: print collected runtime messages");
15679                pw.println("    v[erifiers]: print package verifier info");
15680                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15681                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15682                pw.println("    version: print database version info");
15683                pw.println("    write: write current settings now");
15684                pw.println("    installs: details about install sessions");
15685                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15686                pw.println("    <package.name>: info about given package");
15687                return;
15688            } else if ("--checkin".equals(opt)) {
15689                checkin = true;
15690            } else if ("-f".equals(opt)) {
15691                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15692            } else {
15693                pw.println("Unknown argument: " + opt + "; use -h for help");
15694            }
15695        }
15696
15697        // Is the caller requesting to dump a particular piece of data?
15698        if (opti < args.length) {
15699            String cmd = args[opti];
15700            opti++;
15701            // Is this a package name?
15702            if ("android".equals(cmd) || cmd.contains(".")) {
15703                packageName = cmd;
15704                // When dumping a single package, we always dump all of its
15705                // filter information since the amount of data will be reasonable.
15706                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15707            } else if ("check-permission".equals(cmd)) {
15708                if (opti >= args.length) {
15709                    pw.println("Error: check-permission missing permission argument");
15710                    return;
15711                }
15712                String perm = args[opti];
15713                opti++;
15714                if (opti >= args.length) {
15715                    pw.println("Error: check-permission missing package argument");
15716                    return;
15717                }
15718                String pkg = args[opti];
15719                opti++;
15720                int user = UserHandle.getUserId(Binder.getCallingUid());
15721                if (opti < args.length) {
15722                    try {
15723                        user = Integer.parseInt(args[opti]);
15724                    } catch (NumberFormatException e) {
15725                        pw.println("Error: check-permission user argument is not a number: "
15726                                + args[opti]);
15727                        return;
15728                    }
15729                }
15730                pw.println(checkPermission(perm, pkg, user));
15731                return;
15732            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15733                dumpState.setDump(DumpState.DUMP_LIBS);
15734            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15735                dumpState.setDump(DumpState.DUMP_FEATURES);
15736            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15737                if (opti >= args.length) {
15738                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15739                            | DumpState.DUMP_SERVICE_RESOLVERS
15740                            | DumpState.DUMP_RECEIVER_RESOLVERS
15741                            | DumpState.DUMP_CONTENT_RESOLVERS);
15742                } else {
15743                    while (opti < args.length) {
15744                        String name = args[opti];
15745                        if ("a".equals(name) || "activity".equals(name)) {
15746                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15747                        } else if ("s".equals(name) || "service".equals(name)) {
15748                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15749                        } else if ("r".equals(name) || "receiver".equals(name)) {
15750                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15751                        } else if ("c".equals(name) || "content".equals(name)) {
15752                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15753                        } else {
15754                            pw.println("Error: unknown resolver table type: " + name);
15755                            return;
15756                        }
15757                        opti++;
15758                    }
15759                }
15760            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15761                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15762            } else if ("permission".equals(cmd)) {
15763                if (opti >= args.length) {
15764                    pw.println("Error: permission requires permission name");
15765                    return;
15766                }
15767                permissionNames = new ArraySet<>();
15768                while (opti < args.length) {
15769                    permissionNames.add(args[opti]);
15770                    opti++;
15771                }
15772                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15773                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15774            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15775                dumpState.setDump(DumpState.DUMP_PREFERRED);
15776            } else if ("preferred-xml".equals(cmd)) {
15777                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15778                if (opti < args.length && "--full".equals(args[opti])) {
15779                    fullPreferred = true;
15780                    opti++;
15781                }
15782            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15783                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15784            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15785                dumpState.setDump(DumpState.DUMP_PACKAGES);
15786            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15787                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15788            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15789                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15790            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15791                dumpState.setDump(DumpState.DUMP_MESSAGES);
15792            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15793                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15794            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15795                    || "intent-filter-verifiers".equals(cmd)) {
15796                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15797            } else if ("version".equals(cmd)) {
15798                dumpState.setDump(DumpState.DUMP_VERSION);
15799            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15800                dumpState.setDump(DumpState.DUMP_KEYSETS);
15801            } else if ("installs".equals(cmd)) {
15802                dumpState.setDump(DumpState.DUMP_INSTALLS);
15803            } else if ("write".equals(cmd)) {
15804                synchronized (mPackages) {
15805                    mSettings.writeLPr();
15806                    pw.println("Settings written.");
15807                    return;
15808                }
15809            }
15810        }
15811
15812        if (checkin) {
15813            pw.println("vers,1");
15814        }
15815
15816        // reader
15817        synchronized (mPackages) {
15818            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15819                if (!checkin) {
15820                    if (dumpState.onTitlePrinted())
15821                        pw.println();
15822                    pw.println("Database versions:");
15823                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15824                }
15825            }
15826
15827            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15828                if (!checkin) {
15829                    if (dumpState.onTitlePrinted())
15830                        pw.println();
15831                    pw.println("Verifiers:");
15832                    pw.print("  Required: ");
15833                    pw.print(mRequiredVerifierPackage);
15834                    pw.print(" (uid=");
15835                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15836                            UserHandle.USER_SYSTEM));
15837                    pw.println(")");
15838                } else if (mRequiredVerifierPackage != null) {
15839                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15840                    pw.print(",");
15841                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15842                            UserHandle.USER_SYSTEM));
15843                }
15844            }
15845
15846            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15847                    packageName == null) {
15848                if (mIntentFilterVerifierComponent != null) {
15849                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15850                    if (!checkin) {
15851                        if (dumpState.onTitlePrinted())
15852                            pw.println();
15853                        pw.println("Intent Filter Verifier:");
15854                        pw.print("  Using: ");
15855                        pw.print(verifierPackageName);
15856                        pw.print(" (uid=");
15857                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15858                                UserHandle.USER_SYSTEM));
15859                        pw.println(")");
15860                    } else if (verifierPackageName != null) {
15861                        pw.print("ifv,"); pw.print(verifierPackageName);
15862                        pw.print(",");
15863                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15864                                UserHandle.USER_SYSTEM));
15865                    }
15866                } else {
15867                    pw.println();
15868                    pw.println("No Intent Filter Verifier available!");
15869                }
15870            }
15871
15872            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15873                boolean printedHeader = false;
15874                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15875                while (it.hasNext()) {
15876                    String name = it.next();
15877                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15878                    if (!checkin) {
15879                        if (!printedHeader) {
15880                            if (dumpState.onTitlePrinted())
15881                                pw.println();
15882                            pw.println("Libraries:");
15883                            printedHeader = true;
15884                        }
15885                        pw.print("  ");
15886                    } else {
15887                        pw.print("lib,");
15888                    }
15889                    pw.print(name);
15890                    if (!checkin) {
15891                        pw.print(" -> ");
15892                    }
15893                    if (ent.path != null) {
15894                        if (!checkin) {
15895                            pw.print("(jar) ");
15896                            pw.print(ent.path);
15897                        } else {
15898                            pw.print(",jar,");
15899                            pw.print(ent.path);
15900                        }
15901                    } else {
15902                        if (!checkin) {
15903                            pw.print("(apk) ");
15904                            pw.print(ent.apk);
15905                        } else {
15906                            pw.print(",apk,");
15907                            pw.print(ent.apk);
15908                        }
15909                    }
15910                    pw.println();
15911                }
15912            }
15913
15914            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15915                if (dumpState.onTitlePrinted())
15916                    pw.println();
15917                if (!checkin) {
15918                    pw.println("Features:");
15919                }
15920                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15921                while (it.hasNext()) {
15922                    String name = it.next();
15923                    if (!checkin) {
15924                        pw.print("  ");
15925                    } else {
15926                        pw.print("feat,");
15927                    }
15928                    pw.println(name);
15929                }
15930            }
15931
15932            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15933                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15934                        : "Activity Resolver Table:", "  ", packageName,
15935                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15936                    dumpState.setTitlePrinted(true);
15937                }
15938            }
15939            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15940                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15941                        : "Receiver Resolver Table:", "  ", packageName,
15942                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15943                    dumpState.setTitlePrinted(true);
15944                }
15945            }
15946            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15947                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15948                        : "Service Resolver Table:", "  ", packageName,
15949                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15950                    dumpState.setTitlePrinted(true);
15951                }
15952            }
15953            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15954                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15955                        : "Provider Resolver Table:", "  ", packageName,
15956                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15957                    dumpState.setTitlePrinted(true);
15958                }
15959            }
15960
15961            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15962                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15963                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15964                    int user = mSettings.mPreferredActivities.keyAt(i);
15965                    if (pir.dump(pw,
15966                            dumpState.getTitlePrinted()
15967                                ? "\nPreferred Activities User " + user + ":"
15968                                : "Preferred Activities User " + user + ":", "  ",
15969                            packageName, true, false)) {
15970                        dumpState.setTitlePrinted(true);
15971                    }
15972                }
15973            }
15974
15975            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15976                pw.flush();
15977                FileOutputStream fout = new FileOutputStream(fd);
15978                BufferedOutputStream str = new BufferedOutputStream(fout);
15979                XmlSerializer serializer = new FastXmlSerializer();
15980                try {
15981                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15982                    serializer.startDocument(null, true);
15983                    serializer.setFeature(
15984                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15985                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15986                    serializer.endDocument();
15987                    serializer.flush();
15988                } catch (IllegalArgumentException e) {
15989                    pw.println("Failed writing: " + e);
15990                } catch (IllegalStateException e) {
15991                    pw.println("Failed writing: " + e);
15992                } catch (IOException e) {
15993                    pw.println("Failed writing: " + e);
15994                }
15995            }
15996
15997            if (!checkin
15998                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15999                    && packageName == null) {
16000                pw.println();
16001                int count = mSettings.mPackages.size();
16002                if (count == 0) {
16003                    pw.println("No applications!");
16004                    pw.println();
16005                } else {
16006                    final String prefix = "  ";
16007                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16008                    if (allPackageSettings.size() == 0) {
16009                        pw.println("No domain preferred apps!");
16010                        pw.println();
16011                    } else {
16012                        pw.println("App verification status:");
16013                        pw.println();
16014                        count = 0;
16015                        for (PackageSetting ps : allPackageSettings) {
16016                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16017                            if (ivi == null || ivi.getPackageName() == null) continue;
16018                            pw.println(prefix + "Package: " + ivi.getPackageName());
16019                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16020                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16021                            pw.println();
16022                            count++;
16023                        }
16024                        if (count == 0) {
16025                            pw.println(prefix + "No app verification established.");
16026                            pw.println();
16027                        }
16028                        for (int userId : sUserManager.getUserIds()) {
16029                            pw.println("App linkages for user " + userId + ":");
16030                            pw.println();
16031                            count = 0;
16032                            for (PackageSetting ps : allPackageSettings) {
16033                                final long status = ps.getDomainVerificationStatusForUser(userId);
16034                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16035                                    continue;
16036                                }
16037                                pw.println(prefix + "Package: " + ps.name);
16038                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16039                                String statusStr = IntentFilterVerificationInfo.
16040                                        getStatusStringFromValue(status);
16041                                pw.println(prefix + "Status:  " + statusStr);
16042                                pw.println();
16043                                count++;
16044                            }
16045                            if (count == 0) {
16046                                pw.println(prefix + "No configured app linkages.");
16047                                pw.println();
16048                            }
16049                        }
16050                    }
16051                }
16052            }
16053
16054            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16055                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16056                if (packageName == null && permissionNames == null) {
16057                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16058                        if (iperm == 0) {
16059                            if (dumpState.onTitlePrinted())
16060                                pw.println();
16061                            pw.println("AppOp Permissions:");
16062                        }
16063                        pw.print("  AppOp Permission ");
16064                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16065                        pw.println(":");
16066                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16067                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16068                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16069                        }
16070                    }
16071                }
16072            }
16073
16074            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16075                boolean printedSomething = false;
16076                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16077                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16078                        continue;
16079                    }
16080                    if (!printedSomething) {
16081                        if (dumpState.onTitlePrinted())
16082                            pw.println();
16083                        pw.println("Registered ContentProviders:");
16084                        printedSomething = true;
16085                    }
16086                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16087                    pw.print("    "); pw.println(p.toString());
16088                }
16089                printedSomething = false;
16090                for (Map.Entry<String, PackageParser.Provider> entry :
16091                        mProvidersByAuthority.entrySet()) {
16092                    PackageParser.Provider p = entry.getValue();
16093                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16094                        continue;
16095                    }
16096                    if (!printedSomething) {
16097                        if (dumpState.onTitlePrinted())
16098                            pw.println();
16099                        pw.println("ContentProvider Authorities:");
16100                        printedSomething = true;
16101                    }
16102                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16103                    pw.print("    "); pw.println(p.toString());
16104                    if (p.info != null && p.info.applicationInfo != null) {
16105                        final String appInfo = p.info.applicationInfo.toString();
16106                        pw.print("      applicationInfo="); pw.println(appInfo);
16107                    }
16108                }
16109            }
16110
16111            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16112                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16113            }
16114
16115            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16116                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16117            }
16118
16119            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16120                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16121            }
16122
16123            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16124                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16125            }
16126
16127            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16128                // XXX should handle packageName != null by dumping only install data that
16129                // the given package is involved with.
16130                if (dumpState.onTitlePrinted()) pw.println();
16131                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16132            }
16133
16134            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16135                if (dumpState.onTitlePrinted()) pw.println();
16136                mSettings.dumpReadMessagesLPr(pw, dumpState);
16137
16138                pw.println();
16139                pw.println("Package warning messages:");
16140                BufferedReader in = null;
16141                String line = null;
16142                try {
16143                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16144                    while ((line = in.readLine()) != null) {
16145                        if (line.contains("ignored: updated version")) continue;
16146                        pw.println(line);
16147                    }
16148                } catch (IOException ignored) {
16149                } finally {
16150                    IoUtils.closeQuietly(in);
16151                }
16152            }
16153
16154            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16155                BufferedReader in = null;
16156                String line = null;
16157                try {
16158                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16159                    while ((line = in.readLine()) != null) {
16160                        if (line.contains("ignored: updated version")) continue;
16161                        pw.print("msg,");
16162                        pw.println(line);
16163                    }
16164                } catch (IOException ignored) {
16165                } finally {
16166                    IoUtils.closeQuietly(in);
16167                }
16168            }
16169        }
16170    }
16171
16172    private String dumpDomainString(String packageName) {
16173        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16174        List<IntentFilter> filters = getAllIntentFilters(packageName);
16175
16176        ArraySet<String> result = new ArraySet<>();
16177        if (iviList.size() > 0) {
16178            for (IntentFilterVerificationInfo ivi : iviList) {
16179                for (String host : ivi.getDomains()) {
16180                    result.add(host);
16181                }
16182            }
16183        }
16184        if (filters != null && filters.size() > 0) {
16185            for (IntentFilter filter : filters) {
16186                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16187                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16188                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16189                    result.addAll(filter.getHostsList());
16190                }
16191            }
16192        }
16193
16194        StringBuilder sb = new StringBuilder(result.size() * 16);
16195        for (String domain : result) {
16196            if (sb.length() > 0) sb.append(" ");
16197            sb.append(domain);
16198        }
16199        return sb.toString();
16200    }
16201
16202    // ------- apps on sdcard specific code -------
16203    static final boolean DEBUG_SD_INSTALL = false;
16204
16205    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16206
16207    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16208
16209    private boolean mMediaMounted = false;
16210
16211    static String getEncryptKey() {
16212        try {
16213            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16214                    SD_ENCRYPTION_KEYSTORE_NAME);
16215            if (sdEncKey == null) {
16216                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16217                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16218                if (sdEncKey == null) {
16219                    Slog.e(TAG, "Failed to create encryption keys");
16220                    return null;
16221                }
16222            }
16223            return sdEncKey;
16224        } catch (NoSuchAlgorithmException nsae) {
16225            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16226            return null;
16227        } catch (IOException ioe) {
16228            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16229            return null;
16230        }
16231    }
16232
16233    /*
16234     * Update media status on PackageManager.
16235     */
16236    @Override
16237    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16238        int callingUid = Binder.getCallingUid();
16239        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16240            throw new SecurityException("Media status can only be updated by the system");
16241        }
16242        // reader; this apparently protects mMediaMounted, but should probably
16243        // be a different lock in that case.
16244        synchronized (mPackages) {
16245            Log.i(TAG, "Updating external media status from "
16246                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16247                    + (mediaStatus ? "mounted" : "unmounted"));
16248            if (DEBUG_SD_INSTALL)
16249                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16250                        + ", mMediaMounted=" + mMediaMounted);
16251            if (mediaStatus == mMediaMounted) {
16252                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16253                        : 0, -1);
16254                mHandler.sendMessage(msg);
16255                return;
16256            }
16257            mMediaMounted = mediaStatus;
16258        }
16259        // Queue up an async operation since the package installation may take a
16260        // little while.
16261        mHandler.post(new Runnable() {
16262            public void run() {
16263                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16264            }
16265        });
16266    }
16267
16268    /**
16269     * Called by MountService when the initial ASECs to scan are available.
16270     * Should block until all the ASEC containers are finished being scanned.
16271     */
16272    public void scanAvailableAsecs() {
16273        updateExternalMediaStatusInner(true, false, false);
16274    }
16275
16276    /*
16277     * Collect information of applications on external media, map them against
16278     * existing containers and update information based on current mount status.
16279     * Please note that we always have to report status if reportStatus has been
16280     * set to true especially when unloading packages.
16281     */
16282    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16283            boolean externalStorage) {
16284        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16285        int[] uidArr = EmptyArray.INT;
16286
16287        final String[] list = PackageHelper.getSecureContainerList();
16288        if (ArrayUtils.isEmpty(list)) {
16289            Log.i(TAG, "No secure containers found");
16290        } else {
16291            // Process list of secure containers and categorize them
16292            // as active or stale based on their package internal state.
16293
16294            // reader
16295            synchronized (mPackages) {
16296                for (String cid : list) {
16297                    // Leave stages untouched for now; installer service owns them
16298                    if (PackageInstallerService.isStageName(cid)) continue;
16299
16300                    if (DEBUG_SD_INSTALL)
16301                        Log.i(TAG, "Processing container " + cid);
16302                    String pkgName = getAsecPackageName(cid);
16303                    if (pkgName == null) {
16304                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16305                        continue;
16306                    }
16307                    if (DEBUG_SD_INSTALL)
16308                        Log.i(TAG, "Looking for pkg : " + pkgName);
16309
16310                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16311                    if (ps == null) {
16312                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16313                        continue;
16314                    }
16315
16316                    /*
16317                     * Skip packages that are not external if we're unmounting
16318                     * external storage.
16319                     */
16320                    if (externalStorage && !isMounted && !isExternal(ps)) {
16321                        continue;
16322                    }
16323
16324                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16325                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16326                    // The package status is changed only if the code path
16327                    // matches between settings and the container id.
16328                    if (ps.codePathString != null
16329                            && ps.codePathString.startsWith(args.getCodePath())) {
16330                        if (DEBUG_SD_INSTALL) {
16331                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16332                                    + " at code path: " + ps.codePathString);
16333                        }
16334
16335                        // We do have a valid package installed on sdcard
16336                        processCids.put(args, ps.codePathString);
16337                        final int uid = ps.appId;
16338                        if (uid != -1) {
16339                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16340                        }
16341                    } else {
16342                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16343                                + ps.codePathString);
16344                    }
16345                }
16346            }
16347
16348            Arrays.sort(uidArr);
16349        }
16350
16351        // Process packages with valid entries.
16352        if (isMounted) {
16353            if (DEBUG_SD_INSTALL)
16354                Log.i(TAG, "Loading packages");
16355            loadMediaPackages(processCids, uidArr, externalStorage);
16356            startCleaningPackages();
16357            mInstallerService.onSecureContainersAvailable();
16358        } else {
16359            if (DEBUG_SD_INSTALL)
16360                Log.i(TAG, "Unloading packages");
16361            unloadMediaPackages(processCids, uidArr, reportStatus);
16362        }
16363    }
16364
16365    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16366            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16367        final int size = infos.size();
16368        final String[] packageNames = new String[size];
16369        final int[] packageUids = new int[size];
16370        for (int i = 0; i < size; i++) {
16371            final ApplicationInfo info = infos.get(i);
16372            packageNames[i] = info.packageName;
16373            packageUids[i] = info.uid;
16374        }
16375        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16376                finishedReceiver);
16377    }
16378
16379    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16380            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16381        sendResourcesChangedBroadcast(mediaStatus, replacing,
16382                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16383    }
16384
16385    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16386            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16387        int size = pkgList.length;
16388        if (size > 0) {
16389            // Send broadcasts here
16390            Bundle extras = new Bundle();
16391            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16392            if (uidArr != null) {
16393                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16394            }
16395            if (replacing) {
16396                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16397            }
16398            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16399                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16400            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16401        }
16402    }
16403
16404   /*
16405     * Look at potentially valid container ids from processCids If package
16406     * information doesn't match the one on record or package scanning fails,
16407     * the cid is added to list of removeCids. We currently don't delete stale
16408     * containers.
16409     */
16410    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16411            boolean externalStorage) {
16412        ArrayList<String> pkgList = new ArrayList<String>();
16413        Set<AsecInstallArgs> keys = processCids.keySet();
16414
16415        for (AsecInstallArgs args : keys) {
16416            String codePath = processCids.get(args);
16417            if (DEBUG_SD_INSTALL)
16418                Log.i(TAG, "Loading container : " + args.cid);
16419            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16420            try {
16421                // Make sure there are no container errors first.
16422                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16423                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16424                            + " when installing from sdcard");
16425                    continue;
16426                }
16427                // Check code path here.
16428                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16429                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16430                            + " does not match one in settings " + codePath);
16431                    continue;
16432                }
16433                // Parse package
16434                int parseFlags = mDefParseFlags;
16435                if (args.isExternalAsec()) {
16436                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16437                }
16438                if (args.isFwdLocked()) {
16439                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16440                }
16441
16442                synchronized (mInstallLock) {
16443                    PackageParser.Package pkg = null;
16444                    try {
16445                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16446                    } catch (PackageManagerException e) {
16447                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16448                    }
16449                    // Scan the package
16450                    if (pkg != null) {
16451                        /*
16452                         * TODO why is the lock being held? doPostInstall is
16453                         * called in other places without the lock. This needs
16454                         * to be straightened out.
16455                         */
16456                        // writer
16457                        synchronized (mPackages) {
16458                            retCode = PackageManager.INSTALL_SUCCEEDED;
16459                            pkgList.add(pkg.packageName);
16460                            // Post process args
16461                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16462                                    pkg.applicationInfo.uid);
16463                        }
16464                    } else {
16465                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16466                    }
16467                }
16468
16469            } finally {
16470                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16471                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16472                }
16473            }
16474        }
16475        // writer
16476        synchronized (mPackages) {
16477            // If the platform SDK has changed since the last time we booted,
16478            // we need to re-grant app permission to catch any new ones that
16479            // appear. This is really a hack, and means that apps can in some
16480            // cases get permissions that the user didn't initially explicitly
16481            // allow... it would be nice to have some better way to handle
16482            // this situation.
16483            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16484                    : mSettings.getInternalVersion();
16485            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16486                    : StorageManager.UUID_PRIVATE_INTERNAL;
16487
16488            int updateFlags = UPDATE_PERMISSIONS_ALL;
16489            if (ver.sdkVersion != mSdkVersion) {
16490                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16491                        + mSdkVersion + "; regranting permissions for external");
16492                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16493            }
16494            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16495
16496            // Yay, everything is now upgraded
16497            ver.forceCurrent();
16498
16499            // can downgrade to reader
16500            // Persist settings
16501            mSettings.writeLPr();
16502        }
16503        // Send a broadcast to let everyone know we are done processing
16504        if (pkgList.size() > 0) {
16505            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16506        }
16507    }
16508
16509   /*
16510     * Utility method to unload a list of specified containers
16511     */
16512    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16513        // Just unmount all valid containers.
16514        for (AsecInstallArgs arg : cidArgs) {
16515            synchronized (mInstallLock) {
16516                arg.doPostDeleteLI(false);
16517           }
16518       }
16519   }
16520
16521    /*
16522     * Unload packages mounted on external media. This involves deleting package
16523     * data from internal structures, sending broadcasts about diabled packages,
16524     * gc'ing to free up references, unmounting all secure containers
16525     * corresponding to packages on external media, and posting a
16526     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16527     * that we always have to post this message if status has been requested no
16528     * matter what.
16529     */
16530    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16531            final boolean reportStatus) {
16532        if (DEBUG_SD_INSTALL)
16533            Log.i(TAG, "unloading media packages");
16534        ArrayList<String> pkgList = new ArrayList<String>();
16535        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16536        final Set<AsecInstallArgs> keys = processCids.keySet();
16537        for (AsecInstallArgs args : keys) {
16538            String pkgName = args.getPackageName();
16539            if (DEBUG_SD_INSTALL)
16540                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16541            // Delete package internally
16542            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16543            synchronized (mInstallLock) {
16544                boolean res = deletePackageLI(pkgName, null, false, null, null,
16545                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16546                if (res) {
16547                    pkgList.add(pkgName);
16548                } else {
16549                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16550                    failedList.add(args);
16551                }
16552            }
16553        }
16554
16555        // reader
16556        synchronized (mPackages) {
16557            // We didn't update the settings after removing each package;
16558            // write them now for all packages.
16559            mSettings.writeLPr();
16560        }
16561
16562        // We have to absolutely send UPDATED_MEDIA_STATUS only
16563        // after confirming that all the receivers processed the ordered
16564        // broadcast when packages get disabled, force a gc to clean things up.
16565        // and unload all the containers.
16566        if (pkgList.size() > 0) {
16567            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16568                    new IIntentReceiver.Stub() {
16569                public void performReceive(Intent intent, int resultCode, String data,
16570                        Bundle extras, boolean ordered, boolean sticky,
16571                        int sendingUser) throws RemoteException {
16572                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16573                            reportStatus ? 1 : 0, 1, keys);
16574                    mHandler.sendMessage(msg);
16575                }
16576            });
16577        } else {
16578            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16579                    keys);
16580            mHandler.sendMessage(msg);
16581        }
16582    }
16583
16584    private void loadPrivatePackages(final VolumeInfo vol) {
16585        mHandler.post(new Runnable() {
16586            @Override
16587            public void run() {
16588                loadPrivatePackagesInner(vol);
16589            }
16590        });
16591    }
16592
16593    private void loadPrivatePackagesInner(VolumeInfo vol) {
16594        final String volumeUuid = vol.fsUuid;
16595        if (TextUtils.isEmpty(volumeUuid)) {
16596            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16597            return;
16598        }
16599
16600        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16601        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16602
16603        final VersionInfo ver;
16604        final List<PackageSetting> packages;
16605        synchronized (mPackages) {
16606            ver = mSettings.findOrCreateVersion(volumeUuid);
16607            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16608        }
16609
16610        // TODO: introduce a new concept similar to "frozen" to prevent these
16611        // apps from being launched until after data has been fully reconciled
16612        for (PackageSetting ps : packages) {
16613            synchronized (mInstallLock) {
16614                final PackageParser.Package pkg;
16615                try {
16616                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16617                    loaded.add(pkg.applicationInfo);
16618
16619                } catch (PackageManagerException e) {
16620                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16621                }
16622
16623                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16624                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16625                }
16626            }
16627        }
16628
16629        // Reconcile app data for all started/unlocked users
16630        final UserManager um = mContext.getSystemService(UserManager.class);
16631        for (UserInfo user : um.getUsers()) {
16632            if (um.isUserUnlocked(user.id)) {
16633                reconcileAppsData(volumeUuid, user.id,
16634                        Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE);
16635            } else if (um.isUserRunning(user.id)) {
16636                reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE);
16637            } else {
16638                continue;
16639            }
16640        }
16641
16642        synchronized (mPackages) {
16643            int updateFlags = UPDATE_PERMISSIONS_ALL;
16644            if (ver.sdkVersion != mSdkVersion) {
16645                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16646                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16647                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16648            }
16649            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16650
16651            // Yay, everything is now upgraded
16652            ver.forceCurrent();
16653
16654            mSettings.writeLPr();
16655        }
16656
16657        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16658        sendResourcesChangedBroadcast(true, false, loaded, null);
16659    }
16660
16661    private void unloadPrivatePackages(final VolumeInfo vol) {
16662        mHandler.post(new Runnable() {
16663            @Override
16664            public void run() {
16665                unloadPrivatePackagesInner(vol);
16666            }
16667        });
16668    }
16669
16670    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16671        final String volumeUuid = vol.fsUuid;
16672        if (TextUtils.isEmpty(volumeUuid)) {
16673            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16674            return;
16675        }
16676
16677        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16678        synchronized (mInstallLock) {
16679        synchronized (mPackages) {
16680            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16681            for (PackageSetting ps : packages) {
16682                if (ps.pkg == null) continue;
16683
16684                final ApplicationInfo info = ps.pkg.applicationInfo;
16685                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16686                if (deletePackageLI(ps.name, null, false, null, null,
16687                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16688                    unloaded.add(info);
16689                } else {
16690                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16691                }
16692            }
16693
16694            mSettings.writeLPr();
16695        }
16696        }
16697
16698        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16699        sendResourcesChangedBroadcast(false, false, unloaded, null);
16700    }
16701
16702    /**
16703     * Examine all users present on given mounted volume, and destroy data
16704     * belonging to users that are no longer valid, or whose user ID has been
16705     * recycled.
16706     */
16707    private void reconcileUsers(String volumeUuid) {
16708        final File[] files = FileUtils
16709                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16710        for (File file : files) {
16711            if (!file.isDirectory()) continue;
16712
16713            final int userId;
16714            final UserInfo info;
16715            try {
16716                userId = Integer.parseInt(file.getName());
16717                info = sUserManager.getUserInfo(userId);
16718            } catch (NumberFormatException e) {
16719                Slog.w(TAG, "Invalid user directory " + file);
16720                continue;
16721            }
16722
16723            boolean destroyUser = false;
16724            if (info == null) {
16725                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16726                        + " because no matching user was found");
16727                destroyUser = true;
16728            } else {
16729                try {
16730                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16731                } catch (IOException e) {
16732                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16733                            + " because we failed to enforce serial number: " + e);
16734                    destroyUser = true;
16735                }
16736            }
16737
16738            if (destroyUser) {
16739                synchronized (mInstallLock) {
16740                    try {
16741                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16742                    } catch (InstallerException e) {
16743                        Slog.w(TAG, "Failed to clean up user dirs", e);
16744                    }
16745                }
16746            }
16747        }
16748
16749        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16750        final UserManager um = mContext.getSystemService(UserManager.class);
16751        for (UserInfo user : um.getUsers()) {
16752            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16753            if (userDir.exists()) continue;
16754
16755            try {
16756                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16757                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16758            } catch (IOException e) {
16759                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16760            }
16761        }
16762    }
16763
16764    private void assertPackageKnown(String volumeUuid, String packageName)
16765            throws PackageManagerException {
16766        synchronized (mPackages) {
16767            final PackageSetting ps = mSettings.mPackages.get(packageName);
16768            if (ps == null) {
16769                throw new PackageManagerException("Package " + packageName + " is unknown");
16770            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16771                throw new PackageManagerException(
16772                        "Package " + packageName + " found on unknown volume " + volumeUuid
16773                                + "; expected volume " + ps.volumeUuid);
16774            }
16775        }
16776    }
16777
16778    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16779            throws PackageManagerException {
16780        synchronized (mPackages) {
16781            final PackageSetting ps = mSettings.mPackages.get(packageName);
16782            if (ps == null) {
16783                throw new PackageManagerException("Package " + packageName + " is unknown");
16784            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16785                throw new PackageManagerException(
16786                        "Package " + packageName + " found on unknown volume " + volumeUuid
16787                                + "; expected volume " + ps.volumeUuid);
16788            } else if (!ps.getInstalled(userId)) {
16789                throw new PackageManagerException(
16790                        "Package " + packageName + " not installed for user " + userId);
16791            }
16792        }
16793    }
16794
16795    /**
16796     * Examine all apps present on given mounted volume, and destroy apps that
16797     * aren't expected, either due to uninstallation or reinstallation on
16798     * another volume.
16799     */
16800    private void reconcileApps(String volumeUuid) {
16801        final File[] files = FileUtils
16802                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16803        for (File file : files) {
16804            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16805                    && !PackageInstallerService.isStageName(file.getName());
16806            if (!isPackage) {
16807                // Ignore entries which are not packages
16808                continue;
16809            }
16810
16811            try {
16812                final PackageLite pkg = PackageParser.parsePackageLite(file,
16813                        PackageParser.PARSE_MUST_BE_APK);
16814                assertPackageKnown(volumeUuid, pkg.packageName);
16815
16816            } catch (PackageParserException | PackageManagerException e) {
16817                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16818                synchronized (mInstallLock) {
16819                    removeCodePathLI(file);
16820                }
16821            }
16822        }
16823    }
16824
16825    /**
16826     * Reconcile all app data for the given user.
16827     * <p>
16828     * Verifies that directories exist and that ownership and labeling is
16829     * correct for all installed apps on all mounted volumes.
16830     */
16831    void reconcileAppsData(int userId, @StorageFlags int flags) {
16832        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16833        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16834            final String volumeUuid = vol.getFsUuid();
16835            reconcileAppsData(volumeUuid, userId, flags);
16836        }
16837    }
16838
16839    /**
16840     * Reconcile all app data on given mounted volume.
16841     * <p>
16842     * Destroys app data that isn't expected, either due to uninstallation or
16843     * reinstallation on another volume.
16844     * <p>
16845     * Verifies that directories exist and that ownership and labeling is
16846     * correct for all installed apps.
16847     */
16848    private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) {
16849        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
16850                + Integer.toHexString(flags));
16851
16852        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
16853        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
16854
16855        boolean restoreconNeeded = false;
16856
16857        // First look for stale data that doesn't belong, and check if things
16858        // have changed since we did our last restorecon
16859        if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16860            if (!isUserKeyUnlocked(userId)) {
16861                throw new RuntimeException(
16862                        "Yikes, someone asked us to reconcile CE storage while " + userId
16863                                + " was still locked; this would have caused massive data loss!");
16864            }
16865
16866            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
16867
16868            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
16869            for (File file : files) {
16870                final String packageName = file.getName();
16871                try {
16872                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16873                } catch (PackageManagerException e) {
16874                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16875                    synchronized (mInstallLock) {
16876                        destroyAppDataLI(volumeUuid, packageName, userId,
16877                                Installer.FLAG_CE_STORAGE);
16878                    }
16879                }
16880            }
16881        }
16882        if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16883            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
16884
16885            final File[] files = FileUtils.listFilesOrEmpty(deDir);
16886            for (File file : files) {
16887                final String packageName = file.getName();
16888                try {
16889                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16890                } catch (PackageManagerException e) {
16891                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16892                    synchronized (mInstallLock) {
16893                        destroyAppDataLI(volumeUuid, packageName, userId,
16894                                Installer.FLAG_DE_STORAGE);
16895                    }
16896                }
16897            }
16898        }
16899
16900        // Ensure that data directories are ready to roll for all packages
16901        // installed for this volume and user
16902        final List<PackageSetting> packages;
16903        synchronized (mPackages) {
16904            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16905        }
16906        int preparedCount = 0;
16907        for (PackageSetting ps : packages) {
16908            final String packageName = ps.name;
16909            if (ps.pkg == null) {
16910                Slog.w(TAG, "Odd, missing scanned package " + packageName);
16911                // TODO: might be due to legacy ASEC apps; we should circle back
16912                // and reconcile again once they're scanned
16913                continue;
16914            }
16915
16916            if (ps.getInstalled(userId)) {
16917                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
16918                preparedCount++;
16919            }
16920        }
16921
16922        if (restoreconNeeded) {
16923            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16924                SELinuxMMAC.setRestoreconDone(ceDir);
16925            }
16926            if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16927                SELinuxMMAC.setRestoreconDone(deDir);
16928            }
16929        }
16930
16931        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
16932                + " packages; restoreconNeeded was " + restoreconNeeded);
16933    }
16934
16935    /**
16936     * Prepare app data for the given app just after it was installed or
16937     * upgraded. This method carefully only touches users that it's installed
16938     * for, and it forces a restorecon to handle any seinfo changes.
16939     * <p>
16940     * Verifies that directories exist and that ownership and labeling is
16941     * correct for all installed apps. If there is an ownership mismatch, it
16942     * will try recovering system apps by wiping data; third-party app data is
16943     * left intact.
16944     */
16945    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
16946        final PackageSetting ps;
16947        synchronized (mPackages) {
16948            ps = mSettings.mPackages.get(pkg.packageName);
16949        }
16950
16951        final UserManager um = mContext.getSystemService(UserManager.class);
16952        for (UserInfo user : um.getUsers()) {
16953            final int flags;
16954            if (um.isUserUnlocked(user.id)) {
16955                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
16956            } else if (um.isUserRunning(user.id)) {
16957                flags = Installer.FLAG_DE_STORAGE;
16958            } else {
16959                continue;
16960            }
16961
16962            if (ps.getInstalled(user.id)) {
16963                // Whenever an app changes, force a restorecon of its data
16964                // TODO: when user data is locked, mark that we're still dirty
16965                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
16966            }
16967        }
16968    }
16969
16970    /**
16971     * Prepare app data for the given app.
16972     * <p>
16973     * Verifies that directories exist and that ownership and labeling is
16974     * correct for all installed apps. If there is an ownership mismatch, this
16975     * will try recovering system apps by wiping data; third-party app data is
16976     * left intact.
16977     */
16978    private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags,
16979            PackageParser.Package pkg, boolean restoreconNeeded) {
16980        if (DEBUG_APP_DATA) {
16981            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
16982                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
16983        }
16984
16985        final String packageName = pkg.packageName;
16986        final ApplicationInfo app = pkg.applicationInfo;
16987        final int appId = UserHandle.getAppId(app.uid);
16988
16989        Preconditions.checkNotNull(app.seinfo);
16990
16991        synchronized (mInstallLock) {
16992            try {
16993                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
16994                        appId, app.seinfo);
16995            } catch (InstallerException e) {
16996                if (app.isSystemApp()) {
16997                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
16998                            + ", but trying to recover: " + e);
16999                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17000                    try {
17001                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17002                                appId, app.seinfo);
17003                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17004                    } catch (InstallerException e2) {
17005                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17006                    }
17007                } else {
17008                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17009                }
17010            }
17011
17012            if (restoreconNeeded) {
17013                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17014            }
17015
17016            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17017                // Create a native library symlink only if we have native libraries
17018                // and if the native libraries are 32 bit libraries. We do not provide
17019                // this symlink for 64 bit libraries.
17020                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17021                    final String nativeLibPath = app.nativeLibraryDir;
17022                    try {
17023                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17024                                nativeLibPath, userId);
17025                    } catch (InstallerException e) {
17026                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17027                    }
17028                }
17029            }
17030        }
17031    }
17032
17033    private void unfreezePackage(String packageName) {
17034        synchronized (mPackages) {
17035            final PackageSetting ps = mSettings.mPackages.get(packageName);
17036            if (ps != null) {
17037                ps.frozen = false;
17038            }
17039        }
17040    }
17041
17042    @Override
17043    public int movePackage(final String packageName, final String volumeUuid) {
17044        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17045
17046        final int moveId = mNextMoveId.getAndIncrement();
17047        mHandler.post(new Runnable() {
17048            @Override
17049            public void run() {
17050                try {
17051                    movePackageInternal(packageName, volumeUuid, moveId);
17052                } catch (PackageManagerException e) {
17053                    Slog.w(TAG, "Failed to move " + packageName, e);
17054                    mMoveCallbacks.notifyStatusChanged(moveId,
17055                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17056                }
17057            }
17058        });
17059        return moveId;
17060    }
17061
17062    private void movePackageInternal(final String packageName, final String volumeUuid,
17063            final int moveId) throws PackageManagerException {
17064        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17065        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17066        final PackageManager pm = mContext.getPackageManager();
17067
17068        final boolean currentAsec;
17069        final String currentVolumeUuid;
17070        final File codeFile;
17071        final String installerPackageName;
17072        final String packageAbiOverride;
17073        final int appId;
17074        final String seinfo;
17075        final String label;
17076
17077        // reader
17078        synchronized (mPackages) {
17079            final PackageParser.Package pkg = mPackages.get(packageName);
17080            final PackageSetting ps = mSettings.mPackages.get(packageName);
17081            if (pkg == null || ps == null) {
17082                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17083            }
17084
17085            if (pkg.applicationInfo.isSystemApp()) {
17086                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17087                        "Cannot move system application");
17088            }
17089
17090            if (pkg.applicationInfo.isExternalAsec()) {
17091                currentAsec = true;
17092                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17093            } else if (pkg.applicationInfo.isForwardLocked()) {
17094                currentAsec = true;
17095                currentVolumeUuid = "forward_locked";
17096            } else {
17097                currentAsec = false;
17098                currentVolumeUuid = ps.volumeUuid;
17099
17100                final File probe = new File(pkg.codePath);
17101                final File probeOat = new File(probe, "oat");
17102                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17103                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17104                            "Move only supported for modern cluster style installs");
17105                }
17106            }
17107
17108            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17109                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17110                        "Package already moved to " + volumeUuid);
17111            }
17112
17113            if (ps.frozen) {
17114                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17115                        "Failed to move already frozen package");
17116            }
17117            ps.frozen = true;
17118
17119            codeFile = new File(pkg.codePath);
17120            installerPackageName = ps.installerPackageName;
17121            packageAbiOverride = ps.cpuAbiOverrideString;
17122            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17123            seinfo = pkg.applicationInfo.seinfo;
17124            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17125        }
17126
17127        // Now that we're guarded by frozen state, kill app during move
17128        final long token = Binder.clearCallingIdentity();
17129        try {
17130            killApplication(packageName, appId, "move pkg");
17131        } finally {
17132            Binder.restoreCallingIdentity(token);
17133        }
17134
17135        final Bundle extras = new Bundle();
17136        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17137        extras.putString(Intent.EXTRA_TITLE, label);
17138        mMoveCallbacks.notifyCreated(moveId, extras);
17139
17140        int installFlags;
17141        final boolean moveCompleteApp;
17142        final File measurePath;
17143
17144        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17145            installFlags = INSTALL_INTERNAL;
17146            moveCompleteApp = !currentAsec;
17147            measurePath = Environment.getDataAppDirectory(volumeUuid);
17148        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17149            installFlags = INSTALL_EXTERNAL;
17150            moveCompleteApp = false;
17151            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17152        } else {
17153            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17154            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17155                    || !volume.isMountedWritable()) {
17156                unfreezePackage(packageName);
17157                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17158                        "Move location not mounted private volume");
17159            }
17160
17161            Preconditions.checkState(!currentAsec);
17162
17163            installFlags = INSTALL_INTERNAL;
17164            moveCompleteApp = true;
17165            measurePath = Environment.getDataAppDirectory(volumeUuid);
17166        }
17167
17168        final PackageStats stats = new PackageStats(null, -1);
17169        synchronized (mInstaller) {
17170            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17171                unfreezePackage(packageName);
17172                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17173                        "Failed to measure package size");
17174            }
17175        }
17176
17177        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17178                + stats.dataSize);
17179
17180        final long startFreeBytes = measurePath.getFreeSpace();
17181        final long sizeBytes;
17182        if (moveCompleteApp) {
17183            sizeBytes = stats.codeSize + stats.dataSize;
17184        } else {
17185            sizeBytes = stats.codeSize;
17186        }
17187
17188        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17189            unfreezePackage(packageName);
17190            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17191                    "Not enough free space to move");
17192        }
17193
17194        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17195
17196        final CountDownLatch installedLatch = new CountDownLatch(1);
17197        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17198            @Override
17199            public void onUserActionRequired(Intent intent) throws RemoteException {
17200                throw new IllegalStateException();
17201            }
17202
17203            @Override
17204            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17205                    Bundle extras) throws RemoteException {
17206                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17207                        + PackageManager.installStatusToString(returnCode, msg));
17208
17209                installedLatch.countDown();
17210
17211                // Regardless of success or failure of the move operation,
17212                // always unfreeze the package
17213                unfreezePackage(packageName);
17214
17215                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17216                switch (status) {
17217                    case PackageInstaller.STATUS_SUCCESS:
17218                        mMoveCallbacks.notifyStatusChanged(moveId,
17219                                PackageManager.MOVE_SUCCEEDED);
17220                        break;
17221                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17222                        mMoveCallbacks.notifyStatusChanged(moveId,
17223                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17224                        break;
17225                    default:
17226                        mMoveCallbacks.notifyStatusChanged(moveId,
17227                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17228                        break;
17229                }
17230            }
17231        };
17232
17233        final MoveInfo move;
17234        if (moveCompleteApp) {
17235            // Kick off a thread to report progress estimates
17236            new Thread() {
17237                @Override
17238                public void run() {
17239                    while (true) {
17240                        try {
17241                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17242                                break;
17243                            }
17244                        } catch (InterruptedException ignored) {
17245                        }
17246
17247                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17248                        final int progress = 10 + (int) MathUtils.constrain(
17249                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17250                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17251                    }
17252                }
17253            }.start();
17254
17255            final String dataAppName = codeFile.getName();
17256            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17257                    dataAppName, appId, seinfo);
17258        } else {
17259            move = null;
17260        }
17261
17262        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17263
17264        final Message msg = mHandler.obtainMessage(INIT_COPY);
17265        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17266        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17267                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17268        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17269        msg.obj = params;
17270
17271        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17272                System.identityHashCode(msg.obj));
17273        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17274                System.identityHashCode(msg.obj));
17275
17276        mHandler.sendMessage(msg);
17277    }
17278
17279    @Override
17280    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17281        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17282
17283        final int realMoveId = mNextMoveId.getAndIncrement();
17284        final Bundle extras = new Bundle();
17285        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17286        mMoveCallbacks.notifyCreated(realMoveId, extras);
17287
17288        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17289            @Override
17290            public void onCreated(int moveId, Bundle extras) {
17291                // Ignored
17292            }
17293
17294            @Override
17295            public void onStatusChanged(int moveId, int status, long estMillis) {
17296                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17297            }
17298        };
17299
17300        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17301        storage.setPrimaryStorageUuid(volumeUuid, callback);
17302        return realMoveId;
17303    }
17304
17305    @Override
17306    public int getMoveStatus(int moveId) {
17307        mContext.enforceCallingOrSelfPermission(
17308                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17309        return mMoveCallbacks.mLastStatus.get(moveId);
17310    }
17311
17312    @Override
17313    public void registerMoveCallback(IPackageMoveObserver callback) {
17314        mContext.enforceCallingOrSelfPermission(
17315                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17316        mMoveCallbacks.register(callback);
17317    }
17318
17319    @Override
17320    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17321        mContext.enforceCallingOrSelfPermission(
17322                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17323        mMoveCallbacks.unregister(callback);
17324    }
17325
17326    @Override
17327    public boolean setInstallLocation(int loc) {
17328        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17329                null);
17330        if (getInstallLocation() == loc) {
17331            return true;
17332        }
17333        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17334                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17335            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17336                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17337            return true;
17338        }
17339        return false;
17340   }
17341
17342    @Override
17343    public int getInstallLocation() {
17344        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17345                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17346                PackageHelper.APP_INSTALL_AUTO);
17347    }
17348
17349    /** Called by UserManagerService */
17350    void cleanUpUser(UserManagerService userManager, int userHandle) {
17351        synchronized (mPackages) {
17352            mDirtyUsers.remove(userHandle);
17353            mUserNeedsBadging.delete(userHandle);
17354            mSettings.removeUserLPw(userHandle);
17355            mPendingBroadcasts.remove(userHandle);
17356            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17357        }
17358        synchronized (mInstallLock) {
17359            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17360            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17361                final String volumeUuid = vol.getFsUuid();
17362                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17363                try {
17364                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17365                } catch (InstallerException e) {
17366                    Slog.w(TAG, "Failed to remove user data", e);
17367                }
17368            }
17369            synchronized (mPackages) {
17370                removeUnusedPackagesLILPw(userManager, userHandle);
17371            }
17372        }
17373    }
17374
17375    /**
17376     * We're removing userHandle and would like to remove any downloaded packages
17377     * that are no longer in use by any other user.
17378     * @param userHandle the user being removed
17379     */
17380    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17381        final boolean DEBUG_CLEAN_APKS = false;
17382        int [] users = userManager.getUserIds();
17383        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17384        while (psit.hasNext()) {
17385            PackageSetting ps = psit.next();
17386            if (ps.pkg == null) {
17387                continue;
17388            }
17389            final String packageName = ps.pkg.packageName;
17390            // Skip over if system app
17391            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17392                continue;
17393            }
17394            if (DEBUG_CLEAN_APKS) {
17395                Slog.i(TAG, "Checking package " + packageName);
17396            }
17397            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17398            if (keep) {
17399                if (DEBUG_CLEAN_APKS) {
17400                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17401                }
17402            } else {
17403                for (int i = 0; i < users.length; i++) {
17404                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17405                        keep = true;
17406                        if (DEBUG_CLEAN_APKS) {
17407                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17408                                    + users[i]);
17409                        }
17410                        break;
17411                    }
17412                }
17413            }
17414            if (!keep) {
17415                if (DEBUG_CLEAN_APKS) {
17416                    Slog.i(TAG, "  Removing package " + packageName);
17417                }
17418                mHandler.post(new Runnable() {
17419                    public void run() {
17420                        deletePackageX(packageName, userHandle, 0);
17421                    } //end run
17422                });
17423            }
17424        }
17425    }
17426
17427    /** Called by UserManagerService */
17428    void createNewUser(int userHandle) {
17429        synchronized (mInstallLock) {
17430            try {
17431                mInstaller.createUserConfig(userHandle);
17432            } catch (InstallerException e) {
17433                Slog.w(TAG, "Failed to create user config", e);
17434            }
17435            mSettings.createNewUserLI(this, mInstaller, userHandle);
17436        }
17437        synchronized (mPackages) {
17438            applyFactoryDefaultBrowserLPw(userHandle);
17439            primeDomainVerificationsLPw(userHandle);
17440        }
17441    }
17442
17443    void newUserCreated(final int userHandle) {
17444        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17445        // If permission review for legacy apps is required, we represent
17446        // dagerous permissions for such apps as always granted runtime
17447        // permissions to keep per user flag state whether review is needed.
17448        // Hence, if a new user is added we have to propagate dangerous
17449        // permission grants for these legacy apps.
17450        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17451            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17452                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17453        }
17454    }
17455
17456    @Override
17457    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17458        mContext.enforceCallingOrSelfPermission(
17459                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17460                "Only package verification agents can read the verifier device identity");
17461
17462        synchronized (mPackages) {
17463            return mSettings.getVerifierDeviceIdentityLPw();
17464        }
17465    }
17466
17467    @Override
17468    public void setPermissionEnforced(String permission, boolean enforced) {
17469        // TODO: Now that we no longer change GID for storage, this should to away.
17470        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17471                "setPermissionEnforced");
17472        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17473            synchronized (mPackages) {
17474                if (mSettings.mReadExternalStorageEnforced == null
17475                        || mSettings.mReadExternalStorageEnforced != enforced) {
17476                    mSettings.mReadExternalStorageEnforced = enforced;
17477                    mSettings.writeLPr();
17478                }
17479            }
17480            // kill any non-foreground processes so we restart them and
17481            // grant/revoke the GID.
17482            final IActivityManager am = ActivityManagerNative.getDefault();
17483            if (am != null) {
17484                final long token = Binder.clearCallingIdentity();
17485                try {
17486                    am.killProcessesBelowForeground("setPermissionEnforcement");
17487                } catch (RemoteException e) {
17488                } finally {
17489                    Binder.restoreCallingIdentity(token);
17490                }
17491            }
17492        } else {
17493            throw new IllegalArgumentException("No selective enforcement for " + permission);
17494        }
17495    }
17496
17497    @Override
17498    @Deprecated
17499    public boolean isPermissionEnforced(String permission) {
17500        return true;
17501    }
17502
17503    @Override
17504    public boolean isStorageLow() {
17505        final long token = Binder.clearCallingIdentity();
17506        try {
17507            final DeviceStorageMonitorInternal
17508                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17509            if (dsm != null) {
17510                return dsm.isMemoryLow();
17511            } else {
17512                return false;
17513            }
17514        } finally {
17515            Binder.restoreCallingIdentity(token);
17516        }
17517    }
17518
17519    @Override
17520    public IPackageInstaller getPackageInstaller() {
17521        return mInstallerService;
17522    }
17523
17524    private boolean userNeedsBadging(int userId) {
17525        int index = mUserNeedsBadging.indexOfKey(userId);
17526        if (index < 0) {
17527            final UserInfo userInfo;
17528            final long token = Binder.clearCallingIdentity();
17529            try {
17530                userInfo = sUserManager.getUserInfo(userId);
17531            } finally {
17532                Binder.restoreCallingIdentity(token);
17533            }
17534            final boolean b;
17535            if (userInfo != null && userInfo.isManagedProfile()) {
17536                b = true;
17537            } else {
17538                b = false;
17539            }
17540            mUserNeedsBadging.put(userId, b);
17541            return b;
17542        }
17543        return mUserNeedsBadging.valueAt(index);
17544    }
17545
17546    @Override
17547    public KeySet getKeySetByAlias(String packageName, String alias) {
17548        if (packageName == null || alias == null) {
17549            return null;
17550        }
17551        synchronized(mPackages) {
17552            final PackageParser.Package pkg = mPackages.get(packageName);
17553            if (pkg == null) {
17554                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17555                throw new IllegalArgumentException("Unknown package: " + packageName);
17556            }
17557            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17558            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17559        }
17560    }
17561
17562    @Override
17563    public KeySet getSigningKeySet(String packageName) {
17564        if (packageName == null) {
17565            return null;
17566        }
17567        synchronized(mPackages) {
17568            final PackageParser.Package pkg = mPackages.get(packageName);
17569            if (pkg == null) {
17570                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17571                throw new IllegalArgumentException("Unknown package: " + packageName);
17572            }
17573            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17574                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17575                throw new SecurityException("May not access signing KeySet of other apps.");
17576            }
17577            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17578            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17579        }
17580    }
17581
17582    @Override
17583    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17584        if (packageName == null || ks == null) {
17585            return false;
17586        }
17587        synchronized(mPackages) {
17588            final PackageParser.Package pkg = mPackages.get(packageName);
17589            if (pkg == null) {
17590                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17591                throw new IllegalArgumentException("Unknown package: " + packageName);
17592            }
17593            IBinder ksh = ks.getToken();
17594            if (ksh instanceof KeySetHandle) {
17595                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17596                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17597            }
17598            return false;
17599        }
17600    }
17601
17602    @Override
17603    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17604        if (packageName == null || ks == null) {
17605            return false;
17606        }
17607        synchronized(mPackages) {
17608            final PackageParser.Package pkg = mPackages.get(packageName);
17609            if (pkg == null) {
17610                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17611                throw new IllegalArgumentException("Unknown package: " + packageName);
17612            }
17613            IBinder ksh = ks.getToken();
17614            if (ksh instanceof KeySetHandle) {
17615                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17616                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17617            }
17618            return false;
17619        }
17620    }
17621
17622    private void deletePackageIfUnusedLPr(final String packageName) {
17623        PackageSetting ps = mSettings.mPackages.get(packageName);
17624        if (ps == null) {
17625            return;
17626        }
17627        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17628            // TODO Implement atomic delete if package is unused
17629            // It is currently possible that the package will be deleted even if it is installed
17630            // after this method returns.
17631            mHandler.post(new Runnable() {
17632                public void run() {
17633                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17634                }
17635            });
17636        }
17637    }
17638
17639    /**
17640     * Check and throw if the given before/after packages would be considered a
17641     * downgrade.
17642     */
17643    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17644            throws PackageManagerException {
17645        if (after.versionCode < before.mVersionCode) {
17646            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17647                    "Update version code " + after.versionCode + " is older than current "
17648                    + before.mVersionCode);
17649        } else if (after.versionCode == before.mVersionCode) {
17650            if (after.baseRevisionCode < before.baseRevisionCode) {
17651                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17652                        "Update base revision code " + after.baseRevisionCode
17653                        + " is older than current " + before.baseRevisionCode);
17654            }
17655
17656            if (!ArrayUtils.isEmpty(after.splitNames)) {
17657                for (int i = 0; i < after.splitNames.length; i++) {
17658                    final String splitName = after.splitNames[i];
17659                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17660                    if (j != -1) {
17661                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17662                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17663                                    "Update split " + splitName + " revision code "
17664                                    + after.splitRevisionCodes[i] + " is older than current "
17665                                    + before.splitRevisionCodes[j]);
17666                        }
17667                    }
17668                }
17669            }
17670        }
17671    }
17672
17673    private static class MoveCallbacks extends Handler {
17674        private static final int MSG_CREATED = 1;
17675        private static final int MSG_STATUS_CHANGED = 2;
17676
17677        private final RemoteCallbackList<IPackageMoveObserver>
17678                mCallbacks = new RemoteCallbackList<>();
17679
17680        private final SparseIntArray mLastStatus = new SparseIntArray();
17681
17682        public MoveCallbacks(Looper looper) {
17683            super(looper);
17684        }
17685
17686        public void register(IPackageMoveObserver callback) {
17687            mCallbacks.register(callback);
17688        }
17689
17690        public void unregister(IPackageMoveObserver callback) {
17691            mCallbacks.unregister(callback);
17692        }
17693
17694        @Override
17695        public void handleMessage(Message msg) {
17696            final SomeArgs args = (SomeArgs) msg.obj;
17697            final int n = mCallbacks.beginBroadcast();
17698            for (int i = 0; i < n; i++) {
17699                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17700                try {
17701                    invokeCallback(callback, msg.what, args);
17702                } catch (RemoteException ignored) {
17703                }
17704            }
17705            mCallbacks.finishBroadcast();
17706            args.recycle();
17707        }
17708
17709        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17710                throws RemoteException {
17711            switch (what) {
17712                case MSG_CREATED: {
17713                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17714                    break;
17715                }
17716                case MSG_STATUS_CHANGED: {
17717                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17718                    break;
17719                }
17720            }
17721        }
17722
17723        private void notifyCreated(int moveId, Bundle extras) {
17724            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17725
17726            final SomeArgs args = SomeArgs.obtain();
17727            args.argi1 = moveId;
17728            args.arg2 = extras;
17729            obtainMessage(MSG_CREATED, args).sendToTarget();
17730        }
17731
17732        private void notifyStatusChanged(int moveId, int status) {
17733            notifyStatusChanged(moveId, status, -1);
17734        }
17735
17736        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17737            Slog.v(TAG, "Move " + moveId + " status " + status);
17738
17739            final SomeArgs args = SomeArgs.obtain();
17740            args.argi1 = moveId;
17741            args.argi2 = status;
17742            args.arg3 = estMillis;
17743            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17744
17745            synchronized (mLastStatus) {
17746                mLastStatus.put(moveId, status);
17747            }
17748        }
17749    }
17750
17751    private final static class OnPermissionChangeListeners extends Handler {
17752        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17753
17754        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17755                new RemoteCallbackList<>();
17756
17757        public OnPermissionChangeListeners(Looper looper) {
17758            super(looper);
17759        }
17760
17761        @Override
17762        public void handleMessage(Message msg) {
17763            switch (msg.what) {
17764                case MSG_ON_PERMISSIONS_CHANGED: {
17765                    final int uid = msg.arg1;
17766                    handleOnPermissionsChanged(uid);
17767                } break;
17768            }
17769        }
17770
17771        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17772            mPermissionListeners.register(listener);
17773
17774        }
17775
17776        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17777            mPermissionListeners.unregister(listener);
17778        }
17779
17780        public void onPermissionsChanged(int uid) {
17781            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17782                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17783            }
17784        }
17785
17786        private void handleOnPermissionsChanged(int uid) {
17787            final int count = mPermissionListeners.beginBroadcast();
17788            try {
17789                for (int i = 0; i < count; i++) {
17790                    IOnPermissionsChangeListener callback = mPermissionListeners
17791                            .getBroadcastItem(i);
17792                    try {
17793                        callback.onPermissionsChanged(uid);
17794                    } catch (RemoteException e) {
17795                        Log.e(TAG, "Permission listener is dead", e);
17796                    }
17797                }
17798            } finally {
17799                mPermissionListeners.finishBroadcast();
17800            }
17801        }
17802    }
17803
17804    private class PackageManagerInternalImpl extends PackageManagerInternal {
17805        @Override
17806        public void setLocationPackagesProvider(PackagesProvider provider) {
17807            synchronized (mPackages) {
17808                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17809            }
17810        }
17811
17812        @Override
17813        public void setImePackagesProvider(PackagesProvider provider) {
17814            synchronized (mPackages) {
17815                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17816            }
17817        }
17818
17819        @Override
17820        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17821            synchronized (mPackages) {
17822                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17823            }
17824        }
17825
17826        @Override
17827        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17828            synchronized (mPackages) {
17829                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17830            }
17831        }
17832
17833        @Override
17834        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17835            synchronized (mPackages) {
17836                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17837            }
17838        }
17839
17840        @Override
17841        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17842            synchronized (mPackages) {
17843                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17844            }
17845        }
17846
17847        @Override
17848        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17849            synchronized (mPackages) {
17850                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17851            }
17852        }
17853
17854        @Override
17855        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17856            synchronized (mPackages) {
17857                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17858                        packageName, userId);
17859            }
17860        }
17861
17862        @Override
17863        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17864            synchronized (mPackages) {
17865                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17866                        packageName, userId);
17867            }
17868        }
17869
17870        @Override
17871        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17872            synchronized (mPackages) {
17873                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17874                        packageName, userId);
17875            }
17876        }
17877
17878        @Override
17879        public void setKeepUninstalledPackages(final List<String> packageList) {
17880            Preconditions.checkNotNull(packageList);
17881            List<String> removedFromList = null;
17882            synchronized (mPackages) {
17883                if (mKeepUninstalledPackages != null) {
17884                    final int packagesCount = mKeepUninstalledPackages.size();
17885                    for (int i = 0; i < packagesCount; i++) {
17886                        String oldPackage = mKeepUninstalledPackages.get(i);
17887                        if (packageList != null && packageList.contains(oldPackage)) {
17888                            continue;
17889                        }
17890                        if (removedFromList == null) {
17891                            removedFromList = new ArrayList<>();
17892                        }
17893                        removedFromList.add(oldPackage);
17894                    }
17895                }
17896                mKeepUninstalledPackages = new ArrayList<>(packageList);
17897                if (removedFromList != null) {
17898                    final int removedCount = removedFromList.size();
17899                    for (int i = 0; i < removedCount; i++) {
17900                        deletePackageIfUnusedLPr(removedFromList.get(i));
17901                    }
17902                }
17903            }
17904        }
17905
17906        @Override
17907        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17908            synchronized (mPackages) {
17909                // If we do not support permission review, done.
17910                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17911                    return false;
17912                }
17913
17914                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17915                if (packageSetting == null) {
17916                    return false;
17917                }
17918
17919                // Permission review applies only to apps not supporting the new permission model.
17920                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17921                    return false;
17922                }
17923
17924                // Legacy apps have the permission and get user consent on launch.
17925                PermissionsState permissionsState = packageSetting.getPermissionsState();
17926                return permissionsState.isPermissionReviewRequired(userId);
17927            }
17928        }
17929    }
17930
17931    @Override
17932    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17933        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17934        synchronized (mPackages) {
17935            final long identity = Binder.clearCallingIdentity();
17936            try {
17937                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17938                        packageNames, userId);
17939            } finally {
17940                Binder.restoreCallingIdentity(identity);
17941            }
17942        }
17943    }
17944
17945    private static void enforceSystemOrPhoneCaller(String tag) {
17946        int callingUid = Binder.getCallingUid();
17947        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17948            throw new SecurityException(
17949                    "Cannot call " + tag + " from UID " + callingUid);
17950        }
17951    }
17952}
17953