PackageManagerService.java revision 69d5ebc59e3cbc9c394906a95dc4b9bdc3355c08
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
62import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
63import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
64import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
65import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
66import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
67import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
68import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
69import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
70import static android.content.pm.PackageManager.PERMISSION_DENIED;
71import static android.content.pm.PackageManager.PERMISSION_GRANTED;
72import static android.content.pm.PackageParser.isApkFile;
73import static android.os.Process.PACKAGE_INFO_GID;
74import static android.os.Process.SYSTEM_UID;
75import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
76import static android.system.OsConstants.O_CREAT;
77import static android.system.OsConstants.O_RDWR;
78import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
80import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
81import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
82import static com.android.internal.util.ArrayUtils.appendInt;
83import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
84import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
85import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
87import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
88import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
89import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
92
93import android.Manifest;
94import android.annotation.NonNull;
95import android.annotation.Nullable;
96import android.app.ActivityManager;
97import android.app.ActivityManagerNative;
98import android.app.AppGlobals;
99import android.app.IActivityManager;
100import android.app.admin.IDevicePolicyManager;
101import android.app.backup.IBackupManager;
102import android.content.BroadcastReceiver;
103import android.content.ComponentName;
104import android.content.Context;
105import android.content.IIntentReceiver;
106import android.content.Intent;
107import android.content.IntentFilter;
108import android.content.IntentSender;
109import android.content.IntentSender.SendIntentException;
110import android.content.ServiceConnection;
111import android.content.pm.ActivityInfo;
112import android.content.pm.ApplicationInfo;
113import android.content.pm.AppsQueryHelper;
114import android.content.pm.ComponentInfo;
115import android.content.pm.EphemeralApplicationInfo;
116import android.content.pm.EphemeralResolveInfo;
117import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
118import android.content.pm.FeatureInfo;
119import android.content.pm.IOnPermissionsChangeListener;
120import android.content.pm.IPackageDataObserver;
121import android.content.pm.IPackageDeleteObserver;
122import android.content.pm.IPackageDeleteObserver2;
123import android.content.pm.IPackageInstallObserver2;
124import android.content.pm.IPackageInstaller;
125import android.content.pm.IPackageManager;
126import android.content.pm.IPackageMoveObserver;
127import android.content.pm.IPackageStatsObserver;
128import android.content.pm.InstrumentationInfo;
129import android.content.pm.IntentFilterVerificationInfo;
130import android.content.pm.KeySet;
131import android.content.pm.PackageCleanItem;
132import android.content.pm.PackageInfo;
133import android.content.pm.PackageInfoLite;
134import android.content.pm.PackageInstaller;
135import android.content.pm.PackageManager;
136import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
137import android.content.pm.PackageManagerInternal;
138import android.content.pm.PackageParser;
139import android.content.pm.PackageParser.ActivityIntentInfo;
140import android.content.pm.PackageParser.PackageLite;
141import android.content.pm.PackageParser.PackageParserException;
142import android.content.pm.PackageStats;
143import android.content.pm.PackageUserState;
144import android.content.pm.ParceledListSlice;
145import android.content.pm.PermissionGroupInfo;
146import android.content.pm.PermissionInfo;
147import android.content.pm.ProviderInfo;
148import android.content.pm.ResolveInfo;
149import android.content.pm.ServiceInfo;
150import android.content.pm.Signature;
151import android.content.pm.UserInfo;
152import android.content.pm.VerificationParams;
153import android.content.pm.VerifierDeviceIdentity;
154import android.content.pm.VerifierInfo;
155import android.content.res.Resources;
156import android.graphics.Bitmap;
157import android.hardware.display.DisplayManager;
158import android.net.Uri;
159import android.os.Binder;
160import android.os.Build;
161import android.os.Bundle;
162import android.os.Debug;
163import android.os.Environment;
164import android.os.Environment.UserEnvironment;
165import android.os.FileUtils;
166import android.os.Handler;
167import android.os.IBinder;
168import android.os.Looper;
169import android.os.Message;
170import android.os.Parcel;
171import android.os.ParcelFileDescriptor;
172import android.os.Process;
173import android.os.RemoteCallbackList;
174import android.os.RemoteException;
175import android.os.ResultReceiver;
176import android.os.SELinux;
177import android.os.ServiceManager;
178import android.os.SystemClock;
179import android.os.SystemProperties;
180import android.os.Trace;
181import android.os.UserHandle;
182import android.os.UserManager;
183import android.os.storage.IMountService;
184import android.os.storage.MountServiceInternal;
185import android.os.storage.StorageEventListener;
186import android.os.storage.StorageManager;
187import android.os.storage.VolumeInfo;
188import android.os.storage.VolumeRecord;
189import android.security.KeyStore;
190import android.security.SystemKeyStore;
191import android.system.ErrnoException;
192import android.system.Os;
193import android.text.TextUtils;
194import android.text.format.DateUtils;
195import android.util.ArrayMap;
196import android.util.ArraySet;
197import android.util.AtomicFile;
198import android.util.DisplayMetrics;
199import android.util.EventLog;
200import android.util.ExceptionUtils;
201import android.util.Log;
202import android.util.LogPrinter;
203import android.util.MathUtils;
204import android.util.PrintStreamPrinter;
205import android.util.Slog;
206import android.util.SparseArray;
207import android.util.SparseBooleanArray;
208import android.util.SparseIntArray;
209import android.util.Xml;
210import android.view.Display;
211
212import com.android.internal.R;
213import com.android.internal.annotations.GuardedBy;
214import com.android.internal.app.IMediaContainerService;
215import com.android.internal.app.ResolverActivity;
216import com.android.internal.content.NativeLibraryHelper;
217import com.android.internal.content.PackageHelper;
218import com.android.internal.os.IParcelFileDescriptorFactory;
219import com.android.internal.os.InstallerConnection.InstallerException;
220import com.android.internal.os.SomeArgs;
221import com.android.internal.os.Zygote;
222import com.android.internal.util.ArrayUtils;
223import com.android.internal.util.FastPrintWriter;
224import com.android.internal.util.FastXmlSerializer;
225import com.android.internal.util.IndentingPrintWriter;
226import com.android.internal.util.Preconditions;
227import com.android.internal.util.XmlUtils;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.Installer.StorageFlags;
236import com.android.server.pm.PermissionsState.PermissionState;
237import com.android.server.pm.Settings.DatabaseVersion;
238import com.android.server.pm.Settings.VersionInfo;
239import com.android.server.storage.DeviceStorageMonitorInternal;
240
241import dalvik.system.DexFile;
242import dalvik.system.VMRuntime;
243
244import libcore.io.IoUtils;
245import libcore.util.EmptyArray;
246
247import org.xmlpull.v1.XmlPullParser;
248import org.xmlpull.v1.XmlPullParserException;
249import org.xmlpull.v1.XmlSerializer;
250
251import java.io.BufferedInputStream;
252import java.io.BufferedOutputStream;
253import java.io.BufferedReader;
254import java.io.ByteArrayInputStream;
255import java.io.ByteArrayOutputStream;
256import java.io.File;
257import java.io.FileDescriptor;
258import java.io.FileNotFoundException;
259import java.io.FileOutputStream;
260import java.io.FileReader;
261import java.io.FilenameFilter;
262import java.io.IOException;
263import java.io.InputStream;
264import java.io.PrintWriter;
265import java.nio.charset.StandardCharsets;
266import java.security.MessageDigest;
267import java.security.NoSuchAlgorithmException;
268import java.security.PublicKey;
269import java.security.cert.CertificateEncodingException;
270import java.security.cert.CertificateException;
271import java.text.SimpleDateFormat;
272import java.util.ArrayList;
273import java.util.Arrays;
274import java.util.Collection;
275import java.util.Collections;
276import java.util.Comparator;
277import java.util.Date;
278import java.util.Iterator;
279import java.util.List;
280import java.util.Map;
281import java.util.Objects;
282import java.util.Set;
283import java.util.concurrent.CountDownLatch;
284import java.util.concurrent.TimeUnit;
285import java.util.concurrent.atomic.AtomicBoolean;
286import java.util.concurrent.atomic.AtomicInteger;
287import java.util.concurrent.atomic.AtomicLong;
288
289/**
290 * Keep track of all those .apks everywhere.
291 *
292 * This is very central to the platform's security; please run the unit
293 * tests whenever making modifications here:
294 *
295runtest -c android.content.pm.PackageManagerTests frameworks-core
296 *
297 * {@hide}
298 */
299public class PackageManagerService extends IPackageManager.Stub {
300    static final String TAG = "PackageManager";
301    static final boolean DEBUG_SETTINGS = false;
302    static final boolean DEBUG_PREFERRED = false;
303    static final boolean DEBUG_UPGRADE = false;
304    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
305    private static final boolean DEBUG_BACKUP = false;
306    private static final boolean DEBUG_INSTALL = false;
307    private static final boolean DEBUG_REMOVE = false;
308    private static final boolean DEBUG_BROADCASTS = false;
309    private static final boolean DEBUG_SHOW_INFO = false;
310    private static final boolean DEBUG_PACKAGE_INFO = false;
311    private static final boolean DEBUG_INTENT_MATCHING = false;
312    private static final boolean DEBUG_PACKAGE_SCANNING = false;
313    private static final boolean DEBUG_VERIFY = false;
314    private static final boolean DEBUG_DEXOPT = false;
315    private static final boolean DEBUG_ABI_SELECTION = false;
316    private static final boolean DEBUG_EPHEMERAL = false;
317    private static final boolean DEBUG_TRIAGED_MISSING = false;
318    private static final boolean DEBUG_APP_DATA = false;
319
320    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
321
322    private static final boolean DISABLE_EPHEMERAL_APPS = true;
323
324    private static final int RADIO_UID = Process.PHONE_UID;
325    private static final int LOG_UID = Process.LOG_UID;
326    private static final int NFC_UID = Process.NFC_UID;
327    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
328    private static final int SHELL_UID = Process.SHELL_UID;
329
330    // Cap the size of permission trees that 3rd party apps can define
331    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
332
333    // Suffix used during package installation when copying/moving
334    // package apks to install directory.
335    private static final String INSTALL_PACKAGE_SUFFIX = "-";
336
337    static final int SCAN_NO_DEX = 1<<1;
338    static final int SCAN_FORCE_DEX = 1<<2;
339    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
340    static final int SCAN_NEW_INSTALL = 1<<4;
341    static final int SCAN_NO_PATHS = 1<<5;
342    static final int SCAN_UPDATE_TIME = 1<<6;
343    static final int SCAN_DEFER_DEX = 1<<7;
344    static final int SCAN_BOOTING = 1<<8;
345    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
346    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
347    static final int SCAN_REPLACING = 1<<11;
348    static final int SCAN_REQUIRE_KNOWN = 1<<12;
349    static final int SCAN_MOVE = 1<<13;
350    static final int SCAN_INITIAL = 1<<14;
351
352    static final int REMOVE_CHATTY = 1<<16;
353
354    private static final int[] EMPTY_INT_ARRAY = new int[0];
355
356    /**
357     * Timeout (in milliseconds) after which the watchdog should declare that
358     * our handler thread is wedged.  The usual default for such things is one
359     * minute but we sometimes do very lengthy I/O operations on this thread,
360     * such as installing multi-gigabyte applications, so ours needs to be longer.
361     */
362    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
363
364    /**
365     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
366     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
367     * settings entry if available, otherwise we use the hardcoded default.  If it's been
368     * more than this long since the last fstrim, we force one during the boot sequence.
369     *
370     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
371     * one gets run at the next available charging+idle time.  This final mandatory
372     * no-fstrim check kicks in only of the other scheduling criteria is never met.
373     */
374    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
375
376    /**
377     * Whether verification is enabled by default.
378     */
379    private static final boolean DEFAULT_VERIFY_ENABLE = true;
380
381    /**
382     * The default maximum time to wait for the verification agent to return in
383     * milliseconds.
384     */
385    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
386
387    /**
388     * The default response for package verification timeout.
389     *
390     * This can be either PackageManager.VERIFICATION_ALLOW or
391     * PackageManager.VERIFICATION_REJECT.
392     */
393    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
394
395    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
396
397    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
398            DEFAULT_CONTAINER_PACKAGE,
399            "com.android.defcontainer.DefaultContainerService");
400
401    private static final String KILL_APP_REASON_GIDS_CHANGED =
402            "permission grant or revoke changed gids";
403
404    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
405            "permissions revoked";
406
407    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
408
409    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
410
411    /** Permission grant: not grant the permission. */
412    private static final int GRANT_DENIED = 1;
413
414    /** Permission grant: grant the permission as an install permission. */
415    private static final int GRANT_INSTALL = 2;
416
417    /** Permission grant: grant the permission as a runtime one. */
418    private static final int GRANT_RUNTIME = 3;
419
420    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
421    private static final int GRANT_UPGRADE = 4;
422
423    /** Canonical intent used to identify what counts as a "web browser" app */
424    private static final Intent sBrowserIntent;
425    static {
426        sBrowserIntent = new Intent();
427        sBrowserIntent.setAction(Intent.ACTION_VIEW);
428        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
429        sBrowserIntent.setData(Uri.parse("http:"));
430    }
431
432    final ServiceThread mHandlerThread;
433
434    final PackageHandler mHandler;
435
436    /**
437     * Messages for {@link #mHandler} that need to wait for system ready before
438     * being dispatched.
439     */
440    private ArrayList<Message> mPostSystemReadyMessages;
441
442    final int mSdkVersion = Build.VERSION.SDK_INT;
443
444    final Context mContext;
445    final boolean mFactoryTest;
446    final boolean mOnlyCore;
447    final DisplayMetrics mMetrics;
448    final int mDefParseFlags;
449    final String[] mSeparateProcesses;
450    final boolean mIsUpgrade;
451
452    /** The location for ASEC container files on internal storage. */
453    final String mAsecInternalPath;
454
455    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
456    // LOCK HELD.  Can be called with mInstallLock held.
457    @GuardedBy("mInstallLock")
458    final Installer mInstaller;
459
460    /** Directory where installed third-party apps stored */
461    final File mAppInstallDir;
462    final File mEphemeralInstallDir;
463
464    /**
465     * Directory to which applications installed internally have their
466     * 32 bit native libraries copied.
467     */
468    private File mAppLib32InstallDir;
469
470    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
471    // apps.
472    final File mDrmAppPrivateInstallDir;
473
474    // ----------------------------------------------------------------
475
476    // Lock for state used when installing and doing other long running
477    // operations.  Methods that must be called with this lock held have
478    // the suffix "LI".
479    final Object mInstallLock = new Object();
480
481    // ----------------------------------------------------------------
482
483    // Keys are String (package name), values are Package.  This also serves
484    // as the lock for the global state.  Methods that must be called with
485    // this lock held have the prefix "LP".
486    @GuardedBy("mPackages")
487    final ArrayMap<String, PackageParser.Package> mPackages =
488            new ArrayMap<String, PackageParser.Package>();
489
490    // Tracks available target package names -> overlay package paths.
491    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
492        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
493
494    /**
495     * Tracks new system packages [received in an OTA] that we expect to
496     * find updated user-installed versions. Keys are package name, values
497     * are package location.
498     */
499    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
500
501    /**
502     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
503     */
504    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
505    /**
506     * Whether or not system app permissions should be promoted from install to runtime.
507     */
508    boolean mPromoteSystemApps;
509
510    final Settings mSettings;
511    boolean mRestoredSettings;
512
513    // System configuration read by SystemConfig.
514    final int[] mGlobalGids;
515    final SparseArray<ArraySet<String>> mSystemPermissions;
516    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
517
518    // If mac_permissions.xml was found for seinfo labeling.
519    boolean mFoundPolicyFile;
520
521    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
522
523    public static final class SharedLibraryEntry {
524        public final String path;
525        public final String apk;
526
527        SharedLibraryEntry(String _path, String _apk) {
528            path = _path;
529            apk = _apk;
530        }
531    }
532
533    // Currently known shared libraries.
534    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
535            new ArrayMap<String, SharedLibraryEntry>();
536
537    // All available activities, for your resolving pleasure.
538    final ActivityIntentResolver mActivities =
539            new ActivityIntentResolver();
540
541    // All available receivers, for your resolving pleasure.
542    final ActivityIntentResolver mReceivers =
543            new ActivityIntentResolver();
544
545    // All available services, for your resolving pleasure.
546    final ServiceIntentResolver mServices = new ServiceIntentResolver();
547
548    // All available providers, for your resolving pleasure.
549    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
550
551    // Mapping from provider base names (first directory in content URI codePath)
552    // to the provider information.
553    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
554            new ArrayMap<String, PackageParser.Provider>();
555
556    // Mapping from instrumentation class names to info about them.
557    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
558            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
559
560    // Mapping from permission names to info about them.
561    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
562            new ArrayMap<String, PackageParser.PermissionGroup>();
563
564    // Packages whose data we have transfered into another package, thus
565    // should no longer exist.
566    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
567
568    // Broadcast actions that are only available to the system.
569    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
570
571    /** List of packages waiting for verification. */
572    final SparseArray<PackageVerificationState> mPendingVerification
573            = new SparseArray<PackageVerificationState>();
574
575    /** Set of packages associated with each app op permission. */
576    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
577
578    final PackageInstallerService mInstallerService;
579
580    private final PackageDexOptimizer mPackageDexOptimizer;
581
582    private AtomicInteger mNextMoveId = new AtomicInteger();
583    private final MoveCallbacks mMoveCallbacks;
584
585    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
586
587    // Cache of users who need badging.
588    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
589
590    /** Token for keys in mPendingVerification. */
591    private int mPendingVerificationToken = 0;
592
593    volatile boolean mSystemReady;
594    volatile boolean mSafeMode;
595    volatile boolean mHasSystemUidErrors;
596
597    ApplicationInfo mAndroidApplication;
598    final ActivityInfo mResolveActivity = new ActivityInfo();
599    final ResolveInfo mResolveInfo = new ResolveInfo();
600    ComponentName mResolveComponentName;
601    PackageParser.Package mPlatformPackage;
602    ComponentName mCustomResolverComponentName;
603
604    boolean mResolverReplaced = false;
605
606    private final @Nullable ComponentName mIntentFilterVerifierComponent;
607    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
608
609    private int mIntentFilterVerificationToken = 0;
610
611    /** Component that knows whether or not an ephemeral application exists */
612    final ComponentName mEphemeralResolverComponent;
613    /** The service connection to the ephemeral resolver */
614    final EphemeralResolverConnection mEphemeralResolverConnection;
615
616    /** Component used to install ephemeral applications */
617    final ComponentName mEphemeralInstallerComponent;
618    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
619    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
620
621    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
622            = new SparseArray<IntentFilterVerificationState>();
623
624    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
625            new DefaultPermissionGrantPolicy(this);
626
627    // List of packages names to keep cached, even if they are uninstalled for all users
628    private List<String> mKeepUninstalledPackages;
629
630    private static class IFVerificationParams {
631        PackageParser.Package pkg;
632        boolean replacing;
633        int userId;
634        int verifierUid;
635
636        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
637                int _userId, int _verifierUid) {
638            pkg = _pkg;
639            replacing = _replacing;
640            userId = _userId;
641            replacing = _replacing;
642            verifierUid = _verifierUid;
643        }
644    }
645
646    private interface IntentFilterVerifier<T extends IntentFilter> {
647        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
648                                               T filter, String packageName);
649        void startVerifications(int userId);
650        void receiveVerificationResponse(int verificationId);
651    }
652
653    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
654        private Context mContext;
655        private ComponentName mIntentFilterVerifierComponent;
656        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
657
658        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
659            mContext = context;
660            mIntentFilterVerifierComponent = verifierComponent;
661        }
662
663        private String getDefaultScheme() {
664            return IntentFilter.SCHEME_HTTPS;
665        }
666
667        @Override
668        public void startVerifications(int userId) {
669            // Launch verifications requests
670            int count = mCurrentIntentFilterVerifications.size();
671            for (int n=0; n<count; n++) {
672                int verificationId = mCurrentIntentFilterVerifications.get(n);
673                final IntentFilterVerificationState ivs =
674                        mIntentFilterVerificationStates.get(verificationId);
675
676                String packageName = ivs.getPackageName();
677
678                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
679                final int filterCount = filters.size();
680                ArraySet<String> domainsSet = new ArraySet<>();
681                for (int m=0; m<filterCount; m++) {
682                    PackageParser.ActivityIntentInfo filter = filters.get(m);
683                    domainsSet.addAll(filter.getHostsList());
684                }
685                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
686                synchronized (mPackages) {
687                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
688                            packageName, domainsList) != null) {
689                        scheduleWriteSettingsLocked();
690                    }
691                }
692                sendVerificationRequest(userId, verificationId, ivs);
693            }
694            mCurrentIntentFilterVerifications.clear();
695        }
696
697        private void sendVerificationRequest(int userId, int verificationId,
698                IntentFilterVerificationState ivs) {
699
700            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
703                    verificationId);
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
706                    getDefaultScheme());
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
709                    ivs.getHostsString());
710            verificationIntent.putExtra(
711                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
712                    ivs.getPackageName());
713            verificationIntent.setComponent(mIntentFilterVerifierComponent);
714            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
715
716            UserHandle user = new UserHandle(userId);
717            mContext.sendBroadcastAsUser(verificationIntent, user);
718            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                    "Sending IntentFilter verification broadcast");
720        }
721
722        public void receiveVerificationResponse(int verificationId) {
723            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
724
725            final boolean verified = ivs.isVerified();
726
727            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
728            final int count = filters.size();
729            if (DEBUG_DOMAIN_VERIFICATION) {
730                Slog.i(TAG, "Received verification response " + verificationId
731                        + " for " + count + " filters, verified=" + verified);
732            }
733            for (int n=0; n<count; n++) {
734                PackageParser.ActivityIntentInfo filter = filters.get(n);
735                filter.setVerified(verified);
736
737                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
738                        + " verified with result:" + verified + " and hosts:"
739                        + ivs.getHostsString());
740            }
741
742            mIntentFilterVerificationStates.remove(verificationId);
743
744            final String packageName = ivs.getPackageName();
745            IntentFilterVerificationInfo ivi = null;
746
747            synchronized (mPackages) {
748                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
749            }
750            if (ivi == null) {
751                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
752                        + verificationId + " packageName:" + packageName);
753                return;
754            }
755            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
756                    "Updating IntentFilterVerificationInfo for package " + packageName
757                            +" verificationId:" + verificationId);
758
759            synchronized (mPackages) {
760                if (verified) {
761                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
762                } else {
763                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
764                }
765                scheduleWriteSettingsLocked();
766
767                final int userId = ivs.getUserId();
768                if (userId != UserHandle.USER_ALL) {
769                    final int userStatus =
770                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
771
772                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
773                    boolean needUpdate = false;
774
775                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
776                    // already been set by the User thru the Disambiguation dialog
777                    switch (userStatus) {
778                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
779                            if (verified) {
780                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
781                            } else {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
783                            }
784                            needUpdate = true;
785                            break;
786
787                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
788                            if (verified) {
789                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
790                                needUpdate = true;
791                            }
792                            break;
793
794                        default:
795                            // Nothing to do
796                    }
797
798                    if (needUpdate) {
799                        mSettings.updateIntentFilterVerificationStatusLPw(
800                                packageName, updatedStatus, userId);
801                        scheduleWritePackageRestrictionsLocked(userId);
802                    }
803                }
804            }
805        }
806
807        @Override
808        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
809                    ActivityIntentInfo filter, String packageName) {
810            if (!hasValidDomains(filter)) {
811                return false;
812            }
813            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
814            if (ivs == null) {
815                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
816                        packageName);
817            }
818            if (DEBUG_DOMAIN_VERIFICATION) {
819                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
820            }
821            ivs.addFilter(filter);
822            return true;
823        }
824
825        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
826                int userId, int verificationId, String packageName) {
827            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
828                    verifierUid, userId, packageName);
829            ivs.setPendingState();
830            synchronized (mPackages) {
831                mIntentFilterVerificationStates.append(verificationId, ivs);
832                mCurrentIntentFilterVerifications.add(verificationId);
833            }
834            return ivs;
835        }
836    }
837
838    private static boolean hasValidDomains(ActivityIntentInfo filter) {
839        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
840                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
841                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
842    }
843
844    // Set of pending broadcasts for aggregating enable/disable of components.
845    static class PendingPackageBroadcasts {
846        // for each user id, a map of <package name -> components within that package>
847        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
848
849        public PendingPackageBroadcasts() {
850            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
851        }
852
853        public ArrayList<String> get(int userId, String packageName) {
854            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
855            return packages.get(packageName);
856        }
857
858        public void put(int userId, String packageName, ArrayList<String> components) {
859            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
860            packages.put(packageName, components);
861        }
862
863        public void remove(int userId, String packageName) {
864            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
865            if (packages != null) {
866                packages.remove(packageName);
867            }
868        }
869
870        public void remove(int userId) {
871            mUidMap.remove(userId);
872        }
873
874        public int userIdCount() {
875            return mUidMap.size();
876        }
877
878        public int userIdAt(int n) {
879            return mUidMap.keyAt(n);
880        }
881
882        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
883            return mUidMap.get(userId);
884        }
885
886        public int size() {
887            // total number of pending broadcast entries across all userIds
888            int num = 0;
889            for (int i = 0; i< mUidMap.size(); i++) {
890                num += mUidMap.valueAt(i).size();
891            }
892            return num;
893        }
894
895        public void clear() {
896            mUidMap.clear();
897        }
898
899        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
900            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
901            if (map == null) {
902                map = new ArrayMap<String, ArrayList<String>>();
903                mUidMap.put(userId, map);
904            }
905            return map;
906        }
907    }
908    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
909
910    // Service Connection to remote media container service to copy
911    // package uri's from external media onto secure containers
912    // or internal storage.
913    private IMediaContainerService mContainerService = null;
914
915    static final int SEND_PENDING_BROADCAST = 1;
916    static final int MCS_BOUND = 3;
917    static final int END_COPY = 4;
918    static final int INIT_COPY = 5;
919    static final int MCS_UNBIND = 6;
920    static final int START_CLEANING_PACKAGE = 7;
921    static final int FIND_INSTALL_LOC = 8;
922    static final int POST_INSTALL = 9;
923    static final int MCS_RECONNECT = 10;
924    static final int MCS_GIVE_UP = 11;
925    static final int UPDATED_MEDIA_STATUS = 12;
926    static final int WRITE_SETTINGS = 13;
927    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
928    static final int PACKAGE_VERIFIED = 15;
929    static final int CHECK_PENDING_VERIFICATION = 16;
930    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
931    static final int INTENT_FILTER_VERIFIED = 18;
932
933    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
934
935    // Delay time in millisecs
936    static final int BROADCAST_DELAY = 10 * 1000;
937
938    static UserManagerService sUserManager;
939
940    // Stores a list of users whose package restrictions file needs to be updated
941    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
942
943    final private DefaultContainerConnection mDefContainerConn =
944            new DefaultContainerConnection();
945    class DefaultContainerConnection implements ServiceConnection {
946        public void onServiceConnected(ComponentName name, IBinder service) {
947            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
948            IMediaContainerService imcs =
949                IMediaContainerService.Stub.asInterface(service);
950            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
951        }
952
953        public void onServiceDisconnected(ComponentName name) {
954            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
955        }
956    }
957
958    // Recordkeeping of restore-after-install operations that are currently in flight
959    // between the Package Manager and the Backup Manager
960    static class PostInstallData {
961        public InstallArgs args;
962        public PackageInstalledInfo res;
963
964        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
965            args = _a;
966            res = _r;
967        }
968    }
969
970    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
971    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
972
973    // XML tags for backup/restore of various bits of state
974    private static final String TAG_PREFERRED_BACKUP = "pa";
975    private static final String TAG_DEFAULT_APPS = "da";
976    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
977
978    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
979    private static final String TAG_ALL_GRANTS = "rt-grants";
980    private static final String TAG_GRANT = "grant";
981    private static final String ATTR_PACKAGE_NAME = "pkg";
982
983    private static final String TAG_PERMISSION = "perm";
984    private static final String ATTR_PERMISSION_NAME = "name";
985    private static final String ATTR_IS_GRANTED = "g";
986    private static final String ATTR_USER_SET = "set";
987    private static final String ATTR_USER_FIXED = "fixed";
988    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
989
990    // System/policy permission grants are not backed up
991    private static final int SYSTEM_RUNTIME_GRANT_MASK =
992            FLAG_PERMISSION_POLICY_FIXED
993            | FLAG_PERMISSION_SYSTEM_FIXED
994            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
995
996    // And we back up these user-adjusted states
997    private static final int USER_RUNTIME_GRANT_MASK =
998            FLAG_PERMISSION_USER_SET
999            | FLAG_PERMISSION_USER_FIXED
1000            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1001
1002    final @Nullable String mRequiredVerifierPackage;
1003    final @Nullable String mRequiredInstallerPackage;
1004
1005    private final PackageUsage mPackageUsage = new PackageUsage();
1006
1007    private class PackageUsage {
1008        private static final int WRITE_INTERVAL
1009            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1010
1011        private final Object mFileLock = new Object();
1012        private final AtomicLong mLastWritten = new AtomicLong(0);
1013        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1014
1015        private boolean mIsHistoricalPackageUsageAvailable = true;
1016
1017        boolean isHistoricalPackageUsageAvailable() {
1018            return mIsHistoricalPackageUsageAvailable;
1019        }
1020
1021        void write(boolean force) {
1022            if (force) {
1023                writeInternal();
1024                return;
1025            }
1026            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1027                && !DEBUG_DEXOPT) {
1028                return;
1029            }
1030            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1031                new Thread("PackageUsage_DiskWriter") {
1032                    @Override
1033                    public void run() {
1034                        try {
1035                            writeInternal();
1036                        } finally {
1037                            mBackgroundWriteRunning.set(false);
1038                        }
1039                    }
1040                }.start();
1041            }
1042        }
1043
1044        private void writeInternal() {
1045            synchronized (mPackages) {
1046                synchronized (mFileLock) {
1047                    AtomicFile file = getFile();
1048                    FileOutputStream f = null;
1049                    try {
1050                        f = file.startWrite();
1051                        BufferedOutputStream out = new BufferedOutputStream(f);
1052                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1053                        StringBuilder sb = new StringBuilder();
1054                        for (PackageParser.Package pkg : mPackages.values()) {
1055                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1056                                continue;
1057                            }
1058                            sb.setLength(0);
1059                            sb.append(pkg.packageName);
1060                            sb.append(' ');
1061                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1062                            sb.append('\n');
1063                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1064                        }
1065                        out.flush();
1066                        file.finishWrite(f);
1067                    } catch (IOException e) {
1068                        if (f != null) {
1069                            file.failWrite(f);
1070                        }
1071                        Log.e(TAG, "Failed to write package usage times", e);
1072                    }
1073                }
1074            }
1075            mLastWritten.set(SystemClock.elapsedRealtime());
1076        }
1077
1078        void readLP() {
1079            synchronized (mFileLock) {
1080                AtomicFile file = getFile();
1081                BufferedInputStream in = null;
1082                try {
1083                    in = new BufferedInputStream(file.openRead());
1084                    StringBuffer sb = new StringBuffer();
1085                    while (true) {
1086                        String packageName = readToken(in, sb, ' ');
1087                        if (packageName == null) {
1088                            break;
1089                        }
1090                        String timeInMillisString = readToken(in, sb, '\n');
1091                        if (timeInMillisString == null) {
1092                            throw new IOException("Failed to find last usage time for package "
1093                                                  + packageName);
1094                        }
1095                        PackageParser.Package pkg = mPackages.get(packageName);
1096                        if (pkg == null) {
1097                            continue;
1098                        }
1099                        long timeInMillis;
1100                        try {
1101                            timeInMillis = Long.parseLong(timeInMillisString);
1102                        } catch (NumberFormatException e) {
1103                            throw new IOException("Failed to parse " + timeInMillisString
1104                                                  + " as a long.", e);
1105                        }
1106                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1107                    }
1108                } catch (FileNotFoundException expected) {
1109                    mIsHistoricalPackageUsageAvailable = false;
1110                } catch (IOException e) {
1111                    Log.w(TAG, "Failed to read package usage times", e);
1112                } finally {
1113                    IoUtils.closeQuietly(in);
1114                }
1115            }
1116            mLastWritten.set(SystemClock.elapsedRealtime());
1117        }
1118
1119        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1120                throws IOException {
1121            sb.setLength(0);
1122            while (true) {
1123                int ch = in.read();
1124                if (ch == -1) {
1125                    if (sb.length() == 0) {
1126                        return null;
1127                    }
1128                    throw new IOException("Unexpected EOF");
1129                }
1130                if (ch == endOfToken) {
1131                    return sb.toString();
1132                }
1133                sb.append((char)ch);
1134            }
1135        }
1136
1137        private AtomicFile getFile() {
1138            File dataDir = Environment.getDataDirectory();
1139            File systemDir = new File(dataDir, "system");
1140            File fname = new File(systemDir, "package-usage.list");
1141            return new AtomicFile(fname);
1142        }
1143    }
1144
1145    class PackageHandler extends Handler {
1146        private boolean mBound = false;
1147        final ArrayList<HandlerParams> mPendingInstalls =
1148            new ArrayList<HandlerParams>();
1149
1150        private boolean connectToService() {
1151            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1152                    " DefaultContainerService");
1153            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1154            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1155            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1156                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1157                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1158                mBound = true;
1159                return true;
1160            }
1161            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162            return false;
1163        }
1164
1165        private void disconnectService() {
1166            mContainerService = null;
1167            mBound = false;
1168            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1169            mContext.unbindService(mDefContainerConn);
1170            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1171        }
1172
1173        PackageHandler(Looper looper) {
1174            super(looper);
1175        }
1176
1177        public void handleMessage(Message msg) {
1178            try {
1179                doHandleMessage(msg);
1180            } finally {
1181                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1182            }
1183        }
1184
1185        void doHandleMessage(Message msg) {
1186            switch (msg.what) {
1187                case INIT_COPY: {
1188                    HandlerParams params = (HandlerParams) msg.obj;
1189                    int idx = mPendingInstalls.size();
1190                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1191                    // If a bind was already initiated we dont really
1192                    // need to do anything. The pending install
1193                    // will be processed later on.
1194                    if (!mBound) {
1195                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1196                                System.identityHashCode(mHandler));
1197                        // If this is the only one pending we might
1198                        // have to bind to the service again.
1199                        if (!connectToService()) {
1200                            Slog.e(TAG, "Failed to bind to media container service");
1201                            params.serviceError();
1202                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1203                                    System.identityHashCode(mHandler));
1204                            if (params.traceMethod != null) {
1205                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1206                                        params.traceCookie);
1207                            }
1208                            return;
1209                        } else {
1210                            // Once we bind to the service, the first
1211                            // pending request will be processed.
1212                            mPendingInstalls.add(idx, params);
1213                        }
1214                    } else {
1215                        mPendingInstalls.add(idx, params);
1216                        // Already bound to the service. Just make
1217                        // sure we trigger off processing the first request.
1218                        if (idx == 0) {
1219                            mHandler.sendEmptyMessage(MCS_BOUND);
1220                        }
1221                    }
1222                    break;
1223                }
1224                case MCS_BOUND: {
1225                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1226                    if (msg.obj != null) {
1227                        mContainerService = (IMediaContainerService) msg.obj;
1228                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1229                                System.identityHashCode(mHandler));
1230                    }
1231                    if (mContainerService == null) {
1232                        if (!mBound) {
1233                            // Something seriously wrong since we are not bound and we are not
1234                            // waiting for connection. Bail out.
1235                            Slog.e(TAG, "Cannot bind to media container service");
1236                            for (HandlerParams params : mPendingInstalls) {
1237                                // Indicate service bind error
1238                                params.serviceError();
1239                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1240                                        System.identityHashCode(params));
1241                                if (params.traceMethod != null) {
1242                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1243                                            params.traceMethod, params.traceCookie);
1244                                }
1245                                return;
1246                            }
1247                            mPendingInstalls.clear();
1248                        } else {
1249                            Slog.w(TAG, "Waiting to connect to media container service");
1250                        }
1251                    } else if (mPendingInstalls.size() > 0) {
1252                        HandlerParams params = mPendingInstalls.get(0);
1253                        if (params != null) {
1254                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1255                                    System.identityHashCode(params));
1256                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1257                            if (params.startCopy()) {
1258                                // We are done...  look for more work or to
1259                                // go idle.
1260                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1261                                        "Checking for more work or unbind...");
1262                                // Delete pending install
1263                                if (mPendingInstalls.size() > 0) {
1264                                    mPendingInstalls.remove(0);
1265                                }
1266                                if (mPendingInstalls.size() == 0) {
1267                                    if (mBound) {
1268                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1269                                                "Posting delayed MCS_UNBIND");
1270                                        removeMessages(MCS_UNBIND);
1271                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1272                                        // Unbind after a little delay, to avoid
1273                                        // continual thrashing.
1274                                        sendMessageDelayed(ubmsg, 10000);
1275                                    }
1276                                } else {
1277                                    // There are more pending requests in queue.
1278                                    // Just post MCS_BOUND message to trigger processing
1279                                    // of next pending install.
1280                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1281                                            "Posting MCS_BOUND for next work");
1282                                    mHandler.sendEmptyMessage(MCS_BOUND);
1283                                }
1284                            }
1285                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1286                        }
1287                    } else {
1288                        // Should never happen ideally.
1289                        Slog.w(TAG, "Empty queue");
1290                    }
1291                    break;
1292                }
1293                case MCS_RECONNECT: {
1294                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1295                    if (mPendingInstalls.size() > 0) {
1296                        if (mBound) {
1297                            disconnectService();
1298                        }
1299                        if (!connectToService()) {
1300                            Slog.e(TAG, "Failed to bind to media container service");
1301                            for (HandlerParams params : mPendingInstalls) {
1302                                // Indicate service bind error
1303                                params.serviceError();
1304                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1305                                        System.identityHashCode(params));
1306                            }
1307                            mPendingInstalls.clear();
1308                        }
1309                    }
1310                    break;
1311                }
1312                case MCS_UNBIND: {
1313                    // If there is no actual work left, then time to unbind.
1314                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1315
1316                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1317                        if (mBound) {
1318                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1319
1320                            disconnectService();
1321                        }
1322                    } else if (mPendingInstalls.size() > 0) {
1323                        // There are more pending requests in queue.
1324                        // Just post MCS_BOUND message to trigger processing
1325                        // of next pending install.
1326                        mHandler.sendEmptyMessage(MCS_BOUND);
1327                    }
1328
1329                    break;
1330                }
1331                case MCS_GIVE_UP: {
1332                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1333                    HandlerParams params = mPendingInstalls.remove(0);
1334                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1335                            System.identityHashCode(params));
1336                    break;
1337                }
1338                case SEND_PENDING_BROADCAST: {
1339                    String packages[];
1340                    ArrayList<String> components[];
1341                    int size = 0;
1342                    int uids[];
1343                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1344                    synchronized (mPackages) {
1345                        if (mPendingBroadcasts == null) {
1346                            return;
1347                        }
1348                        size = mPendingBroadcasts.size();
1349                        if (size <= 0) {
1350                            // Nothing to be done. Just return
1351                            return;
1352                        }
1353                        packages = new String[size];
1354                        components = new ArrayList[size];
1355                        uids = new int[size];
1356                        int i = 0;  // filling out the above arrays
1357
1358                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1359                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1360                            Iterator<Map.Entry<String, ArrayList<String>>> it
1361                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1362                                            .entrySet().iterator();
1363                            while (it.hasNext() && i < size) {
1364                                Map.Entry<String, ArrayList<String>> ent = it.next();
1365                                packages[i] = ent.getKey();
1366                                components[i] = ent.getValue();
1367                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1368                                uids[i] = (ps != null)
1369                                        ? UserHandle.getUid(packageUserId, ps.appId)
1370                                        : -1;
1371                                i++;
1372                            }
1373                        }
1374                        size = i;
1375                        mPendingBroadcasts.clear();
1376                    }
1377                    // Send broadcasts
1378                    for (int i = 0; i < size; i++) {
1379                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1380                    }
1381                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1382                    break;
1383                }
1384                case START_CLEANING_PACKAGE: {
1385                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1386                    final String packageName = (String)msg.obj;
1387                    final int userId = msg.arg1;
1388                    final boolean andCode = msg.arg2 != 0;
1389                    synchronized (mPackages) {
1390                        if (userId == UserHandle.USER_ALL) {
1391                            int[] users = sUserManager.getUserIds();
1392                            for (int user : users) {
1393                                mSettings.addPackageToCleanLPw(
1394                                        new PackageCleanItem(user, packageName, andCode));
1395                            }
1396                        } else {
1397                            mSettings.addPackageToCleanLPw(
1398                                    new PackageCleanItem(userId, packageName, andCode));
1399                        }
1400                    }
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1402                    startCleaningPackages();
1403                } break;
1404                case POST_INSTALL: {
1405                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1406
1407                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1408                    mRunningInstalls.delete(msg.arg1);
1409                    boolean deleteOld = false;
1410
1411                    if (data != null) {
1412                        InstallArgs args = data.args;
1413                        PackageInstalledInfo res = data.res;
1414
1415                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1416                            final String packageName = res.pkg.applicationInfo.packageName;
1417                            res.removedInfo.sendBroadcast(false, true, false);
1418                            Bundle extras = new Bundle(1);
1419                            extras.putInt(Intent.EXTRA_UID, res.uid);
1420
1421                            // Now that we successfully installed the package, grant runtime
1422                            // permissions if requested before broadcasting the install.
1423                            if ((args.installFlags
1424                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1425                                    && res.pkg.applicationInfo.targetSdkVersion
1426                                            >= Build.VERSION_CODES.M) {
1427                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1428                                        args.installGrantPermissions);
1429                            }
1430
1431                            synchronized (mPackages) {
1432                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1433                            }
1434
1435                            // Determine the set of users who are adding this
1436                            // package for the first time vs. those who are seeing
1437                            // an update.
1438                            int[] firstUsers;
1439                            int[] updateUsers = new int[0];
1440                            if (res.origUsers == null || res.origUsers.length == 0) {
1441                                firstUsers = res.newUsers;
1442                            } else {
1443                                firstUsers = new int[0];
1444                                for (int i=0; i<res.newUsers.length; i++) {
1445                                    int user = res.newUsers[i];
1446                                    boolean isNew = true;
1447                                    for (int j=0; j<res.origUsers.length; j++) {
1448                                        if (res.origUsers[j] == user) {
1449                                            isNew = false;
1450                                            break;
1451                                        }
1452                                    }
1453                                    if (isNew) {
1454                                        int[] newFirst = new int[firstUsers.length+1];
1455                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1456                                                firstUsers.length);
1457                                        newFirst[firstUsers.length] = user;
1458                                        firstUsers = newFirst;
1459                                    } else {
1460                                        int[] newUpdate = new int[updateUsers.length+1];
1461                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1462                                                updateUsers.length);
1463                                        newUpdate[updateUsers.length] = user;
1464                                        updateUsers = newUpdate;
1465                                    }
1466                                }
1467                            }
1468                            // don't broadcast for ephemeral installs/updates
1469                            final boolean isEphemeral = isEphemeral(res.pkg);
1470                            if (!isEphemeral) {
1471                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1472                                        extras, 0 /*flags*/, null /*targetPackage*/,
1473                                        null /*finishedReceiver*/, firstUsers);
1474                            }
1475                            final boolean update = res.removedInfo.removedPackage != null;
1476                            if (update) {
1477                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1478                            }
1479                            if (!isEphemeral) {
1480                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1481                                        extras, 0 /*flags*/, null /*targetPackage*/,
1482                                        null /*finishedReceiver*/, updateUsers);
1483                            }
1484                            if (update) {
1485                                if (!isEphemeral) {
1486                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1487                                            packageName, extras, 0 /*flags*/,
1488                                            null /*targetPackage*/, null /*finishedReceiver*/,
1489                                            updateUsers);
1490                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1491                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1492                                            packageName /*targetPackage*/,
1493                                            null /*finishedReceiver*/, updateUsers);
1494                                }
1495
1496                                // treat asec-hosted packages like removable media on upgrade
1497                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1498                                    if (DEBUG_INSTALL) {
1499                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1500                                                + " is ASEC-hosted -> AVAILABLE");
1501                                    }
1502                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1503                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1504                                    pkgList.add(packageName);
1505                                    sendResourcesChangedBroadcast(true, true,
1506                                            pkgList,uidArray, null);
1507                                }
1508                            }
1509                            if (res.removedInfo.args != null) {
1510                                // Remove the replaced package's older resources safely now
1511                                deleteOld = true;
1512                            }
1513
1514
1515                            // Work that needs to happen on first install within each user
1516                            if (firstUsers.length > 0) {
1517                                for (int userId : firstUsers) {
1518                                    synchronized (mPackages) {
1519                                        // If this app is a browser and it's newly-installed for
1520                                        // some users, clear any default-browser state in those
1521                                        // users.  The app's nature doesn't depend on the user,
1522                                        // so we can just check its browser nature in any user
1523                                        // and generalize.
1524                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1525                                            mSettings.setDefaultBrowserPackageNameLPw(
1526                                                    null, userId);
1527                                        }
1528
1529                                        // We may also need to apply pending (restored) runtime
1530                                        // permission grants within these users.
1531                                        mSettings.applyPendingPermissionGrantsLPw(
1532                                                packageName, userId);
1533                                    }
1534                                }
1535                            }
1536                            // Log current value of "unknown sources" setting
1537                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1538                                getUnknownSourcesSettings());
1539                        }
1540                        // Force a gc to clear up things
1541                        Runtime.getRuntime().gc();
1542                        // We delete after a gc for applications  on sdcard.
1543                        if (deleteOld) {
1544                            synchronized (mInstallLock) {
1545                                res.removedInfo.args.doPostDeleteLI(true);
1546                            }
1547                        }
1548                        if (args.observer != null) {
1549                            try {
1550                                Bundle extras = extrasForInstallResult(res);
1551                                args.observer.onPackageInstalled(res.name, res.returnCode,
1552                                        res.returnMsg, extras);
1553                            } catch (RemoteException e) {
1554                                Slog.i(TAG, "Observer no longer exists.");
1555                            }
1556                        }
1557                        if (args.traceMethod != null) {
1558                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1559                                    args.traceCookie);
1560                        }
1561                        return;
1562                    } else {
1563                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1564                    }
1565
1566                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1567                } break;
1568                case UPDATED_MEDIA_STATUS: {
1569                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1570                    boolean reportStatus = msg.arg1 == 1;
1571                    boolean doGc = msg.arg2 == 1;
1572                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1573                    if (doGc) {
1574                        // Force a gc to clear up stale containers.
1575                        Runtime.getRuntime().gc();
1576                    }
1577                    if (msg.obj != null) {
1578                        @SuppressWarnings("unchecked")
1579                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1580                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1581                        // Unload containers
1582                        unloadAllContainers(args);
1583                    }
1584                    if (reportStatus) {
1585                        try {
1586                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1587                            PackageHelper.getMountService().finishMediaUpdate();
1588                        } catch (RemoteException e) {
1589                            Log.e(TAG, "MountService not running?");
1590                        }
1591                    }
1592                } break;
1593                case WRITE_SETTINGS: {
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        removeMessages(WRITE_SETTINGS);
1597                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1598                        mSettings.writeLPr();
1599                        mDirtyUsers.clear();
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case WRITE_PACKAGE_RESTRICTIONS: {
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1607                        for (int userId : mDirtyUsers) {
1608                            mSettings.writePackageRestrictionsLPr(userId);
1609                        }
1610                        mDirtyUsers.clear();
1611                    }
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1613                } break;
1614                case CHECK_PENDING_VERIFICATION: {
1615                    final int verificationId = msg.arg1;
1616                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1617
1618                    if ((state != null) && !state.timeoutExtended()) {
1619                        final InstallArgs args = state.getInstallArgs();
1620                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1621
1622                        Slog.i(TAG, "Verification timed out for " + originUri);
1623                        mPendingVerification.remove(verificationId);
1624
1625                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1626
1627                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1628                            Slog.i(TAG, "Continuing with installation of " + originUri);
1629                            state.setVerifierResponse(Binder.getCallingUid(),
1630                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1631                            broadcastPackageVerified(verificationId, originUri,
1632                                    PackageManager.VERIFICATION_ALLOW,
1633                                    state.getInstallArgs().getUser());
1634                            try {
1635                                ret = args.copyApk(mContainerService, true);
1636                            } catch (RemoteException e) {
1637                                Slog.e(TAG, "Could not contact the ContainerService");
1638                            }
1639                        } else {
1640                            broadcastPackageVerified(verificationId, originUri,
1641                                    PackageManager.VERIFICATION_REJECT,
1642                                    state.getInstallArgs().getUser());
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651                    break;
1652                }
1653                case PACKAGE_VERIFIED: {
1654                    final int verificationId = msg.arg1;
1655
1656                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1657                    if (state == null) {
1658                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1659                        break;
1660                    }
1661
1662                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1663
1664                    state.setVerifierResponse(response.callerUid, response.code);
1665
1666                    if (state.isVerificationComplete()) {
1667                        mPendingVerification.remove(verificationId);
1668
1669                        final InstallArgs args = state.getInstallArgs();
1670                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1671
1672                        int ret;
1673                        if (state.isInstallAllowed()) {
1674                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1675                            broadcastPackageVerified(verificationId, originUri,
1676                                    response.code, state.getInstallArgs().getUser());
1677                            try {
1678                                ret = args.copyApk(mContainerService, true);
1679                            } catch (RemoteException e) {
1680                                Slog.e(TAG, "Could not contact the ContainerService");
1681                            }
1682                        } else {
1683                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1684                        }
1685
1686                        Trace.asyncTraceEnd(
1687                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1688
1689                        processPendingInstall(args, ret);
1690                        mHandler.sendEmptyMessage(MCS_UNBIND);
1691                    }
1692
1693                    break;
1694                }
1695                case START_INTENT_FILTER_VERIFICATIONS: {
1696                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1697                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1698                            params.replacing, params.pkg);
1699                    break;
1700                }
1701                case INTENT_FILTER_VERIFIED: {
1702                    final int verificationId = msg.arg1;
1703
1704                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1705                            verificationId);
1706                    if (state == null) {
1707                        Slog.w(TAG, "Invalid IntentFilter verification token "
1708                                + verificationId + " received");
1709                        break;
1710                    }
1711
1712                    final int userId = state.getUserId();
1713
1714                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1715                            "Processing IntentFilter verification with token:"
1716                            + verificationId + " and userId:" + userId);
1717
1718                    final IntentFilterVerificationResponse response =
1719                            (IntentFilterVerificationResponse) msg.obj;
1720
1721                    state.setVerifierResponse(response.callerUid, response.code);
1722
1723                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1724                            "IntentFilter verification with token:" + verificationId
1725                            + " and userId:" + userId
1726                            + " is settings verifier response with response code:"
1727                            + response.code);
1728
1729                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1730                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1731                                + response.getFailedDomainsString());
1732                    }
1733
1734                    if (state.isVerificationComplete()) {
1735                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1736                    } else {
1737                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1738                                "IntentFilter verification with token:" + verificationId
1739                                + " was not said to be complete");
1740                    }
1741
1742                    break;
1743                }
1744            }
1745        }
1746    }
1747
1748    private StorageEventListener mStorageListener = new StorageEventListener() {
1749        @Override
1750        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1751            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1752                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1753                    final String volumeUuid = vol.getFsUuid();
1754
1755                    // Clean up any users or apps that were removed or recreated
1756                    // while this volume was missing
1757                    reconcileUsers(volumeUuid);
1758                    reconcileApps(volumeUuid);
1759
1760                    // Clean up any install sessions that expired or were
1761                    // cancelled while this volume was missing
1762                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1763
1764                    loadPrivatePackages(vol);
1765
1766                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1767                    unloadPrivatePackages(vol);
1768                }
1769            }
1770
1771            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1772                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1773                    updateExternalMediaStatus(true, false);
1774                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1775                    updateExternalMediaStatus(false, false);
1776                }
1777            }
1778        }
1779
1780        @Override
1781        public void onVolumeForgotten(String fsUuid) {
1782            if (TextUtils.isEmpty(fsUuid)) {
1783                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1784                return;
1785            }
1786
1787            // Remove any apps installed on the forgotten volume
1788            synchronized (mPackages) {
1789                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1790                for (PackageSetting ps : packages) {
1791                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1792                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1793                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1794                }
1795
1796                mSettings.onVolumeForgotten(fsUuid);
1797                mSettings.writeLPr();
1798            }
1799        }
1800    };
1801
1802    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1803            String[] grantedPermissions) {
1804        if (userId >= UserHandle.USER_SYSTEM) {
1805            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1806        } else if (userId == UserHandle.USER_ALL) {
1807            final int[] userIds;
1808            synchronized (mPackages) {
1809                userIds = UserManagerService.getInstance().getUserIds();
1810            }
1811            for (int someUserId : userIds) {
1812                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1813            }
1814        }
1815
1816        // We could have touched GID membership, so flush out packages.list
1817        synchronized (mPackages) {
1818            mSettings.writePackageListLPr();
1819        }
1820    }
1821
1822    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1823            String[] grantedPermissions) {
1824        SettingBase sb = (SettingBase) pkg.mExtras;
1825        if (sb == null) {
1826            return;
1827        }
1828
1829        PermissionsState permissionsState = sb.getPermissionsState();
1830
1831        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1832                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1833
1834        synchronized (mPackages) {
1835            for (String permission : pkg.requestedPermissions) {
1836                BasePermission bp = mSettings.mPermissions.get(permission);
1837                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1838                        && (grantedPermissions == null
1839                               || ArrayUtils.contains(grantedPermissions, permission))) {
1840                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1841                    // Installer cannot change immutable permissions.
1842                    if ((flags & immutableFlags) == 0) {
1843                        grantRuntimePermission(pkg.packageName, permission, userId);
1844                    }
1845                }
1846            }
1847        }
1848    }
1849
1850    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1851        Bundle extras = null;
1852        switch (res.returnCode) {
1853            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1854                extras = new Bundle();
1855                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1856                        res.origPermission);
1857                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1858                        res.origPackage);
1859                break;
1860            }
1861            case PackageManager.INSTALL_SUCCEEDED: {
1862                extras = new Bundle();
1863                extras.putBoolean(Intent.EXTRA_REPLACING,
1864                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1865                break;
1866            }
1867        }
1868        return extras;
1869    }
1870
1871    void scheduleWriteSettingsLocked() {
1872        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1873            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1874        }
1875    }
1876
1877    void scheduleWritePackageRestrictionsLocked(int userId) {
1878        if (!sUserManager.exists(userId)) return;
1879        mDirtyUsers.add(userId);
1880        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1881            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1882        }
1883    }
1884
1885    public static PackageManagerService main(Context context, Installer installer,
1886            boolean factoryTest, boolean onlyCore) {
1887        PackageManagerService m = new PackageManagerService(context, installer,
1888                factoryTest, onlyCore);
1889        m.enableSystemUserPackages();
1890        ServiceManager.addService("package", m);
1891        return m;
1892    }
1893
1894    private void enableSystemUserPackages() {
1895        if (!UserManager.isSplitSystemUser()) {
1896            return;
1897        }
1898        // For system user, enable apps based on the following conditions:
1899        // - app is whitelisted or belong to one of these groups:
1900        //   -- system app which has no launcher icons
1901        //   -- system app which has INTERACT_ACROSS_USERS permission
1902        //   -- system IME app
1903        // - app is not in the blacklist
1904        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1905        Set<String> enableApps = new ArraySet<>();
1906        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1907                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1908                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1909        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1910        enableApps.addAll(wlApps);
1911        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1912                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1913        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1914        enableApps.removeAll(blApps);
1915        Log.i(TAG, "Applications installed for system user: " + enableApps);
1916        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1917                UserHandle.SYSTEM);
1918        final int allAppsSize = allAps.size();
1919        synchronized (mPackages) {
1920            for (int i = 0; i < allAppsSize; i++) {
1921                String pName = allAps.get(i);
1922                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1923                // Should not happen, but we shouldn't be failing if it does
1924                if (pkgSetting == null) {
1925                    continue;
1926                }
1927                boolean install = enableApps.contains(pName);
1928                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1929                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1930                            + " for system user");
1931                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1932                }
1933            }
1934        }
1935    }
1936
1937    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1938        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1939                Context.DISPLAY_SERVICE);
1940        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1941    }
1942
1943    public PackageManagerService(Context context, Installer installer,
1944            boolean factoryTest, boolean onlyCore) {
1945        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1946                SystemClock.uptimeMillis());
1947
1948        if (mSdkVersion <= 0) {
1949            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1950        }
1951
1952        mContext = context;
1953        mFactoryTest = factoryTest;
1954        mOnlyCore = onlyCore;
1955        mMetrics = new DisplayMetrics();
1956        mSettings = new Settings(mPackages);
1957        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1958                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1959        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1960                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1961        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1962                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1963        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1964                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1965        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1966                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1967        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1968                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1969
1970        String separateProcesses = SystemProperties.get("debug.separate_processes");
1971        if (separateProcesses != null && separateProcesses.length() > 0) {
1972            if ("*".equals(separateProcesses)) {
1973                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1974                mSeparateProcesses = null;
1975                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1976            } else {
1977                mDefParseFlags = 0;
1978                mSeparateProcesses = separateProcesses.split(",");
1979                Slog.w(TAG, "Running with debug.separate_processes: "
1980                        + separateProcesses);
1981            }
1982        } else {
1983            mDefParseFlags = 0;
1984            mSeparateProcesses = null;
1985        }
1986
1987        mInstaller = installer;
1988        mPackageDexOptimizer = new PackageDexOptimizer(this);
1989        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1990
1991        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1992                FgThread.get().getLooper());
1993
1994        getDefaultDisplayMetrics(context, mMetrics);
1995
1996        SystemConfig systemConfig = SystemConfig.getInstance();
1997        mGlobalGids = systemConfig.getGlobalGids();
1998        mSystemPermissions = systemConfig.getSystemPermissions();
1999        mAvailableFeatures = systemConfig.getAvailableFeatures();
2000
2001        synchronized (mInstallLock) {
2002        // writer
2003        synchronized (mPackages) {
2004            mHandlerThread = new ServiceThread(TAG,
2005                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2006            mHandlerThread.start();
2007            mHandler = new PackageHandler(mHandlerThread.getLooper());
2008            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2009
2010            File dataDir = Environment.getDataDirectory();
2011            mAppInstallDir = new File(dataDir, "app");
2012            mAppLib32InstallDir = new File(dataDir, "app-lib");
2013            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2014            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2015            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2016
2017            sUserManager = new UserManagerService(context, this, mPackages);
2018
2019            // Propagate permission configuration in to package manager.
2020            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2021                    = systemConfig.getPermissions();
2022            for (int i=0; i<permConfig.size(); i++) {
2023                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2024                BasePermission bp = mSettings.mPermissions.get(perm.name);
2025                if (bp == null) {
2026                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2027                    mSettings.mPermissions.put(perm.name, bp);
2028                }
2029                if (perm.gids != null) {
2030                    bp.setGids(perm.gids, perm.perUser);
2031                }
2032            }
2033
2034            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2035            for (int i=0; i<libConfig.size(); i++) {
2036                mSharedLibraries.put(libConfig.keyAt(i),
2037                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2038            }
2039
2040            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2041
2042            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2043
2044            String customResolverActivity = Resources.getSystem().getString(
2045                    R.string.config_customResolverActivity);
2046            if (TextUtils.isEmpty(customResolverActivity)) {
2047                customResolverActivity = null;
2048            } else {
2049                mCustomResolverComponentName = ComponentName.unflattenFromString(
2050                        customResolverActivity);
2051            }
2052
2053            long startTime = SystemClock.uptimeMillis();
2054
2055            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2056                    startTime);
2057
2058            // Set flag to monitor and not change apk file paths when
2059            // scanning install directories.
2060            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2061
2062            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2063            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2064
2065            if (bootClassPath == null) {
2066                Slog.w(TAG, "No BOOTCLASSPATH found!");
2067            }
2068
2069            if (systemServerClassPath == null) {
2070                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2071            }
2072
2073            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2074            final String[] dexCodeInstructionSets =
2075                    getDexCodeInstructionSets(
2076                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2077
2078            /**
2079             * Ensure all external libraries have had dexopt run on them.
2080             */
2081            if (mSharedLibraries.size() > 0) {
2082                // NOTE: For now, we're compiling these system "shared libraries"
2083                // (and framework jars) into all available architectures. It's possible
2084                // to compile them only when we come across an app that uses them (there's
2085                // already logic for that in scanPackageLI) but that adds some complexity.
2086                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2087                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2088                        final String lib = libEntry.path;
2089                        if (lib == null) {
2090                            continue;
2091                        }
2092
2093                        try {
2094                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2095                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2096                                // Shared libraries do not have profiles so we perform a full
2097                                // AOT compilation.
2098                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2099                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2100                                        StorageManager.UUID_PRIVATE_INTERNAL,
2101                                        false /*useProfiles*/);
2102                            }
2103                        } catch (FileNotFoundException e) {
2104                            Slog.w(TAG, "Library not found: " + lib);
2105                        } catch (IOException | InstallerException e) {
2106                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2107                                    + e.getMessage());
2108                        }
2109                    }
2110                }
2111            }
2112
2113            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2114
2115            final VersionInfo ver = mSettings.getInternalVersion();
2116            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2117            // when upgrading from pre-M, promote system app permissions from install to runtime
2118            mPromoteSystemApps =
2119                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2120
2121            // save off the names of pre-existing system packages prior to scanning; we don't
2122            // want to automatically grant runtime permissions for new system apps
2123            if (mPromoteSystemApps) {
2124                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2125                while (pkgSettingIter.hasNext()) {
2126                    PackageSetting ps = pkgSettingIter.next();
2127                    if (isSystemApp(ps)) {
2128                        mExistingSystemPackages.add(ps.name);
2129                    }
2130                }
2131            }
2132
2133            // Collect vendor overlay packages.
2134            // (Do this before scanning any apps.)
2135            // For security and version matching reason, only consider
2136            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2137            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2138            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2139                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2140
2141            // Find base frameworks (resource packages without code).
2142            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2143                    | PackageParser.PARSE_IS_SYSTEM_DIR
2144                    | PackageParser.PARSE_IS_PRIVILEGED,
2145                    scanFlags | SCAN_NO_DEX, 0);
2146
2147            // Collected privileged system packages.
2148            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2149            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2150                    | PackageParser.PARSE_IS_SYSTEM_DIR
2151                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2152
2153            // Collect ordinary system packages.
2154            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2155            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2156                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2157
2158            // Collect all vendor packages.
2159            File vendorAppDir = new File("/vendor/app");
2160            try {
2161                vendorAppDir = vendorAppDir.getCanonicalFile();
2162            } catch (IOException e) {
2163                // failed to look up canonical path, continue with original one
2164            }
2165            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2166                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2167
2168            // Collect all OEM packages.
2169            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2170            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2171                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2172
2173            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2174            try {
2175                mInstaller.moveFiles();
2176            } catch (InstallerException e) {
2177                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2178            }
2179
2180            // Prune any system packages that no longer exist.
2181            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2182            if (!mOnlyCore) {
2183                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2184                while (psit.hasNext()) {
2185                    PackageSetting ps = psit.next();
2186
2187                    /*
2188                     * If this is not a system app, it can't be a
2189                     * disable system app.
2190                     */
2191                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2192                        continue;
2193                    }
2194
2195                    /*
2196                     * If the package is scanned, it's not erased.
2197                     */
2198                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2199                    if (scannedPkg != null) {
2200                        /*
2201                         * If the system app is both scanned and in the
2202                         * disabled packages list, then it must have been
2203                         * added via OTA. Remove it from the currently
2204                         * scanned package so the previously user-installed
2205                         * application can be scanned.
2206                         */
2207                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2208                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2209                                    + ps.name + "; removing system app.  Last known codePath="
2210                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2211                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2212                                    + scannedPkg.mVersionCode);
2213                            removePackageLI(ps, true);
2214                            mExpectingBetter.put(ps.name, ps.codePath);
2215                        }
2216
2217                        continue;
2218                    }
2219
2220                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2221                        psit.remove();
2222                        logCriticalInfo(Log.WARN, "System package " + ps.name
2223                                + " no longer exists; wiping its data");
2224                        removeDataDirsLI(null, ps.name);
2225                    } else {
2226                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2227                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2228                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2229                        }
2230                    }
2231                }
2232            }
2233
2234            //look for any incomplete package installations
2235            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2236            //clean up list
2237            for(int i = 0; i < deletePkgsList.size(); i++) {
2238                //clean up here
2239                cleanupInstallFailedPackage(deletePkgsList.get(i));
2240            }
2241            //delete tmp files
2242            deleteTempPackageFiles();
2243
2244            // Remove any shared userIDs that have no associated packages
2245            mSettings.pruneSharedUsersLPw();
2246
2247            if (!mOnlyCore) {
2248                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2249                        SystemClock.uptimeMillis());
2250                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2251
2252                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2253                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2254
2255                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2256                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2257
2258                /**
2259                 * Remove disable package settings for any updated system
2260                 * apps that were removed via an OTA. If they're not a
2261                 * previously-updated app, remove them completely.
2262                 * Otherwise, just revoke their system-level permissions.
2263                 */
2264                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2265                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2266                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2267
2268                    String msg;
2269                    if (deletedPkg == null) {
2270                        msg = "Updated system package " + deletedAppName
2271                                + " no longer exists; wiping its data";
2272                        removeDataDirsLI(null, deletedAppName);
2273                    } else {
2274                        msg = "Updated system app + " + deletedAppName
2275                                + " no longer present; removing system privileges for "
2276                                + deletedAppName;
2277
2278                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2279
2280                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2281                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2282                    }
2283                    logCriticalInfo(Log.WARN, msg);
2284                }
2285
2286                /**
2287                 * Make sure all system apps that we expected to appear on
2288                 * the userdata partition actually showed up. If they never
2289                 * appeared, crawl back and revive the system version.
2290                 */
2291                for (int i = 0; i < mExpectingBetter.size(); i++) {
2292                    final String packageName = mExpectingBetter.keyAt(i);
2293                    if (!mPackages.containsKey(packageName)) {
2294                        final File scanFile = mExpectingBetter.valueAt(i);
2295
2296                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2297                                + " but never showed up; reverting to system");
2298
2299                        final int reparseFlags;
2300                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2301                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2302                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2303                                    | PackageParser.PARSE_IS_PRIVILEGED;
2304                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2305                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2306                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2307                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2308                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2309                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2310                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2311                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2312                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2313                        } else {
2314                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2315                            continue;
2316                        }
2317
2318                        mSettings.enableSystemPackageLPw(packageName);
2319
2320                        try {
2321                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2322                        } catch (PackageManagerException e) {
2323                            Slog.e(TAG, "Failed to parse original system package: "
2324                                    + e.getMessage());
2325                        }
2326                    }
2327                }
2328            }
2329            mExpectingBetter.clear();
2330
2331            // Now that we know all of the shared libraries, update all clients to have
2332            // the correct library paths.
2333            updateAllSharedLibrariesLPw();
2334
2335            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2336                // NOTE: We ignore potential failures here during a system scan (like
2337                // the rest of the commands above) because there's precious little we
2338                // can do about it. A settings error is reported, though.
2339                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2340                        false /* boot complete */);
2341            }
2342
2343            // Now that we know all the packages we are keeping,
2344            // read and update their last usage times.
2345            mPackageUsage.readLP();
2346
2347            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2348                    SystemClock.uptimeMillis());
2349            Slog.i(TAG, "Time to scan packages: "
2350                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2351                    + " seconds");
2352
2353            // If the platform SDK has changed since the last time we booted,
2354            // we need to re-grant app permission to catch any new ones that
2355            // appear.  This is really a hack, and means that apps can in some
2356            // cases get permissions that the user didn't initially explicitly
2357            // allow...  it would be nice to have some better way to handle
2358            // this situation.
2359            int updateFlags = UPDATE_PERMISSIONS_ALL;
2360            if (ver.sdkVersion != mSdkVersion) {
2361                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2362                        + mSdkVersion + "; regranting permissions for internal storage");
2363                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2364            }
2365            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2366            ver.sdkVersion = mSdkVersion;
2367
2368            // If this is the first boot or an update from pre-M, and it is a normal
2369            // boot, then we need to initialize the default preferred apps across
2370            // all defined users.
2371            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2372                for (UserInfo user : sUserManager.getUsers(true)) {
2373                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2374                    applyFactoryDefaultBrowserLPw(user.id);
2375                    primeDomainVerificationsLPw(user.id);
2376                }
2377            }
2378
2379            // Prepare storage for system user really early during boot,
2380            // since core system apps like SettingsProvider and SystemUI
2381            // can't wait for user to start
2382            final int flags;
2383            if (StorageManager.isFileBasedEncryptionEnabled()) {
2384                flags = Installer.FLAG_DE_STORAGE;
2385            } else {
2386                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
2387            }
2388            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2389
2390            // If this is first boot after an OTA, and a normal boot, then
2391            // we need to clear code cache directories.
2392            if (mIsUpgrade && !onlyCore) {
2393                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2394                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2395                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2396                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2397                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2398                    }
2399                }
2400                ver.fingerprint = Build.FINGERPRINT;
2401            }
2402
2403            checkDefaultBrowser();
2404
2405            // clear only after permissions and other defaults have been updated
2406            mExistingSystemPackages.clear();
2407            mPromoteSystemApps = false;
2408
2409            // All the changes are done during package scanning.
2410            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2411
2412            // can downgrade to reader
2413            mSettings.writeLPr();
2414
2415            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2416                    SystemClock.uptimeMillis());
2417
2418            if (!mOnlyCore) {
2419                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2420                mRequiredInstallerPackage = getRequiredInstallerLPr();
2421                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2422                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2423                        mIntentFilterVerifierComponent);
2424            } else {
2425                mRequiredVerifierPackage = null;
2426                mRequiredInstallerPackage = null;
2427                mIntentFilterVerifierComponent = null;
2428                mIntentFilterVerifier = null;
2429            }
2430
2431            mInstallerService = new PackageInstallerService(context, this);
2432
2433            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2434            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2435            // both the installer and resolver must be present to enable ephemeral
2436            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2437                if (DEBUG_EPHEMERAL) {
2438                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2439                            + " installer:" + ephemeralInstallerComponent);
2440                }
2441                mEphemeralResolverComponent = ephemeralResolverComponent;
2442                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2443                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2444                mEphemeralResolverConnection =
2445                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2446            } else {
2447                if (DEBUG_EPHEMERAL) {
2448                    final String missingComponent =
2449                            (ephemeralResolverComponent == null)
2450                            ? (ephemeralInstallerComponent == null)
2451                                    ? "resolver and installer"
2452                                    : "resolver"
2453                            : "installer";
2454                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2455                }
2456                mEphemeralResolverComponent = null;
2457                mEphemeralInstallerComponent = null;
2458                mEphemeralResolverConnection = null;
2459            }
2460
2461            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2462        } // synchronized (mPackages)
2463        } // synchronized (mInstallLock)
2464
2465        // Now after opening every single application zip, make sure they
2466        // are all flushed.  Not really needed, but keeps things nice and
2467        // tidy.
2468        Runtime.getRuntime().gc();
2469
2470        // The initial scanning above does many calls into installd while
2471        // holding the mPackages lock, but we're mostly interested in yelling
2472        // once we have a booted system.
2473        mInstaller.setWarnIfHeld(mPackages);
2474
2475        // Expose private service for system components to use.
2476        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2477    }
2478
2479    @Override
2480    public boolean isFirstBoot() {
2481        return !mRestoredSettings;
2482    }
2483
2484    @Override
2485    public boolean isOnlyCoreApps() {
2486        return mOnlyCore;
2487    }
2488
2489    @Override
2490    public boolean isUpgrade() {
2491        return mIsUpgrade;
2492    }
2493
2494    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2495        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2496
2497        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2498                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2499        if (matches.size() == 1) {
2500            return matches.get(0).getComponentInfo().packageName;
2501        } else {
2502            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2503            return null;
2504        }
2505    }
2506
2507    private @NonNull String getRequiredInstallerLPr() {
2508        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2509        intent.addCategory(Intent.CATEGORY_DEFAULT);
2510        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2511
2512        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2513                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2514        if (matches.size() == 1) {
2515            return matches.get(0).getComponentInfo().packageName;
2516        } else {
2517            throw new RuntimeException("There must be exactly one installer; found " + matches);
2518        }
2519    }
2520
2521    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2522        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2523
2524        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2525                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2526        ResolveInfo best = null;
2527        final int N = matches.size();
2528        for (int i = 0; i < N; i++) {
2529            final ResolveInfo cur = matches.get(i);
2530            final String packageName = cur.getComponentInfo().packageName;
2531            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2532                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2533                continue;
2534            }
2535
2536            if (best == null || cur.priority > best.priority) {
2537                best = cur;
2538            }
2539        }
2540
2541        if (best != null) {
2542            return best.getComponentInfo().getComponentName();
2543        } else {
2544            throw new RuntimeException("There must be at least one intent filter verifier");
2545        }
2546    }
2547
2548    private @Nullable ComponentName getEphemeralResolverLPr() {
2549        final String[] packageArray =
2550                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2551        if (packageArray.length == 0) {
2552            if (DEBUG_EPHEMERAL) {
2553                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2554            }
2555            return null;
2556        }
2557
2558        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2559        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2560                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2561
2562        final int N = resolvers.size();
2563        if (N == 0) {
2564            if (DEBUG_EPHEMERAL) {
2565                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2566            }
2567            return null;
2568        }
2569
2570        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2571        for (int i = 0; i < N; i++) {
2572            final ResolveInfo info = resolvers.get(i);
2573
2574            if (info.serviceInfo == null) {
2575                continue;
2576            }
2577
2578            final String packageName = info.serviceInfo.packageName;
2579            if (!possiblePackages.contains(packageName)) {
2580                if (DEBUG_EPHEMERAL) {
2581                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2582                            + " pkg: " + packageName + ", info:" + info);
2583                }
2584                continue;
2585            }
2586
2587            if (DEBUG_EPHEMERAL) {
2588                Slog.v(TAG, "Ephemeral resolver found;"
2589                        + " pkg: " + packageName + ", info:" + info);
2590            }
2591            return new ComponentName(packageName, info.serviceInfo.name);
2592        }
2593        if (DEBUG_EPHEMERAL) {
2594            Slog.v(TAG, "Ephemeral resolver NOT found");
2595        }
2596        return null;
2597    }
2598
2599    private @Nullable ComponentName getEphemeralInstallerLPr() {
2600        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2601        intent.addCategory(Intent.CATEGORY_DEFAULT);
2602        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2603
2604        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2605                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2606        if (matches.size() == 0) {
2607            return null;
2608        } else if (matches.size() == 1) {
2609            return matches.get(0).getComponentInfo().getComponentName();
2610        } else {
2611            throw new RuntimeException(
2612                    "There must be at most one ephemeral installer; found " + matches);
2613        }
2614    }
2615
2616    private void primeDomainVerificationsLPw(int userId) {
2617        if (DEBUG_DOMAIN_VERIFICATION) {
2618            Slog.d(TAG, "Priming domain verifications in user " + userId);
2619        }
2620
2621        SystemConfig systemConfig = SystemConfig.getInstance();
2622        ArraySet<String> packages = systemConfig.getLinkedApps();
2623        ArraySet<String> domains = new ArraySet<String>();
2624
2625        for (String packageName : packages) {
2626            PackageParser.Package pkg = mPackages.get(packageName);
2627            if (pkg != null) {
2628                if (!pkg.isSystemApp()) {
2629                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2630                    continue;
2631                }
2632
2633                domains.clear();
2634                for (PackageParser.Activity a : pkg.activities) {
2635                    for (ActivityIntentInfo filter : a.intents) {
2636                        if (hasValidDomains(filter)) {
2637                            domains.addAll(filter.getHostsList());
2638                        }
2639                    }
2640                }
2641
2642                if (domains.size() > 0) {
2643                    if (DEBUG_DOMAIN_VERIFICATION) {
2644                        Slog.v(TAG, "      + " + packageName);
2645                    }
2646                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2647                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2648                    // and then 'always' in the per-user state actually used for intent resolution.
2649                    final IntentFilterVerificationInfo ivi;
2650                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2651                            new ArrayList<String>(domains));
2652                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2653                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2654                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2655                } else {
2656                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2657                            + "' does not handle web links");
2658                }
2659            } else {
2660                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2661            }
2662        }
2663
2664        scheduleWritePackageRestrictionsLocked(userId);
2665        scheduleWriteSettingsLocked();
2666    }
2667
2668    private void applyFactoryDefaultBrowserLPw(int userId) {
2669        // The default browser app's package name is stored in a string resource,
2670        // with a product-specific overlay used for vendor customization.
2671        String browserPkg = mContext.getResources().getString(
2672                com.android.internal.R.string.default_browser);
2673        if (!TextUtils.isEmpty(browserPkg)) {
2674            // non-empty string => required to be a known package
2675            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2676            if (ps == null) {
2677                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2678                browserPkg = null;
2679            } else {
2680                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2681            }
2682        }
2683
2684        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2685        // default.  If there's more than one, just leave everything alone.
2686        if (browserPkg == null) {
2687            calculateDefaultBrowserLPw(userId);
2688        }
2689    }
2690
2691    private void calculateDefaultBrowserLPw(int userId) {
2692        List<String> allBrowsers = resolveAllBrowserApps(userId);
2693        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2694        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2695    }
2696
2697    private List<String> resolveAllBrowserApps(int userId) {
2698        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2699        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2700                PackageManager.MATCH_ALL, userId);
2701
2702        final int count = list.size();
2703        List<String> result = new ArrayList<String>(count);
2704        for (int i=0; i<count; i++) {
2705            ResolveInfo info = list.get(i);
2706            if (info.activityInfo == null
2707                    || !info.handleAllWebDataURI
2708                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2709                    || result.contains(info.activityInfo.packageName)) {
2710                continue;
2711            }
2712            result.add(info.activityInfo.packageName);
2713        }
2714
2715        return result;
2716    }
2717
2718    private boolean packageIsBrowser(String packageName, int userId) {
2719        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2720                PackageManager.MATCH_ALL, userId);
2721        final int N = list.size();
2722        for (int i = 0; i < N; i++) {
2723            ResolveInfo info = list.get(i);
2724            if (packageName.equals(info.activityInfo.packageName)) {
2725                return true;
2726            }
2727        }
2728        return false;
2729    }
2730
2731    private void checkDefaultBrowser() {
2732        final int myUserId = UserHandle.myUserId();
2733        final String packageName = getDefaultBrowserPackageName(myUserId);
2734        if (packageName != null) {
2735            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2736            if (info == null) {
2737                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2738                synchronized (mPackages) {
2739                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2740                }
2741            }
2742        }
2743    }
2744
2745    @Override
2746    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2747            throws RemoteException {
2748        try {
2749            return super.onTransact(code, data, reply, flags);
2750        } catch (RuntimeException e) {
2751            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2752                Slog.wtf(TAG, "Package Manager Crash", e);
2753            }
2754            throw e;
2755        }
2756    }
2757
2758    void cleanupInstallFailedPackage(PackageSetting ps) {
2759        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2760
2761        removeDataDirsLI(ps.volumeUuid, ps.name);
2762        if (ps.codePath != null) {
2763            removeCodePathLI(ps.codePath);
2764        }
2765        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2766            if (ps.resourcePath.isDirectory()) {
2767                FileUtils.deleteContents(ps.resourcePath);
2768            }
2769            ps.resourcePath.delete();
2770        }
2771        mSettings.removePackageLPw(ps.name);
2772    }
2773
2774    static int[] appendInts(int[] cur, int[] add) {
2775        if (add == null) return cur;
2776        if (cur == null) return add;
2777        final int N = add.length;
2778        for (int i=0; i<N; i++) {
2779            cur = appendInt(cur, add[i]);
2780        }
2781        return cur;
2782    }
2783
2784    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2785        if (!sUserManager.exists(userId)) return null;
2786        final PackageSetting ps = (PackageSetting) p.mExtras;
2787        if (ps == null) {
2788            return null;
2789        }
2790
2791        final PermissionsState permissionsState = ps.getPermissionsState();
2792
2793        final int[] gids = permissionsState.computeGids(userId);
2794        final Set<String> permissions = permissionsState.getPermissions(userId);
2795        final PackageUserState state = ps.readUserState(userId);
2796
2797        return PackageParser.generatePackageInfo(p, gids, flags,
2798                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2799    }
2800
2801    @Override
2802    public void checkPackageStartable(String packageName, int userId) {
2803        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2804
2805        synchronized (mPackages) {
2806            final PackageSetting ps = mSettings.mPackages.get(packageName);
2807            if (ps == null) {
2808                throw new SecurityException("Package " + packageName + " was not found!");
2809            }
2810
2811            if (ps.frozen) {
2812                throw new SecurityException("Package " + packageName + " is currently frozen!");
2813            }
2814
2815            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2816                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2817                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2818            }
2819        }
2820    }
2821
2822    @Override
2823    public boolean isPackageAvailable(String packageName, int userId) {
2824        if (!sUserManager.exists(userId)) return false;
2825        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2826        synchronized (mPackages) {
2827            PackageParser.Package p = mPackages.get(packageName);
2828            if (p != null) {
2829                final PackageSetting ps = (PackageSetting) p.mExtras;
2830                if (ps != null) {
2831                    final PackageUserState state = ps.readUserState(userId);
2832                    if (state != null) {
2833                        return PackageParser.isAvailable(state);
2834                    }
2835                }
2836            }
2837        }
2838        return false;
2839    }
2840
2841    @Override
2842    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2843        if (!sUserManager.exists(userId)) return null;
2844        flags = updateFlagsForPackage(flags, userId, packageName);
2845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2846        // reader
2847        synchronized (mPackages) {
2848            PackageParser.Package p = mPackages.get(packageName);
2849            if (DEBUG_PACKAGE_INFO)
2850                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2851            if (p != null) {
2852                return generatePackageInfo(p, flags, userId);
2853            }
2854            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2855                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2856            }
2857        }
2858        return null;
2859    }
2860
2861    @Override
2862    public String[] currentToCanonicalPackageNames(String[] names) {
2863        String[] out = new String[names.length];
2864        // reader
2865        synchronized (mPackages) {
2866            for (int i=names.length-1; i>=0; i--) {
2867                PackageSetting ps = mSettings.mPackages.get(names[i]);
2868                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2869            }
2870        }
2871        return out;
2872    }
2873
2874    @Override
2875    public String[] canonicalToCurrentPackageNames(String[] names) {
2876        String[] out = new String[names.length];
2877        // reader
2878        synchronized (mPackages) {
2879            for (int i=names.length-1; i>=0; i--) {
2880                String cur = mSettings.mRenamedPackages.get(names[i]);
2881                out[i] = cur != null ? cur : names[i];
2882            }
2883        }
2884        return out;
2885    }
2886
2887    @Override
2888    public int getPackageUid(String packageName, int flags, int userId) {
2889        if (!sUserManager.exists(userId)) return -1;
2890        flags = updateFlagsForPackage(flags, userId, packageName);
2891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2892
2893        // reader
2894        synchronized (mPackages) {
2895            final PackageParser.Package p = mPackages.get(packageName);
2896            if (p != null && p.isMatch(flags)) {
2897                return UserHandle.getUid(userId, p.applicationInfo.uid);
2898            }
2899            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2900                final PackageSetting ps = mSettings.mPackages.get(packageName);
2901                if (ps != null && ps.isMatch(flags)) {
2902                    return UserHandle.getUid(userId, ps.appId);
2903                }
2904            }
2905        }
2906
2907        return -1;
2908    }
2909
2910    @Override
2911    public int[] getPackageGids(String packageName, int flags, int userId) {
2912        if (!sUserManager.exists(userId)) return null;
2913        flags = updateFlagsForPackage(flags, userId, packageName);
2914        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2915                "getPackageGids");
2916
2917        // reader
2918        synchronized (mPackages) {
2919            final PackageParser.Package p = mPackages.get(packageName);
2920            if (p != null && p.isMatch(flags)) {
2921                PackageSetting ps = (PackageSetting) p.mExtras;
2922                return ps.getPermissionsState().computeGids(userId);
2923            }
2924            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2925                final PackageSetting ps = mSettings.mPackages.get(packageName);
2926                if (ps != null && ps.isMatch(flags)) {
2927                    return ps.getPermissionsState().computeGids(userId);
2928                }
2929            }
2930        }
2931
2932        return null;
2933    }
2934
2935    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2936        if (bp.perm != null) {
2937            return PackageParser.generatePermissionInfo(bp.perm, flags);
2938        }
2939        PermissionInfo pi = new PermissionInfo();
2940        pi.name = bp.name;
2941        pi.packageName = bp.sourcePackage;
2942        pi.nonLocalizedLabel = bp.name;
2943        pi.protectionLevel = bp.protectionLevel;
2944        return pi;
2945    }
2946
2947    @Override
2948    public PermissionInfo getPermissionInfo(String name, int flags) {
2949        // reader
2950        synchronized (mPackages) {
2951            final BasePermission p = mSettings.mPermissions.get(name);
2952            if (p != null) {
2953                return generatePermissionInfo(p, flags);
2954            }
2955            return null;
2956        }
2957    }
2958
2959    @Override
2960    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2961        // reader
2962        synchronized (mPackages) {
2963            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2964            for (BasePermission p : mSettings.mPermissions.values()) {
2965                if (group == null) {
2966                    if (p.perm == null || p.perm.info.group == null) {
2967                        out.add(generatePermissionInfo(p, flags));
2968                    }
2969                } else {
2970                    if (p.perm != null && group.equals(p.perm.info.group)) {
2971                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2972                    }
2973                }
2974            }
2975
2976            if (out.size() > 0) {
2977                return out;
2978            }
2979            return mPermissionGroups.containsKey(group) ? out : null;
2980        }
2981    }
2982
2983    @Override
2984    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2985        // reader
2986        synchronized (mPackages) {
2987            return PackageParser.generatePermissionGroupInfo(
2988                    mPermissionGroups.get(name), flags);
2989        }
2990    }
2991
2992    @Override
2993    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2994        // reader
2995        synchronized (mPackages) {
2996            final int N = mPermissionGroups.size();
2997            ArrayList<PermissionGroupInfo> out
2998                    = new ArrayList<PermissionGroupInfo>(N);
2999            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3000                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3001            }
3002            return out;
3003        }
3004    }
3005
3006    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3007            int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        PackageSetting ps = mSettings.mPackages.get(packageName);
3010        if (ps != null) {
3011            if (ps.pkg == null) {
3012                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3013                        flags, userId);
3014                if (pInfo != null) {
3015                    return pInfo.applicationInfo;
3016                }
3017                return null;
3018            }
3019            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3020                    ps.readUserState(userId), userId);
3021        }
3022        return null;
3023    }
3024
3025    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3026            int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        PackageSetting ps = mSettings.mPackages.get(packageName);
3029        if (ps != null) {
3030            PackageParser.Package pkg = ps.pkg;
3031            if (pkg == null) {
3032                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3033                    return null;
3034                }
3035                // Only data remains, so we aren't worried about code paths
3036                pkg = new PackageParser.Package(packageName);
3037                pkg.applicationInfo.packageName = packageName;
3038                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3039                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3040                pkg.applicationInfo.uid = ps.appId;
3041                pkg.applicationInfo.initForUser(userId);
3042                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3043                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3044            }
3045            return generatePackageInfo(pkg, flags, userId);
3046        }
3047        return null;
3048    }
3049
3050    @Override
3051    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3052        if (!sUserManager.exists(userId)) return null;
3053        flags = updateFlagsForApplication(flags, userId, packageName);
3054        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3055        // writer
3056        synchronized (mPackages) {
3057            PackageParser.Package p = mPackages.get(packageName);
3058            if (DEBUG_PACKAGE_INFO) Log.v(
3059                    TAG, "getApplicationInfo " + packageName
3060                    + ": " + p);
3061            if (p != null) {
3062                PackageSetting ps = mSettings.mPackages.get(packageName);
3063                if (ps == null) return null;
3064                // Note: isEnabledLP() does not apply here - always return info
3065                return PackageParser.generateApplicationInfo(
3066                        p, flags, ps.readUserState(userId), userId);
3067            }
3068            if ("android".equals(packageName)||"system".equals(packageName)) {
3069                return mAndroidApplication;
3070            }
3071            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3072                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3080            final IPackageDataObserver observer) {
3081        mContext.enforceCallingOrSelfPermission(
3082                android.Manifest.permission.CLEAR_APP_CACHE, null);
3083        // Queue up an async operation since clearing cache may take a little while.
3084        mHandler.post(new Runnable() {
3085            public void run() {
3086                mHandler.removeCallbacks(this);
3087                boolean success = true;
3088                synchronized (mInstallLock) {
3089                    try {
3090                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3091                    } catch (InstallerException e) {
3092                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3093                        success = false;
3094                    }
3095                }
3096                if (observer != null) {
3097                    try {
3098                        observer.onRemoveCompleted(null, success);
3099                    } catch (RemoteException e) {
3100                        Slog.w(TAG, "RemoveException when invoking call back");
3101                    }
3102                }
3103            }
3104        });
3105    }
3106
3107    @Override
3108    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3109            final IntentSender pi) {
3110        mContext.enforceCallingOrSelfPermission(
3111                android.Manifest.permission.CLEAR_APP_CACHE, null);
3112        // Queue up an async operation since clearing cache may take a little while.
3113        mHandler.post(new Runnable() {
3114            public void run() {
3115                mHandler.removeCallbacks(this);
3116                boolean success = true;
3117                synchronized (mInstallLock) {
3118                    try {
3119                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3120                    } catch (InstallerException e) {
3121                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3122                        success = false;
3123                    }
3124                }
3125                if(pi != null) {
3126                    try {
3127                        // Callback via pending intent
3128                        int code = success ? 1 : 0;
3129                        pi.sendIntent(null, code, null,
3130                                null, null);
3131                    } catch (SendIntentException e1) {
3132                        Slog.i(TAG, "Failed to send pending intent");
3133                    }
3134                }
3135            }
3136        });
3137    }
3138
3139    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3140        synchronized (mInstallLock) {
3141            try {
3142                mInstaller.freeCache(volumeUuid, freeStorageSize);
3143            } catch (InstallerException e) {
3144                throw new IOException("Failed to free enough space", e);
3145            }
3146        }
3147    }
3148
3149    /**
3150     * Return if the user key is currently unlocked.
3151     */
3152    private boolean isUserKeyUnlocked(int userId) {
3153        if (StorageManager.isFileBasedEncryptionEnabled()) {
3154            final IMountService mount = IMountService.Stub
3155                    .asInterface(ServiceManager.getService("mount"));
3156            if (mount == null) {
3157                Slog.w(TAG, "Early during boot, assuming locked");
3158                return false;
3159            }
3160            final long token = Binder.clearCallingIdentity();
3161            try {
3162                return mount.isUserKeyUnlocked(userId);
3163            } catch (RemoteException e) {
3164                throw e.rethrowAsRuntimeException();
3165            } finally {
3166                Binder.restoreCallingIdentity(token);
3167            }
3168        } else {
3169            return true;
3170        }
3171    }
3172
3173    /**
3174     * Update given flags based on encryption status of current user.
3175     */
3176    private int updateFlags(int flags, int userId) {
3177        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3178                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3179            // Caller expressed an explicit opinion about what encryption
3180            // aware/unaware components they want to see, so fall through and
3181            // give them what they want
3182        } else {
3183            // Caller expressed no opinion, so match based on user state
3184            if (isUserKeyUnlocked(userId)) {
3185                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3186            } else {
3187                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3188            }
3189        }
3190
3191        // Safe mode means we should ignore any third-party apps
3192        if (mSafeMode) {
3193            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3194        }
3195
3196        return flags;
3197    }
3198
3199    /**
3200     * Update given flags when being used to request {@link PackageInfo}.
3201     */
3202    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3203        boolean triaged = true;
3204        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3205                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3206            // Caller is asking for component details, so they'd better be
3207            // asking for specific encryption matching behavior, or be triaged
3208            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3209                    | PackageManager.MATCH_ENCRYPTION_AWARE
3210                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3211                triaged = false;
3212            }
3213        }
3214        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3215                | PackageManager.MATCH_SYSTEM_ONLY
3216                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3217            triaged = false;
3218        }
3219        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3220            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3221                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3222        }
3223        return updateFlags(flags, userId);
3224    }
3225
3226    /**
3227     * Update given flags when being used to request {@link ApplicationInfo}.
3228     */
3229    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3230        return updateFlagsForPackage(flags, userId, cookie);
3231    }
3232
3233    /**
3234     * Update given flags when being used to request {@link ComponentInfo}.
3235     */
3236    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3237        if (cookie instanceof Intent) {
3238            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3239                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3240            }
3241        }
3242
3243        boolean triaged = true;
3244        // Caller is asking for component details, so they'd better be
3245        // asking for specific encryption matching behavior, or be triaged
3246        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3247                | PackageManager.MATCH_ENCRYPTION_AWARE
3248                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3249            triaged = false;
3250        }
3251        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3252            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3253                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3254        }
3255        return updateFlags(flags, userId);
3256    }
3257
3258    /**
3259     * Update given flags when being used to request {@link ResolveInfo}.
3260     */
3261    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3262        return updateFlagsForComponent(flags, userId, cookie);
3263    }
3264
3265    @Override
3266    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3267        if (!sUserManager.exists(userId)) return null;
3268        flags = updateFlagsForComponent(flags, userId, component);
3269        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3270        synchronized (mPackages) {
3271            PackageParser.Activity a = mActivities.mActivities.get(component);
3272
3273            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3274            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3275                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3276                if (ps == null) return null;
3277                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3278                        userId);
3279            }
3280            if (mResolveComponentName.equals(component)) {
3281                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3282                        new PackageUserState(), userId);
3283            }
3284        }
3285        return null;
3286    }
3287
3288    @Override
3289    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3290            String resolvedType) {
3291        synchronized (mPackages) {
3292            if (component.equals(mResolveComponentName)) {
3293                // The resolver supports EVERYTHING!
3294                return true;
3295            }
3296            PackageParser.Activity a = mActivities.mActivities.get(component);
3297            if (a == null) {
3298                return false;
3299            }
3300            for (int i=0; i<a.intents.size(); i++) {
3301                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3302                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3303                    return true;
3304                }
3305            }
3306            return false;
3307        }
3308    }
3309
3310    @Override
3311    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3312        if (!sUserManager.exists(userId)) return null;
3313        flags = updateFlagsForComponent(flags, userId, component);
3314        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3315        synchronized (mPackages) {
3316            PackageParser.Activity a = mReceivers.mActivities.get(component);
3317            if (DEBUG_PACKAGE_INFO) Log.v(
3318                TAG, "getReceiverInfo " + component + ": " + a);
3319            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3320                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3321                if (ps == null) return null;
3322                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3323                        userId);
3324            }
3325        }
3326        return null;
3327    }
3328
3329    @Override
3330    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3331        if (!sUserManager.exists(userId)) return null;
3332        flags = updateFlagsForComponent(flags, userId, component);
3333        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3334        synchronized (mPackages) {
3335            PackageParser.Service s = mServices.mServices.get(component);
3336            if (DEBUG_PACKAGE_INFO) Log.v(
3337                TAG, "getServiceInfo " + component + ": " + s);
3338            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3339                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3340                if (ps == null) return null;
3341                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3342                        userId);
3343            }
3344        }
3345        return null;
3346    }
3347
3348    @Override
3349    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3350        if (!sUserManager.exists(userId)) return null;
3351        flags = updateFlagsForComponent(flags, userId, component);
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3353        synchronized (mPackages) {
3354            PackageParser.Provider p = mProviders.mProviders.get(component);
3355            if (DEBUG_PACKAGE_INFO) Log.v(
3356                TAG, "getProviderInfo " + component + ": " + p);
3357            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3358                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3359                if (ps == null) return null;
3360                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3361                        userId);
3362            }
3363        }
3364        return null;
3365    }
3366
3367    @Override
3368    public String[] getSystemSharedLibraryNames() {
3369        Set<String> libSet;
3370        synchronized (mPackages) {
3371            libSet = mSharedLibraries.keySet();
3372            int size = libSet.size();
3373            if (size > 0) {
3374                String[] libs = new String[size];
3375                libSet.toArray(libs);
3376                return libs;
3377            }
3378        }
3379        return null;
3380    }
3381
3382    /**
3383     * @hide
3384     */
3385    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3386        synchronized (mPackages) {
3387            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3388            if (lib != null && lib.apk != null) {
3389                return mPackages.get(lib.apk);
3390            }
3391        }
3392        return null;
3393    }
3394
3395    @Override
3396    public FeatureInfo[] getSystemAvailableFeatures() {
3397        Collection<FeatureInfo> featSet;
3398        synchronized (mPackages) {
3399            featSet = mAvailableFeatures.values();
3400            int size = featSet.size();
3401            if (size > 0) {
3402                FeatureInfo[] features = new FeatureInfo[size+1];
3403                featSet.toArray(features);
3404                FeatureInfo fi = new FeatureInfo();
3405                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3406                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3407                features[size] = fi;
3408                return features;
3409            }
3410        }
3411        return null;
3412    }
3413
3414    @Override
3415    public boolean hasSystemFeature(String name) {
3416        synchronized (mPackages) {
3417            return mAvailableFeatures.containsKey(name);
3418        }
3419    }
3420
3421    @Override
3422    public int checkPermission(String permName, String pkgName, int userId) {
3423        if (!sUserManager.exists(userId)) {
3424            return PackageManager.PERMISSION_DENIED;
3425        }
3426
3427        synchronized (mPackages) {
3428            final PackageParser.Package p = mPackages.get(pkgName);
3429            if (p != null && p.mExtras != null) {
3430                final PackageSetting ps = (PackageSetting) p.mExtras;
3431                final PermissionsState permissionsState = ps.getPermissionsState();
3432                if (permissionsState.hasPermission(permName, userId)) {
3433                    return PackageManager.PERMISSION_GRANTED;
3434                }
3435                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3436                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3437                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3438                    return PackageManager.PERMISSION_GRANTED;
3439                }
3440            }
3441        }
3442
3443        return PackageManager.PERMISSION_DENIED;
3444    }
3445
3446    @Override
3447    public int checkUidPermission(String permName, int uid) {
3448        final int userId = UserHandle.getUserId(uid);
3449
3450        if (!sUserManager.exists(userId)) {
3451            return PackageManager.PERMISSION_DENIED;
3452        }
3453
3454        synchronized (mPackages) {
3455            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3456            if (obj != null) {
3457                final SettingBase ps = (SettingBase) obj;
3458                final PermissionsState permissionsState = ps.getPermissionsState();
3459                if (permissionsState.hasPermission(permName, userId)) {
3460                    return PackageManager.PERMISSION_GRANTED;
3461                }
3462                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3463                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3464                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3465                    return PackageManager.PERMISSION_GRANTED;
3466                }
3467            } else {
3468                ArraySet<String> perms = mSystemPermissions.get(uid);
3469                if (perms != null) {
3470                    if (perms.contains(permName)) {
3471                        return PackageManager.PERMISSION_GRANTED;
3472                    }
3473                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3474                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3475                        return PackageManager.PERMISSION_GRANTED;
3476                    }
3477                }
3478            }
3479        }
3480
3481        return PackageManager.PERMISSION_DENIED;
3482    }
3483
3484    @Override
3485    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3486        if (UserHandle.getCallingUserId() != userId) {
3487            mContext.enforceCallingPermission(
3488                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3489                    "isPermissionRevokedByPolicy for user " + userId);
3490        }
3491
3492        if (checkPermission(permission, packageName, userId)
3493                == PackageManager.PERMISSION_GRANTED) {
3494            return false;
3495        }
3496
3497        final long identity = Binder.clearCallingIdentity();
3498        try {
3499            final int flags = getPermissionFlags(permission, packageName, userId);
3500            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3501        } finally {
3502            Binder.restoreCallingIdentity(identity);
3503        }
3504    }
3505
3506    @Override
3507    public String getPermissionControllerPackageName() {
3508        synchronized (mPackages) {
3509            return mRequiredInstallerPackage;
3510        }
3511    }
3512
3513    /**
3514     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3515     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3516     * @param checkShell TODO(yamasani):
3517     * @param message the message to log on security exception
3518     */
3519    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3520            boolean checkShell, String message) {
3521        if (userId < 0) {
3522            throw new IllegalArgumentException("Invalid userId " + userId);
3523        }
3524        if (checkShell) {
3525            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3526        }
3527        if (userId == UserHandle.getUserId(callingUid)) return;
3528        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3529            if (requireFullPermission) {
3530                mContext.enforceCallingOrSelfPermission(
3531                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3532            } else {
3533                try {
3534                    mContext.enforceCallingOrSelfPermission(
3535                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3536                } catch (SecurityException se) {
3537                    mContext.enforceCallingOrSelfPermission(
3538                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3539                }
3540            }
3541        }
3542    }
3543
3544    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3545        if (callingUid == Process.SHELL_UID) {
3546            if (userHandle >= 0
3547                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3548                throw new SecurityException("Shell does not have permission to access user "
3549                        + userHandle);
3550            } else if (userHandle < 0) {
3551                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3552                        + Debug.getCallers(3));
3553            }
3554        }
3555    }
3556
3557    private BasePermission findPermissionTreeLP(String permName) {
3558        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3559            if (permName.startsWith(bp.name) &&
3560                    permName.length() > bp.name.length() &&
3561                    permName.charAt(bp.name.length()) == '.') {
3562                return bp;
3563            }
3564        }
3565        return null;
3566    }
3567
3568    private BasePermission checkPermissionTreeLP(String permName) {
3569        if (permName != null) {
3570            BasePermission bp = findPermissionTreeLP(permName);
3571            if (bp != null) {
3572                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3573                    return bp;
3574                }
3575                throw new SecurityException("Calling uid "
3576                        + Binder.getCallingUid()
3577                        + " is not allowed to add to permission tree "
3578                        + bp.name + " owned by uid " + bp.uid);
3579            }
3580        }
3581        throw new SecurityException("No permission tree found for " + permName);
3582    }
3583
3584    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3585        if (s1 == null) {
3586            return s2 == null;
3587        }
3588        if (s2 == null) {
3589            return false;
3590        }
3591        if (s1.getClass() != s2.getClass()) {
3592            return false;
3593        }
3594        return s1.equals(s2);
3595    }
3596
3597    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3598        if (pi1.icon != pi2.icon) return false;
3599        if (pi1.logo != pi2.logo) return false;
3600        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3601        if (!compareStrings(pi1.name, pi2.name)) return false;
3602        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3603        // We'll take care of setting this one.
3604        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3605        // These are not currently stored in settings.
3606        //if (!compareStrings(pi1.group, pi2.group)) return false;
3607        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3608        //if (pi1.labelRes != pi2.labelRes) return false;
3609        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3610        return true;
3611    }
3612
3613    int permissionInfoFootprint(PermissionInfo info) {
3614        int size = info.name.length();
3615        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3616        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3617        return size;
3618    }
3619
3620    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3621        int size = 0;
3622        for (BasePermission perm : mSettings.mPermissions.values()) {
3623            if (perm.uid == tree.uid) {
3624                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3625            }
3626        }
3627        return size;
3628    }
3629
3630    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3631        // We calculate the max size of permissions defined by this uid and throw
3632        // if that plus the size of 'info' would exceed our stated maximum.
3633        if (tree.uid != Process.SYSTEM_UID) {
3634            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3635            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3636                throw new SecurityException("Permission tree size cap exceeded");
3637            }
3638        }
3639    }
3640
3641    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3642        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3643            throw new SecurityException("Label must be specified in permission");
3644        }
3645        BasePermission tree = checkPermissionTreeLP(info.name);
3646        BasePermission bp = mSettings.mPermissions.get(info.name);
3647        boolean added = bp == null;
3648        boolean changed = true;
3649        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3650        if (added) {
3651            enforcePermissionCapLocked(info, tree);
3652            bp = new BasePermission(info.name, tree.sourcePackage,
3653                    BasePermission.TYPE_DYNAMIC);
3654        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3655            throw new SecurityException(
3656                    "Not allowed to modify non-dynamic permission "
3657                    + info.name);
3658        } else {
3659            if (bp.protectionLevel == fixedLevel
3660                    && bp.perm.owner.equals(tree.perm.owner)
3661                    && bp.uid == tree.uid
3662                    && comparePermissionInfos(bp.perm.info, info)) {
3663                changed = false;
3664            }
3665        }
3666        bp.protectionLevel = fixedLevel;
3667        info = new PermissionInfo(info);
3668        info.protectionLevel = fixedLevel;
3669        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3670        bp.perm.info.packageName = tree.perm.info.packageName;
3671        bp.uid = tree.uid;
3672        if (added) {
3673            mSettings.mPermissions.put(info.name, bp);
3674        }
3675        if (changed) {
3676            if (!async) {
3677                mSettings.writeLPr();
3678            } else {
3679                scheduleWriteSettingsLocked();
3680            }
3681        }
3682        return added;
3683    }
3684
3685    @Override
3686    public boolean addPermission(PermissionInfo info) {
3687        synchronized (mPackages) {
3688            return addPermissionLocked(info, false);
3689        }
3690    }
3691
3692    @Override
3693    public boolean addPermissionAsync(PermissionInfo info) {
3694        synchronized (mPackages) {
3695            return addPermissionLocked(info, true);
3696        }
3697    }
3698
3699    @Override
3700    public void removePermission(String name) {
3701        synchronized (mPackages) {
3702            checkPermissionTreeLP(name);
3703            BasePermission bp = mSettings.mPermissions.get(name);
3704            if (bp != null) {
3705                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3706                    throw new SecurityException(
3707                            "Not allowed to modify non-dynamic permission "
3708                            + name);
3709                }
3710                mSettings.mPermissions.remove(name);
3711                mSettings.writeLPr();
3712            }
3713        }
3714    }
3715
3716    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3717            BasePermission bp) {
3718        int index = pkg.requestedPermissions.indexOf(bp.name);
3719        if (index == -1) {
3720            throw new SecurityException("Package " + pkg.packageName
3721                    + " has not requested permission " + bp.name);
3722        }
3723        if (!bp.isRuntime() && !bp.isDevelopment()) {
3724            throw new SecurityException("Permission " + bp.name
3725                    + " is not a changeable permission type");
3726        }
3727    }
3728
3729    @Override
3730    public void grantRuntimePermission(String packageName, String name, final int userId) {
3731        if (!sUserManager.exists(userId)) {
3732            Log.e(TAG, "No such user:" + userId);
3733            return;
3734        }
3735
3736        mContext.enforceCallingOrSelfPermission(
3737                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3738                "grantRuntimePermission");
3739
3740        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3741                "grantRuntimePermission");
3742
3743        final int uid;
3744        final SettingBase sb;
3745
3746        synchronized (mPackages) {
3747            final PackageParser.Package pkg = mPackages.get(packageName);
3748            if (pkg == null) {
3749                throw new IllegalArgumentException("Unknown package: " + packageName);
3750            }
3751
3752            final BasePermission bp = mSettings.mPermissions.get(name);
3753            if (bp == null) {
3754                throw new IllegalArgumentException("Unknown permission: " + name);
3755            }
3756
3757            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3758
3759            // If a permission review is required for legacy apps we represent
3760            // their permissions as always granted runtime ones since we need
3761            // to keep the review required permission flag per user while an
3762            // install permission's state is shared across all users.
3763            if (Build.PERMISSIONS_REVIEW_REQUIRED
3764                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3765                    && bp.isRuntime()) {
3766                return;
3767            }
3768
3769            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3770            sb = (SettingBase) pkg.mExtras;
3771            if (sb == null) {
3772                throw new IllegalArgumentException("Unknown package: " + packageName);
3773            }
3774
3775            final PermissionsState permissionsState = sb.getPermissionsState();
3776
3777            final int flags = permissionsState.getPermissionFlags(name, userId);
3778            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3779                throw new SecurityException("Cannot grant system fixed permission "
3780                        + name + " for package " + packageName);
3781            }
3782
3783            if (bp.isDevelopment()) {
3784                // Development permissions must be handled specially, since they are not
3785                // normal runtime permissions.  For now they apply to all users.
3786                if (permissionsState.grantInstallPermission(bp) !=
3787                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3788                    scheduleWriteSettingsLocked();
3789                }
3790                return;
3791            }
3792
3793            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3794                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3795                return;
3796            }
3797
3798            final int result = permissionsState.grantRuntimePermission(bp, userId);
3799            switch (result) {
3800                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3801                    return;
3802                }
3803
3804                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3805                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3806                    mHandler.post(new Runnable() {
3807                        @Override
3808                        public void run() {
3809                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3810                        }
3811                    });
3812                }
3813                break;
3814            }
3815
3816            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3817
3818            // Not critical if that is lost - app has to request again.
3819            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3820        }
3821
3822        // Only need to do this if user is initialized. Otherwise it's a new user
3823        // and there are no processes running as the user yet and there's no need
3824        // to make an expensive call to remount processes for the changed permissions.
3825        if (READ_EXTERNAL_STORAGE.equals(name)
3826                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3827            final long token = Binder.clearCallingIdentity();
3828            try {
3829                if (sUserManager.isInitialized(userId)) {
3830                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3831                            MountServiceInternal.class);
3832                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3833                }
3834            } finally {
3835                Binder.restoreCallingIdentity(token);
3836            }
3837        }
3838    }
3839
3840    @Override
3841    public void revokeRuntimePermission(String packageName, String name, int userId) {
3842        if (!sUserManager.exists(userId)) {
3843            Log.e(TAG, "No such user:" + userId);
3844            return;
3845        }
3846
3847        mContext.enforceCallingOrSelfPermission(
3848                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3849                "revokeRuntimePermission");
3850
3851        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3852                "revokeRuntimePermission");
3853
3854        final int appId;
3855
3856        synchronized (mPackages) {
3857            final PackageParser.Package pkg = mPackages.get(packageName);
3858            if (pkg == null) {
3859                throw new IllegalArgumentException("Unknown package: " + packageName);
3860            }
3861
3862            final BasePermission bp = mSettings.mPermissions.get(name);
3863            if (bp == null) {
3864                throw new IllegalArgumentException("Unknown permission: " + name);
3865            }
3866
3867            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3868
3869            // If a permission review is required for legacy apps we represent
3870            // their permissions as always granted runtime ones since we need
3871            // to keep the review required permission flag per user while an
3872            // install permission's state is shared across all users.
3873            if (Build.PERMISSIONS_REVIEW_REQUIRED
3874                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3875                    && bp.isRuntime()) {
3876                return;
3877            }
3878
3879            SettingBase sb = (SettingBase) pkg.mExtras;
3880            if (sb == null) {
3881                throw new IllegalArgumentException("Unknown package: " + packageName);
3882            }
3883
3884            final PermissionsState permissionsState = sb.getPermissionsState();
3885
3886            final int flags = permissionsState.getPermissionFlags(name, userId);
3887            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3888                throw new SecurityException("Cannot revoke system fixed permission "
3889                        + name + " for package " + packageName);
3890            }
3891
3892            if (bp.isDevelopment()) {
3893                // Development permissions must be handled specially, since they are not
3894                // normal runtime permissions.  For now they apply to all users.
3895                if (permissionsState.revokeInstallPermission(bp) !=
3896                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3897                    scheduleWriteSettingsLocked();
3898                }
3899                return;
3900            }
3901
3902            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3903                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3904                return;
3905            }
3906
3907            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3908
3909            // Critical, after this call app should never have the permission.
3910            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3911
3912            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3913        }
3914
3915        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3916    }
3917
3918    @Override
3919    public void resetRuntimePermissions() {
3920        mContext.enforceCallingOrSelfPermission(
3921                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3922                "revokeRuntimePermission");
3923
3924        int callingUid = Binder.getCallingUid();
3925        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3926            mContext.enforceCallingOrSelfPermission(
3927                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3928                    "resetRuntimePermissions");
3929        }
3930
3931        synchronized (mPackages) {
3932            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3933            for (int userId : UserManagerService.getInstance().getUserIds()) {
3934                final int packageCount = mPackages.size();
3935                for (int i = 0; i < packageCount; i++) {
3936                    PackageParser.Package pkg = mPackages.valueAt(i);
3937                    if (!(pkg.mExtras instanceof PackageSetting)) {
3938                        continue;
3939                    }
3940                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3941                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3942                }
3943            }
3944        }
3945    }
3946
3947    @Override
3948    public int getPermissionFlags(String name, String packageName, int userId) {
3949        if (!sUserManager.exists(userId)) {
3950            return 0;
3951        }
3952
3953        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3954
3955        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3956                "getPermissionFlags");
3957
3958        synchronized (mPackages) {
3959            final PackageParser.Package pkg = mPackages.get(packageName);
3960            if (pkg == null) {
3961                throw new IllegalArgumentException("Unknown package: " + packageName);
3962            }
3963
3964            final BasePermission bp = mSettings.mPermissions.get(name);
3965            if (bp == null) {
3966                throw new IllegalArgumentException("Unknown permission: " + name);
3967            }
3968
3969            SettingBase sb = (SettingBase) pkg.mExtras;
3970            if (sb == null) {
3971                throw new IllegalArgumentException("Unknown package: " + packageName);
3972            }
3973
3974            PermissionsState permissionsState = sb.getPermissionsState();
3975            return permissionsState.getPermissionFlags(name, userId);
3976        }
3977    }
3978
3979    @Override
3980    public void updatePermissionFlags(String name, String packageName, int flagMask,
3981            int flagValues, int userId) {
3982        if (!sUserManager.exists(userId)) {
3983            return;
3984        }
3985
3986        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3987
3988        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3989                "updatePermissionFlags");
3990
3991        // Only the system can change these flags and nothing else.
3992        if (getCallingUid() != Process.SYSTEM_UID) {
3993            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3994            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3995            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3996            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3997            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3998        }
3999
4000        synchronized (mPackages) {
4001            final PackageParser.Package pkg = mPackages.get(packageName);
4002            if (pkg == null) {
4003                throw new IllegalArgumentException("Unknown package: " + packageName);
4004            }
4005
4006            final BasePermission bp = mSettings.mPermissions.get(name);
4007            if (bp == null) {
4008                throw new IllegalArgumentException("Unknown permission: " + name);
4009            }
4010
4011            SettingBase sb = (SettingBase) pkg.mExtras;
4012            if (sb == null) {
4013                throw new IllegalArgumentException("Unknown package: " + packageName);
4014            }
4015
4016            PermissionsState permissionsState = sb.getPermissionsState();
4017
4018            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4019
4020            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4021                // Install and runtime permissions are stored in different places,
4022                // so figure out what permission changed and persist the change.
4023                if (permissionsState.getInstallPermissionState(name) != null) {
4024                    scheduleWriteSettingsLocked();
4025                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4026                        || hadState) {
4027                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4028                }
4029            }
4030        }
4031    }
4032
4033    /**
4034     * Update the permission flags for all packages and runtime permissions of a user in order
4035     * to allow device or profile owner to remove POLICY_FIXED.
4036     */
4037    @Override
4038    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4039        if (!sUserManager.exists(userId)) {
4040            return;
4041        }
4042
4043        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4044
4045        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4046                "updatePermissionFlagsForAllApps");
4047
4048        // Only the system can change system fixed flags.
4049        if (getCallingUid() != Process.SYSTEM_UID) {
4050            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4051            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4052        }
4053
4054        synchronized (mPackages) {
4055            boolean changed = false;
4056            final int packageCount = mPackages.size();
4057            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4058                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4059                SettingBase sb = (SettingBase) pkg.mExtras;
4060                if (sb == null) {
4061                    continue;
4062                }
4063                PermissionsState permissionsState = sb.getPermissionsState();
4064                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4065                        userId, flagMask, flagValues);
4066            }
4067            if (changed) {
4068                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4069            }
4070        }
4071    }
4072
4073    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4074        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4075                != PackageManager.PERMISSION_GRANTED
4076            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4077                != PackageManager.PERMISSION_GRANTED) {
4078            throw new SecurityException(message + " requires "
4079                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4080                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4081        }
4082    }
4083
4084    @Override
4085    public boolean shouldShowRequestPermissionRationale(String permissionName,
4086            String packageName, int userId) {
4087        if (UserHandle.getCallingUserId() != userId) {
4088            mContext.enforceCallingPermission(
4089                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4090                    "canShowRequestPermissionRationale for user " + userId);
4091        }
4092
4093        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4094        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4095            return false;
4096        }
4097
4098        if (checkPermission(permissionName, packageName, userId)
4099                == PackageManager.PERMISSION_GRANTED) {
4100            return false;
4101        }
4102
4103        final int flags;
4104
4105        final long identity = Binder.clearCallingIdentity();
4106        try {
4107            flags = getPermissionFlags(permissionName,
4108                    packageName, userId);
4109        } finally {
4110            Binder.restoreCallingIdentity(identity);
4111        }
4112
4113        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4114                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4115                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4116
4117        if ((flags & fixedFlags) != 0) {
4118            return false;
4119        }
4120
4121        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4122    }
4123
4124    @Override
4125    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4126        mContext.enforceCallingOrSelfPermission(
4127                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4128                "addOnPermissionsChangeListener");
4129
4130        synchronized (mPackages) {
4131            mOnPermissionChangeListeners.addListenerLocked(listener);
4132        }
4133    }
4134
4135    @Override
4136    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4137        synchronized (mPackages) {
4138            mOnPermissionChangeListeners.removeListenerLocked(listener);
4139        }
4140    }
4141
4142    @Override
4143    public boolean isProtectedBroadcast(String actionName) {
4144        synchronized (mPackages) {
4145            if (mProtectedBroadcasts.contains(actionName)) {
4146                return true;
4147            } else if (actionName != null) {
4148                // TODO: remove these terrible hacks
4149                if (actionName.startsWith("android.net.netmon.lingerExpired")
4150                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4151                    return true;
4152                }
4153            }
4154        }
4155        return false;
4156    }
4157
4158    @Override
4159    public int checkSignatures(String pkg1, String pkg2) {
4160        synchronized (mPackages) {
4161            final PackageParser.Package p1 = mPackages.get(pkg1);
4162            final PackageParser.Package p2 = mPackages.get(pkg2);
4163            if (p1 == null || p1.mExtras == null
4164                    || p2 == null || p2.mExtras == null) {
4165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4166            }
4167            return compareSignatures(p1.mSignatures, p2.mSignatures);
4168        }
4169    }
4170
4171    @Override
4172    public int checkUidSignatures(int uid1, int uid2) {
4173        // Map to base uids.
4174        uid1 = UserHandle.getAppId(uid1);
4175        uid2 = UserHandle.getAppId(uid2);
4176        // reader
4177        synchronized (mPackages) {
4178            Signature[] s1;
4179            Signature[] s2;
4180            Object obj = mSettings.getUserIdLPr(uid1);
4181            if (obj != null) {
4182                if (obj instanceof SharedUserSetting) {
4183                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4184                } else if (obj instanceof PackageSetting) {
4185                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4186                } else {
4187                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4188                }
4189            } else {
4190                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4191            }
4192            obj = mSettings.getUserIdLPr(uid2);
4193            if (obj != null) {
4194                if (obj instanceof SharedUserSetting) {
4195                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4196                } else if (obj instanceof PackageSetting) {
4197                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4198                } else {
4199                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4200                }
4201            } else {
4202                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4203            }
4204            return compareSignatures(s1, s2);
4205        }
4206    }
4207
4208    private void killUid(int appId, int userId, String reason) {
4209        final long identity = Binder.clearCallingIdentity();
4210        try {
4211            IActivityManager am = ActivityManagerNative.getDefault();
4212            if (am != null) {
4213                try {
4214                    am.killUid(appId, userId, reason);
4215                } catch (RemoteException e) {
4216                    /* ignore - same process */
4217                }
4218            }
4219        } finally {
4220            Binder.restoreCallingIdentity(identity);
4221        }
4222    }
4223
4224    /**
4225     * Compares two sets of signatures. Returns:
4226     * <br />
4227     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4228     * <br />
4229     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4230     * <br />
4231     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4232     * <br />
4233     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4234     * <br />
4235     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4236     */
4237    static int compareSignatures(Signature[] s1, Signature[] s2) {
4238        if (s1 == null) {
4239            return s2 == null
4240                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4241                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4242        }
4243
4244        if (s2 == null) {
4245            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4246        }
4247
4248        if (s1.length != s2.length) {
4249            return PackageManager.SIGNATURE_NO_MATCH;
4250        }
4251
4252        // Since both signature sets are of size 1, we can compare without HashSets.
4253        if (s1.length == 1) {
4254            return s1[0].equals(s2[0]) ?
4255                    PackageManager.SIGNATURE_MATCH :
4256                    PackageManager.SIGNATURE_NO_MATCH;
4257        }
4258
4259        ArraySet<Signature> set1 = new ArraySet<Signature>();
4260        for (Signature sig : s1) {
4261            set1.add(sig);
4262        }
4263        ArraySet<Signature> set2 = new ArraySet<Signature>();
4264        for (Signature sig : s2) {
4265            set2.add(sig);
4266        }
4267        // Make sure s2 contains all signatures in s1.
4268        if (set1.equals(set2)) {
4269            return PackageManager.SIGNATURE_MATCH;
4270        }
4271        return PackageManager.SIGNATURE_NO_MATCH;
4272    }
4273
4274    /**
4275     * If the database version for this type of package (internal storage or
4276     * external storage) is less than the version where package signatures
4277     * were updated, return true.
4278     */
4279    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4280        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4281        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4282    }
4283
4284    /**
4285     * Used for backward compatibility to make sure any packages with
4286     * certificate chains get upgraded to the new style. {@code existingSigs}
4287     * will be in the old format (since they were stored on disk from before the
4288     * system upgrade) and {@code scannedSigs} will be in the newer format.
4289     */
4290    private int compareSignaturesCompat(PackageSignatures existingSigs,
4291            PackageParser.Package scannedPkg) {
4292        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4293            return PackageManager.SIGNATURE_NO_MATCH;
4294        }
4295
4296        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4297        for (Signature sig : existingSigs.mSignatures) {
4298            existingSet.add(sig);
4299        }
4300        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4301        for (Signature sig : scannedPkg.mSignatures) {
4302            try {
4303                Signature[] chainSignatures = sig.getChainSignatures();
4304                for (Signature chainSig : chainSignatures) {
4305                    scannedCompatSet.add(chainSig);
4306                }
4307            } catch (CertificateEncodingException e) {
4308                scannedCompatSet.add(sig);
4309            }
4310        }
4311        /*
4312         * Make sure the expanded scanned set contains all signatures in the
4313         * existing one.
4314         */
4315        if (scannedCompatSet.equals(existingSet)) {
4316            // Migrate the old signatures to the new scheme.
4317            existingSigs.assignSignatures(scannedPkg.mSignatures);
4318            // The new KeySets will be re-added later in the scanning process.
4319            synchronized (mPackages) {
4320                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4321            }
4322            return PackageManager.SIGNATURE_MATCH;
4323        }
4324        return PackageManager.SIGNATURE_NO_MATCH;
4325    }
4326
4327    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4328        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4329        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4330    }
4331
4332    private int compareSignaturesRecover(PackageSignatures existingSigs,
4333            PackageParser.Package scannedPkg) {
4334        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4335            return PackageManager.SIGNATURE_NO_MATCH;
4336        }
4337
4338        String msg = null;
4339        try {
4340            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4341                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4342                        + scannedPkg.packageName);
4343                return PackageManager.SIGNATURE_MATCH;
4344            }
4345        } catch (CertificateException e) {
4346            msg = e.getMessage();
4347        }
4348
4349        logCriticalInfo(Log.INFO,
4350                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4351        return PackageManager.SIGNATURE_NO_MATCH;
4352    }
4353
4354    @Override
4355    public String[] getPackagesForUid(int uid) {
4356        uid = UserHandle.getAppId(uid);
4357        // reader
4358        synchronized (mPackages) {
4359            Object obj = mSettings.getUserIdLPr(uid);
4360            if (obj instanceof SharedUserSetting) {
4361                final SharedUserSetting sus = (SharedUserSetting) obj;
4362                final int N = sus.packages.size();
4363                final String[] res = new String[N];
4364                final Iterator<PackageSetting> it = sus.packages.iterator();
4365                int i = 0;
4366                while (it.hasNext()) {
4367                    res[i++] = it.next().name;
4368                }
4369                return res;
4370            } else if (obj instanceof PackageSetting) {
4371                final PackageSetting ps = (PackageSetting) obj;
4372                return new String[] { ps.name };
4373            }
4374        }
4375        return null;
4376    }
4377
4378    @Override
4379    public String getNameForUid(int uid) {
4380        // reader
4381        synchronized (mPackages) {
4382            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4383            if (obj instanceof SharedUserSetting) {
4384                final SharedUserSetting sus = (SharedUserSetting) obj;
4385                return sus.name + ":" + sus.userId;
4386            } else if (obj instanceof PackageSetting) {
4387                final PackageSetting ps = (PackageSetting) obj;
4388                return ps.name;
4389            }
4390        }
4391        return null;
4392    }
4393
4394    @Override
4395    public int getUidForSharedUser(String sharedUserName) {
4396        if(sharedUserName == null) {
4397            return -1;
4398        }
4399        // reader
4400        synchronized (mPackages) {
4401            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4402            if (suid == null) {
4403                return -1;
4404            }
4405            return suid.userId;
4406        }
4407    }
4408
4409    @Override
4410    public int getFlagsForUid(int uid) {
4411        synchronized (mPackages) {
4412            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4413            if (obj instanceof SharedUserSetting) {
4414                final SharedUserSetting sus = (SharedUserSetting) obj;
4415                return sus.pkgFlags;
4416            } else if (obj instanceof PackageSetting) {
4417                final PackageSetting ps = (PackageSetting) obj;
4418                return ps.pkgFlags;
4419            }
4420        }
4421        return 0;
4422    }
4423
4424    @Override
4425    public int getPrivateFlagsForUid(int uid) {
4426        synchronized (mPackages) {
4427            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4428            if (obj instanceof SharedUserSetting) {
4429                final SharedUserSetting sus = (SharedUserSetting) obj;
4430                return sus.pkgPrivateFlags;
4431            } else if (obj instanceof PackageSetting) {
4432                final PackageSetting ps = (PackageSetting) obj;
4433                return ps.pkgPrivateFlags;
4434            }
4435        }
4436        return 0;
4437    }
4438
4439    @Override
4440    public boolean isUidPrivileged(int uid) {
4441        uid = UserHandle.getAppId(uid);
4442        // reader
4443        synchronized (mPackages) {
4444            Object obj = mSettings.getUserIdLPr(uid);
4445            if (obj instanceof SharedUserSetting) {
4446                final SharedUserSetting sus = (SharedUserSetting) obj;
4447                final Iterator<PackageSetting> it = sus.packages.iterator();
4448                while (it.hasNext()) {
4449                    if (it.next().isPrivileged()) {
4450                        return true;
4451                    }
4452                }
4453            } else if (obj instanceof PackageSetting) {
4454                final PackageSetting ps = (PackageSetting) obj;
4455                return ps.isPrivileged();
4456            }
4457        }
4458        return false;
4459    }
4460
4461    @Override
4462    public String[] getAppOpPermissionPackages(String permissionName) {
4463        synchronized (mPackages) {
4464            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4465            if (pkgs == null) {
4466                return null;
4467            }
4468            return pkgs.toArray(new String[pkgs.size()]);
4469        }
4470    }
4471
4472    @Override
4473    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4474            int flags, int userId) {
4475        if (!sUserManager.exists(userId)) return null;
4476        flags = updateFlagsForResolve(flags, userId, intent);
4477        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4478        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4479        final ResolveInfo bestChoice =
4480                chooseBestActivity(intent, resolvedType, flags, query, userId);
4481
4482        if (isEphemeralAllowed(intent, query, userId)) {
4483            final EphemeralResolveInfo ai =
4484                    getEphemeralResolveInfo(intent, resolvedType, userId);
4485            if (ai != null) {
4486                if (DEBUG_EPHEMERAL) {
4487                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4488                }
4489                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4490                bestChoice.ephemeralResolveInfo = ai;
4491            }
4492        }
4493        return bestChoice;
4494    }
4495
4496    @Override
4497    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4498            IntentFilter filter, int match, ComponentName activity) {
4499        final int userId = UserHandle.getCallingUserId();
4500        if (DEBUG_PREFERRED) {
4501            Log.v(TAG, "setLastChosenActivity intent=" + intent
4502                + " resolvedType=" + resolvedType
4503                + " flags=" + flags
4504                + " filter=" + filter
4505                + " match=" + match
4506                + " activity=" + activity);
4507            filter.dump(new PrintStreamPrinter(System.out), "    ");
4508        }
4509        intent.setComponent(null);
4510        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4511        // Find any earlier preferred or last chosen entries and nuke them
4512        findPreferredActivity(intent, resolvedType,
4513                flags, query, 0, false, true, false, userId);
4514        // Add the new activity as the last chosen for this filter
4515        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4516                "Setting last chosen");
4517    }
4518
4519    @Override
4520    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4521        final int userId = UserHandle.getCallingUserId();
4522        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4523        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4524        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4525                false, false, false, userId);
4526    }
4527
4528
4529    private boolean isEphemeralAllowed(
4530            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4531        // Short circuit and return early if possible.
4532        if (DISABLE_EPHEMERAL_APPS) {
4533            return false;
4534        }
4535        final int callingUser = UserHandle.getCallingUserId();
4536        if (callingUser != UserHandle.USER_SYSTEM) {
4537            return false;
4538        }
4539        if (mEphemeralResolverConnection == null) {
4540            return false;
4541        }
4542        if (intent.getComponent() != null) {
4543            return false;
4544        }
4545        if (intent.getPackage() != null) {
4546            return false;
4547        }
4548        final boolean isWebUri = hasWebURI(intent);
4549        if (!isWebUri) {
4550            return false;
4551        }
4552        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4553        synchronized (mPackages) {
4554            final int count = resolvedActivites.size();
4555            for (int n = 0; n < count; n++) {
4556                ResolveInfo info = resolvedActivites.get(n);
4557                String packageName = info.activityInfo.packageName;
4558                PackageSetting ps = mSettings.mPackages.get(packageName);
4559                if (ps != null) {
4560                    // Try to get the status from User settings first
4561                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4562                    int status = (int) (packedStatus >> 32);
4563                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4564                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4565                        if (DEBUG_EPHEMERAL) {
4566                            Slog.v(TAG, "DENY ephemeral apps;"
4567                                + " pkg: " + packageName + ", status: " + status);
4568                        }
4569                        return false;
4570                    }
4571                }
4572            }
4573        }
4574        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4575        return true;
4576    }
4577
4578    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4579            int userId) {
4580        MessageDigest digest = null;
4581        try {
4582            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4583        } catch (NoSuchAlgorithmException e) {
4584            // If we can't create a digest, ignore ephemeral apps.
4585            return null;
4586        }
4587
4588        final byte[] hostBytes = intent.getData().getHost().getBytes();
4589        final byte[] digestBytes = digest.digest(hostBytes);
4590        int shaPrefix =
4591                digestBytes[0] << 24
4592                | digestBytes[1] << 16
4593                | digestBytes[2] << 8
4594                | digestBytes[3] << 0;
4595        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4596                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4597        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4598            // No hash prefix match; there are no ephemeral apps for this domain.
4599            return null;
4600        }
4601        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4602            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4603            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4604                continue;
4605            }
4606            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4607            // No filters; this should never happen.
4608            if (filters.isEmpty()) {
4609                continue;
4610            }
4611            // We have a domain match; resolve the filters to see if anything matches.
4612            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4613            for (int j = filters.size() - 1; j >= 0; --j) {
4614                final EphemeralResolveIntentInfo intentInfo =
4615                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4616                ephemeralResolver.addFilter(intentInfo);
4617            }
4618            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4619                    intent, resolvedType, false /*defaultOnly*/, userId);
4620            if (!matchedResolveInfoList.isEmpty()) {
4621                return matchedResolveInfoList.get(0);
4622            }
4623        }
4624        // Hash or filter mis-match; no ephemeral apps for this domain.
4625        return null;
4626    }
4627
4628    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4629            int flags, List<ResolveInfo> query, int userId) {
4630        if (query != null) {
4631            final int N = query.size();
4632            if (N == 1) {
4633                return query.get(0);
4634            } else if (N > 1) {
4635                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4636                // If there is more than one activity with the same priority,
4637                // then let the user decide between them.
4638                ResolveInfo r0 = query.get(0);
4639                ResolveInfo r1 = query.get(1);
4640                if (DEBUG_INTENT_MATCHING || debug) {
4641                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4642                            + r1.activityInfo.name + "=" + r1.priority);
4643                }
4644                // If the first activity has a higher priority, or a different
4645                // default, then it is always desirable to pick it.
4646                if (r0.priority != r1.priority
4647                        || r0.preferredOrder != r1.preferredOrder
4648                        || r0.isDefault != r1.isDefault) {
4649                    return query.get(0);
4650                }
4651                // If we have saved a preference for a preferred activity for
4652                // this Intent, use that.
4653                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4654                        flags, query, r0.priority, true, false, debug, userId);
4655                if (ri != null) {
4656                    return ri;
4657                }
4658                ri = new ResolveInfo(mResolveInfo);
4659                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4660                ri.activityInfo.applicationInfo = new ApplicationInfo(
4661                        ri.activityInfo.applicationInfo);
4662                if (userId != 0) {
4663                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4664                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4665                }
4666                // Make sure that the resolver is displayable in car mode
4667                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4668                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4669                return ri;
4670            }
4671        }
4672        return null;
4673    }
4674
4675    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4676            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4677        final int N = query.size();
4678        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4679                .get(userId);
4680        // Get the list of persistent preferred activities that handle the intent
4681        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4682        List<PersistentPreferredActivity> pprefs = ppir != null
4683                ? ppir.queryIntent(intent, resolvedType,
4684                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4685                : null;
4686        if (pprefs != null && pprefs.size() > 0) {
4687            final int M = pprefs.size();
4688            for (int i=0; i<M; i++) {
4689                final PersistentPreferredActivity ppa = pprefs.get(i);
4690                if (DEBUG_PREFERRED || debug) {
4691                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4692                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4693                            + "\n  component=" + ppa.mComponent);
4694                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4695                }
4696                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4697                        flags | MATCH_DISABLED_COMPONENTS, userId);
4698                if (DEBUG_PREFERRED || debug) {
4699                    Slog.v(TAG, "Found persistent preferred activity:");
4700                    if (ai != null) {
4701                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4702                    } else {
4703                        Slog.v(TAG, "  null");
4704                    }
4705                }
4706                if (ai == null) {
4707                    // This previously registered persistent preferred activity
4708                    // component is no longer known. Ignore it and do NOT remove it.
4709                    continue;
4710                }
4711                for (int j=0; j<N; j++) {
4712                    final ResolveInfo ri = query.get(j);
4713                    if (!ri.activityInfo.applicationInfo.packageName
4714                            .equals(ai.applicationInfo.packageName)) {
4715                        continue;
4716                    }
4717                    if (!ri.activityInfo.name.equals(ai.name)) {
4718                        continue;
4719                    }
4720                    //  Found a persistent preference that can handle the intent.
4721                    if (DEBUG_PREFERRED || debug) {
4722                        Slog.v(TAG, "Returning persistent preferred activity: " +
4723                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4724                    }
4725                    return ri;
4726                }
4727            }
4728        }
4729        return null;
4730    }
4731
4732    // TODO: handle preferred activities missing while user has amnesia
4733    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4734            List<ResolveInfo> query, int priority, boolean always,
4735            boolean removeMatches, boolean debug, int userId) {
4736        if (!sUserManager.exists(userId)) return null;
4737        flags = updateFlagsForResolve(flags, userId, intent);
4738        // writer
4739        synchronized (mPackages) {
4740            if (intent.getSelector() != null) {
4741                intent = intent.getSelector();
4742            }
4743            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4744
4745            // Try to find a matching persistent preferred activity.
4746            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4747                    debug, userId);
4748
4749            // If a persistent preferred activity matched, use it.
4750            if (pri != null) {
4751                return pri;
4752            }
4753
4754            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4755            // Get the list of preferred activities that handle the intent
4756            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4757            List<PreferredActivity> prefs = pir != null
4758                    ? pir.queryIntent(intent, resolvedType,
4759                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4760                    : null;
4761            if (prefs != null && prefs.size() > 0) {
4762                boolean changed = false;
4763                try {
4764                    // First figure out how good the original match set is.
4765                    // We will only allow preferred activities that came
4766                    // from the same match quality.
4767                    int match = 0;
4768
4769                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4770
4771                    final int N = query.size();
4772                    for (int j=0; j<N; j++) {
4773                        final ResolveInfo ri = query.get(j);
4774                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4775                                + ": 0x" + Integer.toHexString(match));
4776                        if (ri.match > match) {
4777                            match = ri.match;
4778                        }
4779                    }
4780
4781                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4782                            + Integer.toHexString(match));
4783
4784                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4785                    final int M = prefs.size();
4786                    for (int i=0; i<M; i++) {
4787                        final PreferredActivity pa = prefs.get(i);
4788                        if (DEBUG_PREFERRED || debug) {
4789                            Slog.v(TAG, "Checking PreferredActivity ds="
4790                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4791                                    + "\n  component=" + pa.mPref.mComponent);
4792                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4793                        }
4794                        if (pa.mPref.mMatch != match) {
4795                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4796                                    + Integer.toHexString(pa.mPref.mMatch));
4797                            continue;
4798                        }
4799                        // If it's not an "always" type preferred activity and that's what we're
4800                        // looking for, skip it.
4801                        if (always && !pa.mPref.mAlways) {
4802                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4803                            continue;
4804                        }
4805                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4806                                flags | MATCH_DISABLED_COMPONENTS, userId);
4807                        if (DEBUG_PREFERRED || debug) {
4808                            Slog.v(TAG, "Found preferred activity:");
4809                            if (ai != null) {
4810                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4811                            } else {
4812                                Slog.v(TAG, "  null");
4813                            }
4814                        }
4815                        if (ai == null) {
4816                            // This previously registered preferred activity
4817                            // component is no longer known.  Most likely an update
4818                            // to the app was installed and in the new version this
4819                            // component no longer exists.  Clean it up by removing
4820                            // it from the preferred activities list, and skip it.
4821                            Slog.w(TAG, "Removing dangling preferred activity: "
4822                                    + pa.mPref.mComponent);
4823                            pir.removeFilter(pa);
4824                            changed = true;
4825                            continue;
4826                        }
4827                        for (int j=0; j<N; j++) {
4828                            final ResolveInfo ri = query.get(j);
4829                            if (!ri.activityInfo.applicationInfo.packageName
4830                                    .equals(ai.applicationInfo.packageName)) {
4831                                continue;
4832                            }
4833                            if (!ri.activityInfo.name.equals(ai.name)) {
4834                                continue;
4835                            }
4836
4837                            if (removeMatches) {
4838                                pir.removeFilter(pa);
4839                                changed = true;
4840                                if (DEBUG_PREFERRED) {
4841                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4842                                }
4843                                break;
4844                            }
4845
4846                            // Okay we found a previously set preferred or last chosen app.
4847                            // If the result set is different from when this
4848                            // was created, we need to clear it and re-ask the
4849                            // user their preference, if we're looking for an "always" type entry.
4850                            if (always && !pa.mPref.sameSet(query)) {
4851                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4852                                        + intent + " type " + resolvedType);
4853                                if (DEBUG_PREFERRED) {
4854                                    Slog.v(TAG, "Removing preferred activity since set changed "
4855                                            + pa.mPref.mComponent);
4856                                }
4857                                pir.removeFilter(pa);
4858                                // Re-add the filter as a "last chosen" entry (!always)
4859                                PreferredActivity lastChosen = new PreferredActivity(
4860                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4861                                pir.addFilter(lastChosen);
4862                                changed = true;
4863                                return null;
4864                            }
4865
4866                            // Yay! Either the set matched or we're looking for the last chosen
4867                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4868                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4869                            return ri;
4870                        }
4871                    }
4872                } finally {
4873                    if (changed) {
4874                        if (DEBUG_PREFERRED) {
4875                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4876                        }
4877                        scheduleWritePackageRestrictionsLocked(userId);
4878                    }
4879                }
4880            }
4881        }
4882        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4883        return null;
4884    }
4885
4886    /*
4887     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4888     */
4889    @Override
4890    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4891            int targetUserId) {
4892        mContext.enforceCallingOrSelfPermission(
4893                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4894        List<CrossProfileIntentFilter> matches =
4895                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4896        if (matches != null) {
4897            int size = matches.size();
4898            for (int i = 0; i < size; i++) {
4899                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4900            }
4901        }
4902        if (hasWebURI(intent)) {
4903            // cross-profile app linking works only towards the parent.
4904            final UserInfo parent = getProfileParent(sourceUserId);
4905            synchronized(mPackages) {
4906                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4907                        intent, resolvedType, 0, sourceUserId, parent.id);
4908                return xpDomainInfo != null;
4909            }
4910        }
4911        return false;
4912    }
4913
4914    private UserInfo getProfileParent(int userId) {
4915        final long identity = Binder.clearCallingIdentity();
4916        try {
4917            return sUserManager.getProfileParent(userId);
4918        } finally {
4919            Binder.restoreCallingIdentity(identity);
4920        }
4921    }
4922
4923    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4924            String resolvedType, int userId) {
4925        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4926        if (resolver != null) {
4927            return resolver.queryIntent(intent, resolvedType, false, userId);
4928        }
4929        return null;
4930    }
4931
4932    @Override
4933    public List<ResolveInfo> queryIntentActivities(Intent intent,
4934            String resolvedType, int flags, int userId) {
4935        if (!sUserManager.exists(userId)) return Collections.emptyList();
4936        flags = updateFlagsForResolve(flags, userId, intent);
4937        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4938        ComponentName comp = intent.getComponent();
4939        if (comp == null) {
4940            if (intent.getSelector() != null) {
4941                intent = intent.getSelector();
4942                comp = intent.getComponent();
4943            }
4944        }
4945
4946        if (comp != null) {
4947            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4948            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4949            if (ai != null) {
4950                final ResolveInfo ri = new ResolveInfo();
4951                ri.activityInfo = ai;
4952                list.add(ri);
4953            }
4954            return list;
4955        }
4956
4957        // reader
4958        synchronized (mPackages) {
4959            final String pkgName = intent.getPackage();
4960            if (pkgName == null) {
4961                List<CrossProfileIntentFilter> matchingFilters =
4962                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4963                // Check for results that need to skip the current profile.
4964                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4965                        resolvedType, flags, userId);
4966                if (xpResolveInfo != null) {
4967                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4968                    result.add(xpResolveInfo);
4969                    return filterIfNotSystemUser(result, userId);
4970                }
4971
4972                // Check for results in the current profile.
4973                List<ResolveInfo> result = mActivities.queryIntent(
4974                        intent, resolvedType, flags, userId);
4975                result = filterIfNotSystemUser(result, userId);
4976
4977                // Check for cross profile results.
4978                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4979                xpResolveInfo = queryCrossProfileIntents(
4980                        matchingFilters, intent, resolvedType, flags, userId,
4981                        hasNonNegativePriorityResult);
4982                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4983                    boolean isVisibleToUser = filterIfNotSystemUser(
4984                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4985                    if (isVisibleToUser) {
4986                        result.add(xpResolveInfo);
4987                        Collections.sort(result, mResolvePrioritySorter);
4988                    }
4989                }
4990                if (hasWebURI(intent)) {
4991                    CrossProfileDomainInfo xpDomainInfo = null;
4992                    final UserInfo parent = getProfileParent(userId);
4993                    if (parent != null) {
4994                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4995                                flags, userId, parent.id);
4996                    }
4997                    if (xpDomainInfo != null) {
4998                        if (xpResolveInfo != null) {
4999                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5000                            // in the result.
5001                            result.remove(xpResolveInfo);
5002                        }
5003                        if (result.size() == 0) {
5004                            result.add(xpDomainInfo.resolveInfo);
5005                            return result;
5006                        }
5007                    } else if (result.size() <= 1) {
5008                        return result;
5009                    }
5010                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5011                            xpDomainInfo, userId);
5012                    Collections.sort(result, mResolvePrioritySorter);
5013                }
5014                return result;
5015            }
5016            final PackageParser.Package pkg = mPackages.get(pkgName);
5017            if (pkg != null) {
5018                return filterIfNotSystemUser(
5019                        mActivities.queryIntentForPackage(
5020                                intent, resolvedType, flags, pkg.activities, userId),
5021                        userId);
5022            }
5023            return new ArrayList<ResolveInfo>();
5024        }
5025    }
5026
5027    private static class CrossProfileDomainInfo {
5028        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5029        ResolveInfo resolveInfo;
5030        /* Best domain verification status of the activities found in the other profile */
5031        int bestDomainVerificationStatus;
5032    }
5033
5034    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5035            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5036        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5037                sourceUserId)) {
5038            return null;
5039        }
5040        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5041                resolvedType, flags, parentUserId);
5042
5043        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5044            return null;
5045        }
5046        CrossProfileDomainInfo result = null;
5047        int size = resultTargetUser.size();
5048        for (int i = 0; i < size; i++) {
5049            ResolveInfo riTargetUser = resultTargetUser.get(i);
5050            // Intent filter verification is only for filters that specify a host. So don't return
5051            // those that handle all web uris.
5052            if (riTargetUser.handleAllWebDataURI) {
5053                continue;
5054            }
5055            String packageName = riTargetUser.activityInfo.packageName;
5056            PackageSetting ps = mSettings.mPackages.get(packageName);
5057            if (ps == null) {
5058                continue;
5059            }
5060            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5061            int status = (int)(verificationState >> 32);
5062            if (result == null) {
5063                result = new CrossProfileDomainInfo();
5064                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5065                        sourceUserId, parentUserId);
5066                result.bestDomainVerificationStatus = status;
5067            } else {
5068                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5069                        result.bestDomainVerificationStatus);
5070            }
5071        }
5072        // Don't consider matches with status NEVER across profiles.
5073        if (result != null && result.bestDomainVerificationStatus
5074                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5075            return null;
5076        }
5077        return result;
5078    }
5079
5080    /**
5081     * Verification statuses are ordered from the worse to the best, except for
5082     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5083     */
5084    private int bestDomainVerificationStatus(int status1, int status2) {
5085        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5086            return status2;
5087        }
5088        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5089            return status1;
5090        }
5091        return (int) MathUtils.max(status1, status2);
5092    }
5093
5094    private boolean isUserEnabled(int userId) {
5095        long callingId = Binder.clearCallingIdentity();
5096        try {
5097            UserInfo userInfo = sUserManager.getUserInfo(userId);
5098            return userInfo != null && userInfo.isEnabled();
5099        } finally {
5100            Binder.restoreCallingIdentity(callingId);
5101        }
5102    }
5103
5104    /**
5105     * Filter out activities with systemUserOnly flag set, when current user is not System.
5106     *
5107     * @return filtered list
5108     */
5109    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5110        if (userId == UserHandle.USER_SYSTEM) {
5111            return resolveInfos;
5112        }
5113        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5114            ResolveInfo info = resolveInfos.get(i);
5115            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5116                resolveInfos.remove(i);
5117            }
5118        }
5119        return resolveInfos;
5120    }
5121
5122    /**
5123     * @param resolveInfos list of resolve infos in descending priority order
5124     * @return if the list contains a resolve info with non-negative priority
5125     */
5126    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5127        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5128    }
5129
5130    private static boolean hasWebURI(Intent intent) {
5131        if (intent.getData() == null) {
5132            return false;
5133        }
5134        final String scheme = intent.getScheme();
5135        if (TextUtils.isEmpty(scheme)) {
5136            return false;
5137        }
5138        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5139    }
5140
5141    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5142            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5143            int userId) {
5144        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5145
5146        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5147            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5148                    candidates.size());
5149        }
5150
5151        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5152        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5153        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5154        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5155        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5156        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5157
5158        synchronized (mPackages) {
5159            final int count = candidates.size();
5160            // First, try to use linked apps. Partition the candidates into four lists:
5161            // one for the final results, one for the "do not use ever", one for "undefined status"
5162            // and finally one for "browser app type".
5163            for (int n=0; n<count; n++) {
5164                ResolveInfo info = candidates.get(n);
5165                String packageName = info.activityInfo.packageName;
5166                PackageSetting ps = mSettings.mPackages.get(packageName);
5167                if (ps != null) {
5168                    // Add to the special match all list (Browser use case)
5169                    if (info.handleAllWebDataURI) {
5170                        matchAllList.add(info);
5171                        continue;
5172                    }
5173                    // Try to get the status from User settings first
5174                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5175                    int status = (int)(packedStatus >> 32);
5176                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5177                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5178                        if (DEBUG_DOMAIN_VERIFICATION) {
5179                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5180                                    + " : linkgen=" + linkGeneration);
5181                        }
5182                        // Use link-enabled generation as preferredOrder, i.e.
5183                        // prefer newly-enabled over earlier-enabled.
5184                        info.preferredOrder = linkGeneration;
5185                        alwaysList.add(info);
5186                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5187                        if (DEBUG_DOMAIN_VERIFICATION) {
5188                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5189                        }
5190                        neverList.add(info);
5191                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5192                        if (DEBUG_DOMAIN_VERIFICATION) {
5193                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5194                        }
5195                        alwaysAskList.add(info);
5196                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5197                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5198                        if (DEBUG_DOMAIN_VERIFICATION) {
5199                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5200                        }
5201                        undefinedList.add(info);
5202                    }
5203                }
5204            }
5205
5206            // We'll want to include browser possibilities in a few cases
5207            boolean includeBrowser = false;
5208
5209            // First try to add the "always" resolution(s) for the current user, if any
5210            if (alwaysList.size() > 0) {
5211                result.addAll(alwaysList);
5212            } else {
5213                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5214                result.addAll(undefinedList);
5215                // Maybe add one for the other profile.
5216                if (xpDomainInfo != null && (
5217                        xpDomainInfo.bestDomainVerificationStatus
5218                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5219                    result.add(xpDomainInfo.resolveInfo);
5220                }
5221                includeBrowser = true;
5222            }
5223
5224            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5225            // If there were 'always' entries their preferred order has been set, so we also
5226            // back that off to make the alternatives equivalent
5227            if (alwaysAskList.size() > 0) {
5228                for (ResolveInfo i : result) {
5229                    i.preferredOrder = 0;
5230                }
5231                result.addAll(alwaysAskList);
5232                includeBrowser = true;
5233            }
5234
5235            if (includeBrowser) {
5236                // Also add browsers (all of them or only the default one)
5237                if (DEBUG_DOMAIN_VERIFICATION) {
5238                    Slog.v(TAG, "   ...including browsers in candidate set");
5239                }
5240                if ((matchFlags & MATCH_ALL) != 0) {
5241                    result.addAll(matchAllList);
5242                } else {
5243                    // Browser/generic handling case.  If there's a default browser, go straight
5244                    // to that (but only if there is no other higher-priority match).
5245                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5246                    int maxMatchPrio = 0;
5247                    ResolveInfo defaultBrowserMatch = null;
5248                    final int numCandidates = matchAllList.size();
5249                    for (int n = 0; n < numCandidates; n++) {
5250                        ResolveInfo info = matchAllList.get(n);
5251                        // track the highest overall match priority...
5252                        if (info.priority > maxMatchPrio) {
5253                            maxMatchPrio = info.priority;
5254                        }
5255                        // ...and the highest-priority default browser match
5256                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5257                            if (defaultBrowserMatch == null
5258                                    || (defaultBrowserMatch.priority < info.priority)) {
5259                                if (debug) {
5260                                    Slog.v(TAG, "Considering default browser match " + info);
5261                                }
5262                                defaultBrowserMatch = info;
5263                            }
5264                        }
5265                    }
5266                    if (defaultBrowserMatch != null
5267                            && defaultBrowserMatch.priority >= maxMatchPrio
5268                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5269                    {
5270                        if (debug) {
5271                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5272                        }
5273                        result.add(defaultBrowserMatch);
5274                    } else {
5275                        result.addAll(matchAllList);
5276                    }
5277                }
5278
5279                // If there is nothing selected, add all candidates and remove the ones that the user
5280                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5281                if (result.size() == 0) {
5282                    result.addAll(candidates);
5283                    result.removeAll(neverList);
5284                }
5285            }
5286        }
5287        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5288            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5289                    result.size());
5290            for (ResolveInfo info : result) {
5291                Slog.v(TAG, "  + " + info.activityInfo);
5292            }
5293        }
5294        return result;
5295    }
5296
5297    // Returns a packed value as a long:
5298    //
5299    // high 'int'-sized word: link status: undefined/ask/never/always.
5300    // low 'int'-sized word: relative priority among 'always' results.
5301    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5302        long result = ps.getDomainVerificationStatusForUser(userId);
5303        // if none available, get the master status
5304        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5305            if (ps.getIntentFilterVerificationInfo() != null) {
5306                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5307            }
5308        }
5309        return result;
5310    }
5311
5312    private ResolveInfo querySkipCurrentProfileIntents(
5313            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5314            int flags, int sourceUserId) {
5315        if (matchingFilters != null) {
5316            int size = matchingFilters.size();
5317            for (int i = 0; i < size; i ++) {
5318                CrossProfileIntentFilter filter = matchingFilters.get(i);
5319                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5320                    // Checking if there are activities in the target user that can handle the
5321                    // intent.
5322                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5323                            resolvedType, flags, sourceUserId);
5324                    if (resolveInfo != null) {
5325                        return resolveInfo;
5326                    }
5327                }
5328            }
5329        }
5330        return null;
5331    }
5332
5333    // Return matching ResolveInfo in target user if any.
5334    private ResolveInfo queryCrossProfileIntents(
5335            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5336            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5337        if (matchingFilters != null) {
5338            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5339            // match the same intent. For performance reasons, it is better not to
5340            // run queryIntent twice for the same userId
5341            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5342            int size = matchingFilters.size();
5343            for (int i = 0; i < size; i++) {
5344                CrossProfileIntentFilter filter = matchingFilters.get(i);
5345                int targetUserId = filter.getTargetUserId();
5346                boolean skipCurrentProfile =
5347                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5348                boolean skipCurrentProfileIfNoMatchFound =
5349                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5350                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5351                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5352                    // Checking if there are activities in the target user that can handle the
5353                    // intent.
5354                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5355                            resolvedType, flags, sourceUserId);
5356                    if (resolveInfo != null) return resolveInfo;
5357                    alreadyTriedUserIds.put(targetUserId, true);
5358                }
5359            }
5360        }
5361        return null;
5362    }
5363
5364    /**
5365     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5366     * will forward the intent to the filter's target user.
5367     * Otherwise, returns null.
5368     */
5369    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5370            String resolvedType, int flags, int sourceUserId) {
5371        int targetUserId = filter.getTargetUserId();
5372        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5373                resolvedType, flags, targetUserId);
5374        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5375                && isUserEnabled(targetUserId)) {
5376            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5377        }
5378        return null;
5379    }
5380
5381    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5382            int sourceUserId, int targetUserId) {
5383        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5384        long ident = Binder.clearCallingIdentity();
5385        boolean targetIsProfile;
5386        try {
5387            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5388        } finally {
5389            Binder.restoreCallingIdentity(ident);
5390        }
5391        String className;
5392        if (targetIsProfile) {
5393            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5394        } else {
5395            className = FORWARD_INTENT_TO_PARENT;
5396        }
5397        ComponentName forwardingActivityComponentName = new ComponentName(
5398                mAndroidApplication.packageName, className);
5399        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5400                sourceUserId);
5401        if (!targetIsProfile) {
5402            forwardingActivityInfo.showUserIcon = targetUserId;
5403            forwardingResolveInfo.noResourceId = true;
5404        }
5405        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5406        forwardingResolveInfo.priority = 0;
5407        forwardingResolveInfo.preferredOrder = 0;
5408        forwardingResolveInfo.match = 0;
5409        forwardingResolveInfo.isDefault = true;
5410        forwardingResolveInfo.filter = filter;
5411        forwardingResolveInfo.targetUserId = targetUserId;
5412        return forwardingResolveInfo;
5413    }
5414
5415    @Override
5416    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5417            Intent[] specifics, String[] specificTypes, Intent intent,
5418            String resolvedType, int flags, int userId) {
5419        if (!sUserManager.exists(userId)) return Collections.emptyList();
5420        flags = updateFlagsForResolve(flags, userId, intent);
5421        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5422                false, "query intent activity options");
5423        final String resultsAction = intent.getAction();
5424
5425        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5426                | PackageManager.GET_RESOLVED_FILTER, userId);
5427
5428        if (DEBUG_INTENT_MATCHING) {
5429            Log.v(TAG, "Query " + intent + ": " + results);
5430        }
5431
5432        int specificsPos = 0;
5433        int N;
5434
5435        // todo: note that the algorithm used here is O(N^2).  This
5436        // isn't a problem in our current environment, but if we start running
5437        // into situations where we have more than 5 or 10 matches then this
5438        // should probably be changed to something smarter...
5439
5440        // First we go through and resolve each of the specific items
5441        // that were supplied, taking care of removing any corresponding
5442        // duplicate items in the generic resolve list.
5443        if (specifics != null) {
5444            for (int i=0; i<specifics.length; i++) {
5445                final Intent sintent = specifics[i];
5446                if (sintent == null) {
5447                    continue;
5448                }
5449
5450                if (DEBUG_INTENT_MATCHING) {
5451                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5452                }
5453
5454                String action = sintent.getAction();
5455                if (resultsAction != null && resultsAction.equals(action)) {
5456                    // If this action was explicitly requested, then don't
5457                    // remove things that have it.
5458                    action = null;
5459                }
5460
5461                ResolveInfo ri = null;
5462                ActivityInfo ai = null;
5463
5464                ComponentName comp = sintent.getComponent();
5465                if (comp == null) {
5466                    ri = resolveIntent(
5467                        sintent,
5468                        specificTypes != null ? specificTypes[i] : null,
5469                            flags, userId);
5470                    if (ri == null) {
5471                        continue;
5472                    }
5473                    if (ri == mResolveInfo) {
5474                        // ACK!  Must do something better with this.
5475                    }
5476                    ai = ri.activityInfo;
5477                    comp = new ComponentName(ai.applicationInfo.packageName,
5478                            ai.name);
5479                } else {
5480                    ai = getActivityInfo(comp, flags, userId);
5481                    if (ai == null) {
5482                        continue;
5483                    }
5484                }
5485
5486                // Look for any generic query activities that are duplicates
5487                // of this specific one, and remove them from the results.
5488                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5489                N = results.size();
5490                int j;
5491                for (j=specificsPos; j<N; j++) {
5492                    ResolveInfo sri = results.get(j);
5493                    if ((sri.activityInfo.name.equals(comp.getClassName())
5494                            && sri.activityInfo.applicationInfo.packageName.equals(
5495                                    comp.getPackageName()))
5496                        || (action != null && sri.filter.matchAction(action))) {
5497                        results.remove(j);
5498                        if (DEBUG_INTENT_MATCHING) Log.v(
5499                            TAG, "Removing duplicate item from " + j
5500                            + " due to specific " + specificsPos);
5501                        if (ri == null) {
5502                            ri = sri;
5503                        }
5504                        j--;
5505                        N--;
5506                    }
5507                }
5508
5509                // Add this specific item to its proper place.
5510                if (ri == null) {
5511                    ri = new ResolveInfo();
5512                    ri.activityInfo = ai;
5513                }
5514                results.add(specificsPos, ri);
5515                ri.specificIndex = i;
5516                specificsPos++;
5517            }
5518        }
5519
5520        // Now we go through the remaining generic results and remove any
5521        // duplicate actions that are found here.
5522        N = results.size();
5523        for (int i=specificsPos; i<N-1; i++) {
5524            final ResolveInfo rii = results.get(i);
5525            if (rii.filter == null) {
5526                continue;
5527            }
5528
5529            // Iterate over all of the actions of this result's intent
5530            // filter...  typically this should be just one.
5531            final Iterator<String> it = rii.filter.actionsIterator();
5532            if (it == null) {
5533                continue;
5534            }
5535            while (it.hasNext()) {
5536                final String action = it.next();
5537                if (resultsAction != null && resultsAction.equals(action)) {
5538                    // If this action was explicitly requested, then don't
5539                    // remove things that have it.
5540                    continue;
5541                }
5542                for (int j=i+1; j<N; j++) {
5543                    final ResolveInfo rij = results.get(j);
5544                    if (rij.filter != null && rij.filter.hasAction(action)) {
5545                        results.remove(j);
5546                        if (DEBUG_INTENT_MATCHING) Log.v(
5547                            TAG, "Removing duplicate item from " + j
5548                            + " due to action " + action + " at " + i);
5549                        j--;
5550                        N--;
5551                    }
5552                }
5553            }
5554
5555            // If the caller didn't request filter information, drop it now
5556            // so we don't have to marshall/unmarshall it.
5557            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5558                rii.filter = null;
5559            }
5560        }
5561
5562        // Filter out the caller activity if so requested.
5563        if (caller != null) {
5564            N = results.size();
5565            for (int i=0; i<N; i++) {
5566                ActivityInfo ainfo = results.get(i).activityInfo;
5567                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5568                        && caller.getClassName().equals(ainfo.name)) {
5569                    results.remove(i);
5570                    break;
5571                }
5572            }
5573        }
5574
5575        // If the caller didn't request filter information,
5576        // drop them now so we don't have to
5577        // marshall/unmarshall it.
5578        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5579            N = results.size();
5580            for (int i=0; i<N; i++) {
5581                results.get(i).filter = null;
5582            }
5583        }
5584
5585        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5586        return results;
5587    }
5588
5589    @Override
5590    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5591            int userId) {
5592        if (!sUserManager.exists(userId)) return Collections.emptyList();
5593        flags = updateFlagsForResolve(flags, userId, intent);
5594        ComponentName comp = intent.getComponent();
5595        if (comp == null) {
5596            if (intent.getSelector() != null) {
5597                intent = intent.getSelector();
5598                comp = intent.getComponent();
5599            }
5600        }
5601        if (comp != null) {
5602            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5603            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5604            if (ai != null) {
5605                ResolveInfo ri = new ResolveInfo();
5606                ri.activityInfo = ai;
5607                list.add(ri);
5608            }
5609            return list;
5610        }
5611
5612        // reader
5613        synchronized (mPackages) {
5614            String pkgName = intent.getPackage();
5615            if (pkgName == null) {
5616                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5617            }
5618            final PackageParser.Package pkg = mPackages.get(pkgName);
5619            if (pkg != null) {
5620                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5621                        userId);
5622            }
5623            return null;
5624        }
5625    }
5626
5627    @Override
5628    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5629        if (!sUserManager.exists(userId)) return null;
5630        flags = updateFlagsForResolve(flags, userId, intent);
5631        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5632        if (query != null) {
5633            if (query.size() >= 1) {
5634                // If there is more than one service with the same priority,
5635                // just arbitrarily pick the first one.
5636                return query.get(0);
5637            }
5638        }
5639        return null;
5640    }
5641
5642    @Override
5643    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5644            int userId) {
5645        if (!sUserManager.exists(userId)) return Collections.emptyList();
5646        flags = updateFlagsForResolve(flags, userId, intent);
5647        ComponentName comp = intent.getComponent();
5648        if (comp == null) {
5649            if (intent.getSelector() != null) {
5650                intent = intent.getSelector();
5651                comp = intent.getComponent();
5652            }
5653        }
5654        if (comp != null) {
5655            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5656            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5657            if (si != null) {
5658                final ResolveInfo ri = new ResolveInfo();
5659                ri.serviceInfo = si;
5660                list.add(ri);
5661            }
5662            return list;
5663        }
5664
5665        // reader
5666        synchronized (mPackages) {
5667            String pkgName = intent.getPackage();
5668            if (pkgName == null) {
5669                return mServices.queryIntent(intent, resolvedType, flags, userId);
5670            }
5671            final PackageParser.Package pkg = mPackages.get(pkgName);
5672            if (pkg != null) {
5673                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5674                        userId);
5675            }
5676            return null;
5677        }
5678    }
5679
5680    @Override
5681    public List<ResolveInfo> queryIntentContentProviders(
5682            Intent intent, String resolvedType, int flags, int userId) {
5683        if (!sUserManager.exists(userId)) return Collections.emptyList();
5684        flags = updateFlagsForResolve(flags, userId, intent);
5685        ComponentName comp = intent.getComponent();
5686        if (comp == null) {
5687            if (intent.getSelector() != null) {
5688                intent = intent.getSelector();
5689                comp = intent.getComponent();
5690            }
5691        }
5692        if (comp != null) {
5693            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5694            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5695            if (pi != null) {
5696                final ResolveInfo ri = new ResolveInfo();
5697                ri.providerInfo = pi;
5698                list.add(ri);
5699            }
5700            return list;
5701        }
5702
5703        // reader
5704        synchronized (mPackages) {
5705            String pkgName = intent.getPackage();
5706            if (pkgName == null) {
5707                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5708            }
5709            final PackageParser.Package pkg = mPackages.get(pkgName);
5710            if (pkg != null) {
5711                return mProviders.queryIntentForPackage(
5712                        intent, resolvedType, flags, pkg.providers, userId);
5713            }
5714            return null;
5715        }
5716    }
5717
5718    @Override
5719    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5720        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5721        flags = updateFlagsForPackage(flags, userId, null);
5722        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5724
5725        // writer
5726        synchronized (mPackages) {
5727            ArrayList<PackageInfo> list;
5728            if (listUninstalled) {
5729                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5730                for (PackageSetting ps : mSettings.mPackages.values()) {
5731                    PackageInfo pi;
5732                    if (ps.pkg != null) {
5733                        pi = generatePackageInfo(ps.pkg, flags, userId);
5734                    } else {
5735                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5736                    }
5737                    if (pi != null) {
5738                        list.add(pi);
5739                    }
5740                }
5741            } else {
5742                list = new ArrayList<PackageInfo>(mPackages.size());
5743                for (PackageParser.Package p : mPackages.values()) {
5744                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5745                    if (pi != null) {
5746                        list.add(pi);
5747                    }
5748                }
5749            }
5750
5751            return new ParceledListSlice<PackageInfo>(list);
5752        }
5753    }
5754
5755    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5756            String[] permissions, boolean[] tmp, int flags, int userId) {
5757        int numMatch = 0;
5758        final PermissionsState permissionsState = ps.getPermissionsState();
5759        for (int i=0; i<permissions.length; i++) {
5760            final String permission = permissions[i];
5761            if (permissionsState.hasPermission(permission, userId)) {
5762                tmp[i] = true;
5763                numMatch++;
5764            } else {
5765                tmp[i] = false;
5766            }
5767        }
5768        if (numMatch == 0) {
5769            return;
5770        }
5771        PackageInfo pi;
5772        if (ps.pkg != null) {
5773            pi = generatePackageInfo(ps.pkg, flags, userId);
5774        } else {
5775            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5776        }
5777        // The above might return null in cases of uninstalled apps or install-state
5778        // skew across users/profiles.
5779        if (pi != null) {
5780            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5781                if (numMatch == permissions.length) {
5782                    pi.requestedPermissions = permissions;
5783                } else {
5784                    pi.requestedPermissions = new String[numMatch];
5785                    numMatch = 0;
5786                    for (int i=0; i<permissions.length; i++) {
5787                        if (tmp[i]) {
5788                            pi.requestedPermissions[numMatch] = permissions[i];
5789                            numMatch++;
5790                        }
5791                    }
5792                }
5793            }
5794            list.add(pi);
5795        }
5796    }
5797
5798    @Override
5799    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5800            String[] permissions, int flags, int userId) {
5801        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5802        flags = updateFlagsForPackage(flags, userId, permissions);
5803        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5804
5805        // writer
5806        synchronized (mPackages) {
5807            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5808            boolean[] tmpBools = new boolean[permissions.length];
5809            if (listUninstalled) {
5810                for (PackageSetting ps : mSettings.mPackages.values()) {
5811                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5812                }
5813            } else {
5814                for (PackageParser.Package pkg : mPackages.values()) {
5815                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5816                    if (ps != null) {
5817                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5818                                userId);
5819                    }
5820                }
5821            }
5822
5823            return new ParceledListSlice<PackageInfo>(list);
5824        }
5825    }
5826
5827    @Override
5828    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5829        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5830        flags = updateFlagsForApplication(flags, userId, null);
5831        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5832
5833        // writer
5834        synchronized (mPackages) {
5835            ArrayList<ApplicationInfo> list;
5836            if (listUninstalled) {
5837                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5838                for (PackageSetting ps : mSettings.mPackages.values()) {
5839                    ApplicationInfo ai;
5840                    if (ps.pkg != null) {
5841                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5842                                ps.readUserState(userId), userId);
5843                    } else {
5844                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5845                    }
5846                    if (ai != null) {
5847                        list.add(ai);
5848                    }
5849                }
5850            } else {
5851                list = new ArrayList<ApplicationInfo>(mPackages.size());
5852                for (PackageParser.Package p : mPackages.values()) {
5853                    if (p.mExtras != null) {
5854                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5855                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5856                        if (ai != null) {
5857                            list.add(ai);
5858                        }
5859                    }
5860                }
5861            }
5862
5863            return new ParceledListSlice<ApplicationInfo>(list);
5864        }
5865    }
5866
5867    @Override
5868    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5869        if (DISABLE_EPHEMERAL_APPS) {
5870            return null;
5871        }
5872
5873        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5874                "getEphemeralApplications");
5875        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5876                "getEphemeralApplications");
5877        synchronized (mPackages) {
5878            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5879                    .getEphemeralApplicationsLPw(userId);
5880            if (ephemeralApps != null) {
5881                return new ParceledListSlice<>(ephemeralApps);
5882            }
5883        }
5884        return null;
5885    }
5886
5887    @Override
5888    public boolean isEphemeralApplication(String packageName, int userId) {
5889        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5890                "isEphemeral");
5891        if (DISABLE_EPHEMERAL_APPS) {
5892            return false;
5893        }
5894
5895        if (!isCallerSameApp(packageName)) {
5896            return false;
5897        }
5898        synchronized (mPackages) {
5899            PackageParser.Package pkg = mPackages.get(packageName);
5900            if (pkg != null) {
5901                return pkg.applicationInfo.isEphemeralApp();
5902            }
5903        }
5904        return false;
5905    }
5906
5907    @Override
5908    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5909        if (DISABLE_EPHEMERAL_APPS) {
5910            return null;
5911        }
5912
5913        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5914                "getCookie");
5915        if (!isCallerSameApp(packageName)) {
5916            return null;
5917        }
5918        synchronized (mPackages) {
5919            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5920                    packageName, userId);
5921        }
5922    }
5923
5924    @Override
5925    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5926        if (DISABLE_EPHEMERAL_APPS) {
5927            return true;
5928        }
5929
5930        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5931                "setCookie");
5932        if (!isCallerSameApp(packageName)) {
5933            return false;
5934        }
5935        synchronized (mPackages) {
5936            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5937                    packageName, cookie, userId);
5938        }
5939    }
5940
5941    @Override
5942    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5943        if (DISABLE_EPHEMERAL_APPS) {
5944            return null;
5945        }
5946
5947        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5948                "getEphemeralApplicationIcon");
5949        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5950                "getEphemeralApplicationIcon");
5951        synchronized (mPackages) {
5952            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5953                    packageName, userId);
5954        }
5955    }
5956
5957    private boolean isCallerSameApp(String packageName) {
5958        PackageParser.Package pkg = mPackages.get(packageName);
5959        return pkg != null
5960                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5961    }
5962
5963    public List<ApplicationInfo> getPersistentApplications(int flags) {
5964        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5965
5966        // reader
5967        synchronized (mPackages) {
5968            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5969            final int userId = UserHandle.getCallingUserId();
5970            while (i.hasNext()) {
5971                final PackageParser.Package p = i.next();
5972                if (p.applicationInfo != null
5973                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5974                        && (!mSafeMode || isSystemApp(p))) {
5975                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5976                    if (ps != null) {
5977                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5978                                ps.readUserState(userId), userId);
5979                        if (ai != null) {
5980                            finalList.add(ai);
5981                        }
5982                    }
5983                }
5984            }
5985        }
5986
5987        return finalList;
5988    }
5989
5990    @Override
5991    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5992        if (!sUserManager.exists(userId)) return null;
5993        flags = updateFlagsForComponent(flags, userId, name);
5994        // reader
5995        synchronized (mPackages) {
5996            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5997            PackageSetting ps = provider != null
5998                    ? mSettings.mPackages.get(provider.owner.packageName)
5999                    : null;
6000            return ps != null
6001                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6002                    ? PackageParser.generateProviderInfo(provider, flags,
6003                            ps.readUserState(userId), userId)
6004                    : null;
6005        }
6006    }
6007
6008    /**
6009     * @deprecated
6010     */
6011    @Deprecated
6012    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6013        // reader
6014        synchronized (mPackages) {
6015            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6016                    .entrySet().iterator();
6017            final int userId = UserHandle.getCallingUserId();
6018            while (i.hasNext()) {
6019                Map.Entry<String, PackageParser.Provider> entry = i.next();
6020                PackageParser.Provider p = entry.getValue();
6021                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6022
6023                if (ps != null && p.syncable
6024                        && (!mSafeMode || (p.info.applicationInfo.flags
6025                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6026                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6027                            ps.readUserState(userId), userId);
6028                    if (info != null) {
6029                        outNames.add(entry.getKey());
6030                        outInfo.add(info);
6031                    }
6032                }
6033            }
6034        }
6035    }
6036
6037    @Override
6038    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6039            int uid, int flags) {
6040        final int userId = processName != null ? UserHandle.getUserId(uid)
6041                : UserHandle.getCallingUserId();
6042        if (!sUserManager.exists(userId)) return null;
6043        flags = updateFlagsForComponent(flags, userId, processName);
6044
6045        ArrayList<ProviderInfo> finalList = null;
6046        // reader
6047        synchronized (mPackages) {
6048            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6049            while (i.hasNext()) {
6050                final PackageParser.Provider p = i.next();
6051                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6052                if (ps != null && p.info.authority != null
6053                        && (processName == null
6054                                || (p.info.processName.equals(processName)
6055                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6056                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6057                    if (finalList == null) {
6058                        finalList = new ArrayList<ProviderInfo>(3);
6059                    }
6060                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6061                            ps.readUserState(userId), userId);
6062                    if (info != null) {
6063                        finalList.add(info);
6064                    }
6065                }
6066            }
6067        }
6068
6069        if (finalList != null) {
6070            Collections.sort(finalList, mProviderInitOrderSorter);
6071            return new ParceledListSlice<ProviderInfo>(finalList);
6072        }
6073
6074        return null;
6075    }
6076
6077    @Override
6078    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6079        // reader
6080        synchronized (mPackages) {
6081            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6082            return PackageParser.generateInstrumentationInfo(i, flags);
6083        }
6084    }
6085
6086    @Override
6087    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6088            int flags) {
6089        ArrayList<InstrumentationInfo> finalList =
6090            new ArrayList<InstrumentationInfo>();
6091
6092        // reader
6093        synchronized (mPackages) {
6094            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6095            while (i.hasNext()) {
6096                final PackageParser.Instrumentation p = i.next();
6097                if (targetPackage == null
6098                        || targetPackage.equals(p.info.targetPackage)) {
6099                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6100                            flags);
6101                    if (ii != null) {
6102                        finalList.add(ii);
6103                    }
6104                }
6105            }
6106        }
6107
6108        return finalList;
6109    }
6110
6111    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6112        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6113        if (overlays == null) {
6114            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6115            return;
6116        }
6117        for (PackageParser.Package opkg : overlays.values()) {
6118            // Not much to do if idmap fails: we already logged the error
6119            // and we certainly don't want to abort installation of pkg simply
6120            // because an overlay didn't fit properly. For these reasons,
6121            // ignore the return value of createIdmapForPackagePairLI.
6122            createIdmapForPackagePairLI(pkg, opkg);
6123        }
6124    }
6125
6126    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6127            PackageParser.Package opkg) {
6128        if (!opkg.mTrustedOverlay) {
6129            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6130                    opkg.baseCodePath + ": overlay not trusted");
6131            return false;
6132        }
6133        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6134        if (overlaySet == null) {
6135            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6136                    opkg.baseCodePath + " but target package has no known overlays");
6137            return false;
6138        }
6139        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6140        // TODO: generate idmap for split APKs
6141        try {
6142            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6143        } catch (InstallerException e) {
6144            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6145                    + opkg.baseCodePath);
6146            return false;
6147        }
6148        PackageParser.Package[] overlayArray =
6149            overlaySet.values().toArray(new PackageParser.Package[0]);
6150        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6151            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6152                return p1.mOverlayPriority - p2.mOverlayPriority;
6153            }
6154        };
6155        Arrays.sort(overlayArray, cmp);
6156
6157        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6158        int i = 0;
6159        for (PackageParser.Package p : overlayArray) {
6160            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6161        }
6162        return true;
6163    }
6164
6165    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6167        try {
6168            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6169        } finally {
6170            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6171        }
6172    }
6173
6174    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6175        final File[] files = dir.listFiles();
6176        if (ArrayUtils.isEmpty(files)) {
6177            Log.d(TAG, "No files in app dir " + dir);
6178            return;
6179        }
6180
6181        if (DEBUG_PACKAGE_SCANNING) {
6182            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6183                    + " flags=0x" + Integer.toHexString(parseFlags));
6184        }
6185
6186        for (File file : files) {
6187            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6188                    && !PackageInstallerService.isStageName(file.getName());
6189            if (!isPackage) {
6190                // Ignore entries which are not packages
6191                continue;
6192            }
6193            try {
6194                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6195                        scanFlags, currentTime, null);
6196            } catch (PackageManagerException e) {
6197                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6198
6199                // Delete invalid userdata apps
6200                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6201                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6202                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6203                    removeCodePathLI(file);
6204                }
6205            }
6206        }
6207    }
6208
6209    private static File getSettingsProblemFile() {
6210        File dataDir = Environment.getDataDirectory();
6211        File systemDir = new File(dataDir, "system");
6212        File fname = new File(systemDir, "uiderrors.txt");
6213        return fname;
6214    }
6215
6216    static void reportSettingsProblem(int priority, String msg) {
6217        logCriticalInfo(priority, msg);
6218    }
6219
6220    static void logCriticalInfo(int priority, String msg) {
6221        Slog.println(priority, TAG, msg);
6222        EventLogTags.writePmCriticalInfo(msg);
6223        try {
6224            File fname = getSettingsProblemFile();
6225            FileOutputStream out = new FileOutputStream(fname, true);
6226            PrintWriter pw = new FastPrintWriter(out);
6227            SimpleDateFormat formatter = new SimpleDateFormat();
6228            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6229            pw.println(dateString + ": " + msg);
6230            pw.close();
6231            FileUtils.setPermissions(
6232                    fname.toString(),
6233                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6234                    -1, -1);
6235        } catch (java.io.IOException e) {
6236        }
6237    }
6238
6239    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6240            PackageParser.Package pkg, File srcFile, int parseFlags)
6241            throws PackageManagerException {
6242        if (ps != null
6243                && ps.codePath.equals(srcFile)
6244                && ps.timeStamp == srcFile.lastModified()
6245                && !isCompatSignatureUpdateNeeded(pkg)
6246                && !isRecoverSignatureUpdateNeeded(pkg)) {
6247            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6248            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6249            ArraySet<PublicKey> signingKs;
6250            synchronized (mPackages) {
6251                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6252            }
6253            if (ps.signatures.mSignatures != null
6254                    && ps.signatures.mSignatures.length != 0
6255                    && signingKs != null) {
6256                // Optimization: reuse the existing cached certificates
6257                // if the package appears to be unchanged.
6258                pkg.mSignatures = ps.signatures.mSignatures;
6259                pkg.mSigningKeys = signingKs;
6260                return;
6261            }
6262
6263            Slog.w(TAG, "PackageSetting for " + ps.name
6264                    + " is missing signatures.  Collecting certs again to recover them.");
6265        } else {
6266            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6267        }
6268
6269        try {
6270            pp.collectCertificates(pkg, parseFlags);
6271        } catch (PackageParserException e) {
6272            throw PackageManagerException.from(e);
6273        }
6274    }
6275
6276    /**
6277     *  Traces a package scan.
6278     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6279     */
6280    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6281            long currentTime, UserHandle user) throws PackageManagerException {
6282        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6283        try {
6284            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6285        } finally {
6286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6287        }
6288    }
6289
6290    /**
6291     *  Scans a package and returns the newly parsed package.
6292     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6293     */
6294    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6295            long currentTime, UserHandle user) throws PackageManagerException {
6296        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6297        parseFlags |= mDefParseFlags;
6298        PackageParser pp = new PackageParser();
6299        pp.setSeparateProcesses(mSeparateProcesses);
6300        pp.setOnlyCoreApps(mOnlyCore);
6301        pp.setDisplayMetrics(mMetrics);
6302
6303        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6304            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6305        }
6306
6307        final PackageParser.Package pkg;
6308        try {
6309            pkg = pp.parsePackage(scanFile, parseFlags);
6310        } catch (PackageParserException e) {
6311            throw PackageManagerException.from(e);
6312        }
6313
6314        PackageSetting ps = null;
6315        PackageSetting updatedPkg;
6316        // reader
6317        synchronized (mPackages) {
6318            // Look to see if we already know about this package.
6319            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6320            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6321                // This package has been renamed to its original name.  Let's
6322                // use that.
6323                ps = mSettings.peekPackageLPr(oldName);
6324            }
6325            // If there was no original package, see one for the real package name.
6326            if (ps == null) {
6327                ps = mSettings.peekPackageLPr(pkg.packageName);
6328            }
6329            // Check to see if this package could be hiding/updating a system
6330            // package.  Must look for it either under the original or real
6331            // package name depending on our state.
6332            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6333            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6334        }
6335        boolean updatedPkgBetter = false;
6336        // First check if this is a system package that may involve an update
6337        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6338            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6339            // it needs to drop FLAG_PRIVILEGED.
6340            if (locationIsPrivileged(scanFile)) {
6341                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6342            } else {
6343                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6344            }
6345
6346            if (ps != null && !ps.codePath.equals(scanFile)) {
6347                // The path has changed from what was last scanned...  check the
6348                // version of the new path against what we have stored to determine
6349                // what to do.
6350                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6351                if (pkg.mVersionCode <= ps.versionCode) {
6352                    // The system package has been updated and the code path does not match
6353                    // Ignore entry. Skip it.
6354                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6355                            + " ignored: updated version " + ps.versionCode
6356                            + " better than this " + pkg.mVersionCode);
6357                    if (!updatedPkg.codePath.equals(scanFile)) {
6358                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6359                                + ps.name + " changing from " + updatedPkg.codePathString
6360                                + " to " + scanFile);
6361                        updatedPkg.codePath = scanFile;
6362                        updatedPkg.codePathString = scanFile.toString();
6363                        updatedPkg.resourcePath = scanFile;
6364                        updatedPkg.resourcePathString = scanFile.toString();
6365                    }
6366                    updatedPkg.pkg = pkg;
6367                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6368                            "Package " + ps.name + " at " + scanFile
6369                                    + " ignored: updated version " + ps.versionCode
6370                                    + " better than this " + pkg.mVersionCode);
6371                } else {
6372                    // The current app on the system partition is better than
6373                    // what we have updated to on the data partition; switch
6374                    // back to the system partition version.
6375                    // At this point, its safely assumed that package installation for
6376                    // apps in system partition will go through. If not there won't be a working
6377                    // version of the app
6378                    // writer
6379                    synchronized (mPackages) {
6380                        // Just remove the loaded entries from package lists.
6381                        mPackages.remove(ps.name);
6382                    }
6383
6384                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6385                            + " reverting from " + ps.codePathString
6386                            + ": new version " + pkg.mVersionCode
6387                            + " better than installed " + ps.versionCode);
6388
6389                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6390                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6391                    synchronized (mInstallLock) {
6392                        args.cleanUpResourcesLI();
6393                    }
6394                    synchronized (mPackages) {
6395                        mSettings.enableSystemPackageLPw(ps.name);
6396                    }
6397                    updatedPkgBetter = true;
6398                }
6399            }
6400        }
6401
6402        if (updatedPkg != null) {
6403            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6404            // initially
6405            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6406
6407            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6408            // flag set initially
6409            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6410                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6411            }
6412        }
6413
6414        // Verify certificates against what was last scanned
6415        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6416
6417        /*
6418         * A new system app appeared, but we already had a non-system one of the
6419         * same name installed earlier.
6420         */
6421        boolean shouldHideSystemApp = false;
6422        if (updatedPkg == null && ps != null
6423                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6424            /*
6425             * Check to make sure the signatures match first. If they don't,
6426             * wipe the installed application and its data.
6427             */
6428            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6429                    != PackageManager.SIGNATURE_MATCH) {
6430                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6431                        + " signatures don't match existing userdata copy; removing");
6432                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6433                ps = null;
6434            } else {
6435                /*
6436                 * If the newly-added system app is an older version than the
6437                 * already installed version, hide it. It will be scanned later
6438                 * and re-added like an update.
6439                 */
6440                if (pkg.mVersionCode <= ps.versionCode) {
6441                    shouldHideSystemApp = true;
6442                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6443                            + " but new version " + pkg.mVersionCode + " better than installed "
6444                            + ps.versionCode + "; hiding system");
6445                } else {
6446                    /*
6447                     * The newly found system app is a newer version that the
6448                     * one previously installed. Simply remove the
6449                     * already-installed application and replace it with our own
6450                     * while keeping the application data.
6451                     */
6452                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6453                            + " reverting from " + ps.codePathString + ": new version "
6454                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6455                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6456                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6457                    synchronized (mInstallLock) {
6458                        args.cleanUpResourcesLI();
6459                    }
6460                }
6461            }
6462        }
6463
6464        // The apk is forward locked (not public) if its code and resources
6465        // are kept in different files. (except for app in either system or
6466        // vendor path).
6467        // TODO grab this value from PackageSettings
6468        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6469            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6470                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6471            }
6472        }
6473
6474        // TODO: extend to support forward-locked splits
6475        String resourcePath = null;
6476        String baseResourcePath = null;
6477        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6478            if (ps != null && ps.resourcePathString != null) {
6479                resourcePath = ps.resourcePathString;
6480                baseResourcePath = ps.resourcePathString;
6481            } else {
6482                // Should not happen at all. Just log an error.
6483                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6484            }
6485        } else {
6486            resourcePath = pkg.codePath;
6487            baseResourcePath = pkg.baseCodePath;
6488        }
6489
6490        // Set application objects path explicitly.
6491        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6492        pkg.applicationInfo.setCodePath(pkg.codePath);
6493        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6494        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6495        pkg.applicationInfo.setResourcePath(resourcePath);
6496        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6497        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6498
6499        // Note that we invoke the following method only if we are about to unpack an application
6500        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6501                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6502
6503        /*
6504         * If the system app should be overridden by a previously installed
6505         * data, hide the system app now and let the /data/app scan pick it up
6506         * again.
6507         */
6508        if (shouldHideSystemApp) {
6509            synchronized (mPackages) {
6510                mSettings.disableSystemPackageLPw(pkg.packageName);
6511            }
6512        }
6513
6514        return scannedPkg;
6515    }
6516
6517    private static String fixProcessName(String defProcessName,
6518            String processName, int uid) {
6519        if (processName == null) {
6520            return defProcessName;
6521        }
6522        return processName;
6523    }
6524
6525    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6526            throws PackageManagerException {
6527        if (pkgSetting.signatures.mSignatures != null) {
6528            // Already existing package. Make sure signatures match
6529            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6530                    == PackageManager.SIGNATURE_MATCH;
6531            if (!match) {
6532                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6533                        == PackageManager.SIGNATURE_MATCH;
6534            }
6535            if (!match) {
6536                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6537                        == PackageManager.SIGNATURE_MATCH;
6538            }
6539            if (!match) {
6540                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6541                        + pkg.packageName + " signatures do not match the "
6542                        + "previously installed version; ignoring!");
6543            }
6544        }
6545
6546        // Check for shared user signatures
6547        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6548            // Already existing package. Make sure signatures match
6549            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6550                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6551            if (!match) {
6552                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6553                        == PackageManager.SIGNATURE_MATCH;
6554            }
6555            if (!match) {
6556                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6557                        == PackageManager.SIGNATURE_MATCH;
6558            }
6559            if (!match) {
6560                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6561                        "Package " + pkg.packageName
6562                        + " has no signatures that match those in shared user "
6563                        + pkgSetting.sharedUser.name + "; ignoring!");
6564            }
6565        }
6566    }
6567
6568    /**
6569     * Enforces that only the system UID or root's UID can call a method exposed
6570     * via Binder.
6571     *
6572     * @param message used as message if SecurityException is thrown
6573     * @throws SecurityException if the caller is not system or root
6574     */
6575    private static final void enforceSystemOrRoot(String message) {
6576        final int uid = Binder.getCallingUid();
6577        if (uid != Process.SYSTEM_UID && uid != 0) {
6578            throw new SecurityException(message);
6579        }
6580    }
6581
6582    @Override
6583    public void performFstrimIfNeeded() {
6584        enforceSystemOrRoot("Only the system can request fstrim");
6585
6586        // Before everything else, see whether we need to fstrim.
6587        try {
6588            IMountService ms = PackageHelper.getMountService();
6589            if (ms != null) {
6590                final boolean isUpgrade = isUpgrade();
6591                boolean doTrim = isUpgrade;
6592                if (doTrim) {
6593                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6594                } else {
6595                    final long interval = android.provider.Settings.Global.getLong(
6596                            mContext.getContentResolver(),
6597                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6598                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6599                    if (interval > 0) {
6600                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6601                        if (timeSinceLast > interval) {
6602                            doTrim = true;
6603                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6604                                    + "; running immediately");
6605                        }
6606                    }
6607                }
6608                if (doTrim) {
6609                    if (!isFirstBoot()) {
6610                        try {
6611                            ActivityManagerNative.getDefault().showBootMessage(
6612                                    mContext.getResources().getString(
6613                                            R.string.android_upgrading_fstrim), true);
6614                        } catch (RemoteException e) {
6615                        }
6616                    }
6617                    ms.runMaintenance();
6618                }
6619            } else {
6620                Slog.e(TAG, "Mount service unavailable!");
6621            }
6622        } catch (RemoteException e) {
6623            // Can't happen; MountService is local
6624        }
6625    }
6626
6627    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6628        List<ResolveInfo> ris = null;
6629        try {
6630            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6631                    intent, null, 0, userId);
6632        } catch (RemoteException e) {
6633        }
6634        ArraySet<String> pkgNames = new ArraySet<String>();
6635        if (ris != null) {
6636            for (ResolveInfo ri : ris) {
6637                pkgNames.add(ri.activityInfo.packageName);
6638            }
6639        }
6640        return pkgNames;
6641    }
6642
6643    @Override
6644    public void notifyPackageUse(String packageName) {
6645        synchronized (mPackages) {
6646            PackageParser.Package p = mPackages.get(packageName);
6647            if (p == null) {
6648                return;
6649            }
6650            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6651        }
6652    }
6653
6654    // TODO: this is not used nor needed. Delete it.
6655    @Override
6656    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6657        return performDexOptTraced(packageName, instructionSet, false);
6658    }
6659
6660    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles) {
6661        return performDexOptTraced(packageName, instructionSet, useProfiles);
6662    }
6663
6664    private boolean performDexOptTraced(String packageName, String instructionSet,
6665                boolean useProfiles) {
6666        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6667        try {
6668            return performDexOptInternal(packageName, instructionSet, useProfiles);
6669        } finally {
6670            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6671        }
6672    }
6673
6674    private boolean performDexOptInternal(String packageName, String instructionSet,
6675                boolean useProfiles) {
6676        PackageParser.Package p;
6677        final String targetInstructionSet;
6678        synchronized (mPackages) {
6679            p = mPackages.get(packageName);
6680            if (p == null) {
6681                return false;
6682            }
6683            mPackageUsage.write(false);
6684
6685            targetInstructionSet = instructionSet != null ? instructionSet :
6686                    getPrimaryInstructionSet(p.applicationInfo);
6687            if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6688                // Skip only if we do not use profiles since they might trigger a recompilation.
6689                return false;
6690            }
6691        }
6692        long callingId = Binder.clearCallingIdentity();
6693        try {
6694            synchronized (mInstallLock) {
6695                final String[] instructionSets = new String[] { targetInstructionSet };
6696                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6697                        true /* inclDependencies */, p.volumeUuid, useProfiles);
6698                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6699            }
6700        } finally {
6701            Binder.restoreCallingIdentity(callingId);
6702        }
6703    }
6704
6705    public ArraySet<String> getOptimizablePackages() {
6706        ArraySet<String> pkgs = new ArraySet<String>();
6707        synchronized (mPackages) {
6708            for (PackageParser.Package p : mPackages.values()) {
6709                if (PackageDexOptimizer.canOptimizePackage(p)) {
6710                    pkgs.add(p.packageName);
6711                }
6712            }
6713        }
6714        return pkgs;
6715    }
6716
6717    public void shutdown() {
6718        mPackageUsage.write(true);
6719    }
6720
6721    @Override
6722    public void forceDexOpt(String packageName) {
6723        enforceSystemOrRoot("forceDexOpt");
6724
6725        PackageParser.Package pkg;
6726        synchronized (mPackages) {
6727            pkg = mPackages.get(packageName);
6728            if (pkg == null) {
6729                throw new IllegalArgumentException("Unknown package: " + packageName);
6730            }
6731        }
6732
6733        synchronized (mInstallLock) {
6734            final String[] instructionSets = new String[] {
6735                    getPrimaryInstructionSet(pkg.applicationInfo) };
6736
6737            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6738
6739            // Whoever is calling forceDexOpt wants a fully compiled package.
6740            // Don't use profiles since that may cause compilation to be skipped.
6741            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6742                    true /* inclDependencies */, pkg.volumeUuid, false /* useProfiles */);
6743
6744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6745            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6746                throw new IllegalStateException("Failed to dexopt: " + res);
6747            }
6748        }
6749    }
6750
6751    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6752        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6753            Slog.w(TAG, "Unable to update from " + oldPkg.name
6754                    + " to " + newPkg.packageName
6755                    + ": old package not in system partition");
6756            return false;
6757        } else if (mPackages.get(oldPkg.name) != null) {
6758            Slog.w(TAG, "Unable to update from " + oldPkg.name
6759                    + " to " + newPkg.packageName
6760                    + ": old package still exists");
6761            return false;
6762        }
6763        return true;
6764    }
6765
6766    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6767        // TODO: triage flags as part of 26466827
6768        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6769
6770        boolean res = true;
6771        final int[] users = sUserManager.getUserIds();
6772        for (int user : users) {
6773            try {
6774                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6775            } catch (InstallerException e) {
6776                Slog.w(TAG, "Failed to delete data directory", e);
6777                res = false;
6778            }
6779        }
6780        return res;
6781    }
6782
6783    void removeCodePathLI(File codePath) {
6784        if (codePath.isDirectory()) {
6785            try {
6786                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6787            } catch (InstallerException e) {
6788                Slog.w(TAG, "Failed to remove code path", e);
6789            }
6790        } else {
6791            codePath.delete();
6792        }
6793    }
6794
6795    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6796        try {
6797            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6798        } catch (InstallerException e) {
6799            Slog.w(TAG, "Failed to destroy app data", e);
6800        }
6801    }
6802
6803    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6804            int appId, String seinfo) {
6805        try {
6806            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6807        } catch (InstallerException e) {
6808            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6809        }
6810    }
6811
6812    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6813        // TODO: triage flags as part of 26466827
6814        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6815
6816        final int[] users = sUserManager.getUserIds();
6817        for (int user : users) {
6818            try {
6819                mInstaller.clearAppData(volumeUuid, packageName, user,
6820                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6821            } catch (InstallerException e) {
6822                Slog.w(TAG, "Failed to delete code cache directory", e);
6823            }
6824        }
6825    }
6826
6827    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6828            PackageParser.Package changingLib) {
6829        if (file.path != null) {
6830            usesLibraryFiles.add(file.path);
6831            return;
6832        }
6833        PackageParser.Package p = mPackages.get(file.apk);
6834        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6835            // If we are doing this while in the middle of updating a library apk,
6836            // then we need to make sure to use that new apk for determining the
6837            // dependencies here.  (We haven't yet finished committing the new apk
6838            // to the package manager state.)
6839            if (p == null || p.packageName.equals(changingLib.packageName)) {
6840                p = changingLib;
6841            }
6842        }
6843        if (p != null) {
6844            usesLibraryFiles.addAll(p.getAllCodePaths());
6845        }
6846    }
6847
6848    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6849            PackageParser.Package changingLib) throws PackageManagerException {
6850        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6851            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6852            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6853            for (int i=0; i<N; i++) {
6854                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6855                if (file == null) {
6856                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6857                            "Package " + pkg.packageName + " requires unavailable shared library "
6858                            + pkg.usesLibraries.get(i) + "; failing!");
6859                }
6860                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6861            }
6862            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6863            for (int i=0; i<N; i++) {
6864                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6865                if (file == null) {
6866                    Slog.w(TAG, "Package " + pkg.packageName
6867                            + " desires unavailable shared library "
6868                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6869                } else {
6870                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6871                }
6872            }
6873            N = usesLibraryFiles.size();
6874            if (N > 0) {
6875                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6876            } else {
6877                pkg.usesLibraryFiles = null;
6878            }
6879        }
6880    }
6881
6882    private static boolean hasString(List<String> list, List<String> which) {
6883        if (list == null) {
6884            return false;
6885        }
6886        for (int i=list.size()-1; i>=0; i--) {
6887            for (int j=which.size()-1; j>=0; j--) {
6888                if (which.get(j).equals(list.get(i))) {
6889                    return true;
6890                }
6891            }
6892        }
6893        return false;
6894    }
6895
6896    private void updateAllSharedLibrariesLPw() {
6897        for (PackageParser.Package pkg : mPackages.values()) {
6898            try {
6899                updateSharedLibrariesLPw(pkg, null);
6900            } catch (PackageManagerException e) {
6901                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6902            }
6903        }
6904    }
6905
6906    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6907            PackageParser.Package changingPkg) {
6908        ArrayList<PackageParser.Package> res = null;
6909        for (PackageParser.Package pkg : mPackages.values()) {
6910            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6911                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6912                if (res == null) {
6913                    res = new ArrayList<PackageParser.Package>();
6914                }
6915                res.add(pkg);
6916                try {
6917                    updateSharedLibrariesLPw(pkg, changingPkg);
6918                } catch (PackageManagerException e) {
6919                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6920                }
6921            }
6922        }
6923        return res;
6924    }
6925
6926    /**
6927     * Derive the value of the {@code cpuAbiOverride} based on the provided
6928     * value and an optional stored value from the package settings.
6929     */
6930    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6931        String cpuAbiOverride = null;
6932
6933        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6934            cpuAbiOverride = null;
6935        } else if (abiOverride != null) {
6936            cpuAbiOverride = abiOverride;
6937        } else if (settings != null) {
6938            cpuAbiOverride = settings.cpuAbiOverrideString;
6939        }
6940
6941        return cpuAbiOverride;
6942    }
6943
6944    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6945            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6946        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6947        try {
6948            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6949        } finally {
6950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6951        }
6952    }
6953
6954    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6955            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6956        boolean success = false;
6957        try {
6958            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6959                    currentTime, user);
6960            success = true;
6961            return res;
6962        } finally {
6963            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6964                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6965            }
6966        }
6967    }
6968
6969    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6970            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6971        final File scanFile = new File(pkg.codePath);
6972        if (pkg.applicationInfo.getCodePath() == null ||
6973                pkg.applicationInfo.getResourcePath() == null) {
6974            // Bail out. The resource and code paths haven't been set.
6975            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6976                    "Code and resource paths haven't been set correctly");
6977        }
6978
6979        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6980            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6981        } else {
6982            // Only allow system apps to be flagged as core apps.
6983            pkg.coreApp = false;
6984        }
6985
6986        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6987            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6988        }
6989
6990        if (mCustomResolverComponentName != null &&
6991                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6992            setUpCustomResolverActivity(pkg);
6993        }
6994
6995        if (pkg.packageName.equals("android")) {
6996            synchronized (mPackages) {
6997                if (mAndroidApplication != null) {
6998                    Slog.w(TAG, "*************************************************");
6999                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7000                    Slog.w(TAG, " file=" + scanFile);
7001                    Slog.w(TAG, "*************************************************");
7002                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7003                            "Core android package being redefined.  Skipping.");
7004                }
7005
7006                // Set up information for our fall-back user intent resolution activity.
7007                mPlatformPackage = pkg;
7008                pkg.mVersionCode = mSdkVersion;
7009                mAndroidApplication = pkg.applicationInfo;
7010
7011                if (!mResolverReplaced) {
7012                    mResolveActivity.applicationInfo = mAndroidApplication;
7013                    mResolveActivity.name = ResolverActivity.class.getName();
7014                    mResolveActivity.packageName = mAndroidApplication.packageName;
7015                    mResolveActivity.processName = "system:ui";
7016                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7017                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7018                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7019                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7020                    mResolveActivity.exported = true;
7021                    mResolveActivity.enabled = true;
7022                    mResolveInfo.activityInfo = mResolveActivity;
7023                    mResolveInfo.priority = 0;
7024                    mResolveInfo.preferredOrder = 0;
7025                    mResolveInfo.match = 0;
7026                    mResolveComponentName = new ComponentName(
7027                            mAndroidApplication.packageName, mResolveActivity.name);
7028                }
7029            }
7030        }
7031
7032        if (DEBUG_PACKAGE_SCANNING) {
7033            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7034                Log.d(TAG, "Scanning package " + pkg.packageName);
7035        }
7036
7037        if (mPackages.containsKey(pkg.packageName)
7038                || mSharedLibraries.containsKey(pkg.packageName)) {
7039            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7040                    "Application package " + pkg.packageName
7041                    + " already installed.  Skipping duplicate.");
7042        }
7043
7044        // If we're only installing presumed-existing packages, require that the
7045        // scanned APK is both already known and at the path previously established
7046        // for it.  Previously unknown packages we pick up normally, but if we have an
7047        // a priori expectation about this package's install presence, enforce it.
7048        // With a singular exception for new system packages. When an OTA contains
7049        // a new system package, we allow the codepath to change from a system location
7050        // to the user-installed location. If we don't allow this change, any newer,
7051        // user-installed version of the application will be ignored.
7052        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7053            if (mExpectingBetter.containsKey(pkg.packageName)) {
7054                logCriticalInfo(Log.WARN,
7055                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7056            } else {
7057                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7058                if (known != null) {
7059                    if (DEBUG_PACKAGE_SCANNING) {
7060                        Log.d(TAG, "Examining " + pkg.codePath
7061                                + " and requiring known paths " + known.codePathString
7062                                + " & " + known.resourcePathString);
7063                    }
7064                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7065                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7066                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7067                                "Application package " + pkg.packageName
7068                                + " found at " + pkg.applicationInfo.getCodePath()
7069                                + " but expected at " + known.codePathString + "; ignoring.");
7070                    }
7071                }
7072            }
7073        }
7074
7075        // Initialize package source and resource directories
7076        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7077        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7078
7079        SharedUserSetting suid = null;
7080        PackageSetting pkgSetting = null;
7081
7082        if (!isSystemApp(pkg)) {
7083            // Only system apps can use these features.
7084            pkg.mOriginalPackages = null;
7085            pkg.mRealPackage = null;
7086            pkg.mAdoptPermissions = null;
7087        }
7088
7089        // writer
7090        synchronized (mPackages) {
7091            if (pkg.mSharedUserId != null) {
7092                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7093                if (suid == null) {
7094                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7095                            "Creating application package " + pkg.packageName
7096                            + " for shared user failed");
7097                }
7098                if (DEBUG_PACKAGE_SCANNING) {
7099                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7100                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7101                                + "): packages=" + suid.packages);
7102                }
7103            }
7104
7105            // Check if we are renaming from an original package name.
7106            PackageSetting origPackage = null;
7107            String realName = null;
7108            if (pkg.mOriginalPackages != null) {
7109                // This package may need to be renamed to a previously
7110                // installed name.  Let's check on that...
7111                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7112                if (pkg.mOriginalPackages.contains(renamed)) {
7113                    // This package had originally been installed as the
7114                    // original name, and we have already taken care of
7115                    // transitioning to the new one.  Just update the new
7116                    // one to continue using the old name.
7117                    realName = pkg.mRealPackage;
7118                    if (!pkg.packageName.equals(renamed)) {
7119                        // Callers into this function may have already taken
7120                        // care of renaming the package; only do it here if
7121                        // it is not already done.
7122                        pkg.setPackageName(renamed);
7123                    }
7124
7125                } else {
7126                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7127                        if ((origPackage = mSettings.peekPackageLPr(
7128                                pkg.mOriginalPackages.get(i))) != null) {
7129                            // We do have the package already installed under its
7130                            // original name...  should we use it?
7131                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7132                                // New package is not compatible with original.
7133                                origPackage = null;
7134                                continue;
7135                            } else if (origPackage.sharedUser != null) {
7136                                // Make sure uid is compatible between packages.
7137                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7138                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7139                                            + " to " + pkg.packageName + ": old uid "
7140                                            + origPackage.sharedUser.name
7141                                            + " differs from " + pkg.mSharedUserId);
7142                                    origPackage = null;
7143                                    continue;
7144                                }
7145                            } else {
7146                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7147                                        + pkg.packageName + " to old name " + origPackage.name);
7148                            }
7149                            break;
7150                        }
7151                    }
7152                }
7153            }
7154
7155            if (mTransferedPackages.contains(pkg.packageName)) {
7156                Slog.w(TAG, "Package " + pkg.packageName
7157                        + " was transferred to another, but its .apk remains");
7158            }
7159
7160            // Just create the setting, don't add it yet. For already existing packages
7161            // the PkgSetting exists already and doesn't have to be created.
7162            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7163                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7164                    pkg.applicationInfo.primaryCpuAbi,
7165                    pkg.applicationInfo.secondaryCpuAbi,
7166                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7167                    user, false);
7168            if (pkgSetting == null) {
7169                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7170                        "Creating application package " + pkg.packageName + " failed");
7171            }
7172
7173            if (pkgSetting.origPackage != null) {
7174                // If we are first transitioning from an original package,
7175                // fix up the new package's name now.  We need to do this after
7176                // looking up the package under its new name, so getPackageLP
7177                // can take care of fiddling things correctly.
7178                pkg.setPackageName(origPackage.name);
7179
7180                // File a report about this.
7181                String msg = "New package " + pkgSetting.realName
7182                        + " renamed to replace old package " + pkgSetting.name;
7183                reportSettingsProblem(Log.WARN, msg);
7184
7185                // Make a note of it.
7186                mTransferedPackages.add(origPackage.name);
7187
7188                // No longer need to retain this.
7189                pkgSetting.origPackage = null;
7190            }
7191
7192            if (realName != null) {
7193                // Make a note of it.
7194                mTransferedPackages.add(pkg.packageName);
7195            }
7196
7197            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7198                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7199            }
7200
7201            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7202                // Check all shared libraries and map to their actual file path.
7203                // We only do this here for apps not on a system dir, because those
7204                // are the only ones that can fail an install due to this.  We
7205                // will take care of the system apps by updating all of their
7206                // library paths after the scan is done.
7207                updateSharedLibrariesLPw(pkg, null);
7208            }
7209
7210            if (mFoundPolicyFile) {
7211                SELinuxMMAC.assignSeinfoValue(pkg);
7212            }
7213
7214            pkg.applicationInfo.uid = pkgSetting.appId;
7215            pkg.mExtras = pkgSetting;
7216            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7217                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7218                    // We just determined the app is signed correctly, so bring
7219                    // over the latest parsed certs.
7220                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7221                } else {
7222                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7223                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7224                                "Package " + pkg.packageName + " upgrade keys do not match the "
7225                                + "previously installed version");
7226                    } else {
7227                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7228                        String msg = "System package " + pkg.packageName
7229                            + " signature changed; retaining data.";
7230                        reportSettingsProblem(Log.WARN, msg);
7231                    }
7232                }
7233            } else {
7234                try {
7235                    verifySignaturesLP(pkgSetting, pkg);
7236                    // We just determined the app is signed correctly, so bring
7237                    // over the latest parsed certs.
7238                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7239                } catch (PackageManagerException e) {
7240                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7241                        throw e;
7242                    }
7243                    // The signature has changed, but this package is in the system
7244                    // image...  let's recover!
7245                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7246                    // However...  if this package is part of a shared user, but it
7247                    // doesn't match the signature of the shared user, let's fail.
7248                    // What this means is that you can't change the signatures
7249                    // associated with an overall shared user, which doesn't seem all
7250                    // that unreasonable.
7251                    if (pkgSetting.sharedUser != null) {
7252                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7253                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7254                            throw new PackageManagerException(
7255                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7256                                            "Signature mismatch for shared user: "
7257                                            + pkgSetting.sharedUser);
7258                        }
7259                    }
7260                    // File a report about this.
7261                    String msg = "System package " + pkg.packageName
7262                        + " signature changed; retaining data.";
7263                    reportSettingsProblem(Log.WARN, msg);
7264                }
7265            }
7266            // Verify that this new package doesn't have any content providers
7267            // that conflict with existing packages.  Only do this if the
7268            // package isn't already installed, since we don't want to break
7269            // things that are installed.
7270            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7271                final int N = pkg.providers.size();
7272                int i;
7273                for (i=0; i<N; i++) {
7274                    PackageParser.Provider p = pkg.providers.get(i);
7275                    if (p.info.authority != null) {
7276                        String names[] = p.info.authority.split(";");
7277                        for (int j = 0; j < names.length; j++) {
7278                            if (mProvidersByAuthority.containsKey(names[j])) {
7279                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7280                                final String otherPackageName =
7281                                        ((other != null && other.getComponentName() != null) ?
7282                                                other.getComponentName().getPackageName() : "?");
7283                                throw new PackageManagerException(
7284                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7285                                                "Can't install because provider name " + names[j]
7286                                                + " (in package " + pkg.applicationInfo.packageName
7287                                                + ") is already used by " + otherPackageName);
7288                            }
7289                        }
7290                    }
7291                }
7292            }
7293
7294            if (pkg.mAdoptPermissions != null) {
7295                // This package wants to adopt ownership of permissions from
7296                // another package.
7297                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7298                    final String origName = pkg.mAdoptPermissions.get(i);
7299                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7300                    if (orig != null) {
7301                        if (verifyPackageUpdateLPr(orig, pkg)) {
7302                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7303                                    + pkg.packageName);
7304                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7305                        }
7306                    }
7307                }
7308            }
7309        }
7310
7311        final String pkgName = pkg.packageName;
7312
7313        final long scanFileTime = scanFile.lastModified();
7314        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7315        pkg.applicationInfo.processName = fixProcessName(
7316                pkg.applicationInfo.packageName,
7317                pkg.applicationInfo.processName,
7318                pkg.applicationInfo.uid);
7319
7320        if (pkg != mPlatformPackage) {
7321            // Get all of our default paths setup
7322            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7323        }
7324
7325        final String path = scanFile.getPath();
7326        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7327
7328        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7329            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7330
7331            // Some system apps still use directory structure for native libraries
7332            // in which case we might end up not detecting abi solely based on apk
7333            // structure. Try to detect abi based on directory structure.
7334            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7335                    pkg.applicationInfo.primaryCpuAbi == null) {
7336                setBundledAppAbisAndRoots(pkg, pkgSetting);
7337                setNativeLibraryPaths(pkg);
7338            }
7339
7340        } else {
7341            if ((scanFlags & SCAN_MOVE) != 0) {
7342                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7343                // but we already have this packages package info in the PackageSetting. We just
7344                // use that and derive the native library path based on the new codepath.
7345                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7346                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7347            }
7348
7349            // Set native library paths again. For moves, the path will be updated based on the
7350            // ABIs we've determined above. For non-moves, the path will be updated based on the
7351            // ABIs we determined during compilation, but the path will depend on the final
7352            // package path (after the rename away from the stage path).
7353            setNativeLibraryPaths(pkg);
7354        }
7355
7356        // This is a special case for the "system" package, where the ABI is
7357        // dictated by the zygote configuration (and init.rc). We should keep track
7358        // of this ABI so that we can deal with "normal" applications that run under
7359        // the same UID correctly.
7360        if (mPlatformPackage == pkg) {
7361            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7362                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7363        }
7364
7365        // If there's a mismatch between the abi-override in the package setting
7366        // and the abiOverride specified for the install. Warn about this because we
7367        // would've already compiled the app without taking the package setting into
7368        // account.
7369        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7370            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7371                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7372                        " for package " + pkg.packageName);
7373            }
7374        }
7375
7376        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7377        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7378        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7379
7380        // Copy the derived override back to the parsed package, so that we can
7381        // update the package settings accordingly.
7382        pkg.cpuAbiOverride = cpuAbiOverride;
7383
7384        if (DEBUG_ABI_SELECTION) {
7385            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7386                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7387                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7388        }
7389
7390        // Push the derived path down into PackageSettings so we know what to
7391        // clean up at uninstall time.
7392        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7393
7394        if (DEBUG_ABI_SELECTION) {
7395            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7396                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7397                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7398        }
7399
7400        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7401            // We don't do this here during boot because we can do it all
7402            // at once after scanning all existing packages.
7403            //
7404            // We also do this *before* we perform dexopt on this package, so that
7405            // we can avoid redundant dexopts, and also to make sure we've got the
7406            // code and package path correct.
7407            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7408                    pkg, true /* boot complete */);
7409        }
7410
7411        if (mFactoryTest && pkg.requestedPermissions.contains(
7412                android.Manifest.permission.FACTORY_TEST)) {
7413            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7414        }
7415
7416        ArrayList<PackageParser.Package> clientLibPkgs = null;
7417
7418        // writer
7419        synchronized (mPackages) {
7420            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7421                // Only system apps can add new shared libraries.
7422                if (pkg.libraryNames != null) {
7423                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7424                        String name = pkg.libraryNames.get(i);
7425                        boolean allowed = false;
7426                        if (pkg.isUpdatedSystemApp()) {
7427                            // New library entries can only be added through the
7428                            // system image.  This is important to get rid of a lot
7429                            // of nasty edge cases: for example if we allowed a non-
7430                            // system update of the app to add a library, then uninstalling
7431                            // the update would make the library go away, and assumptions
7432                            // we made such as through app install filtering would now
7433                            // have allowed apps on the device which aren't compatible
7434                            // with it.  Better to just have the restriction here, be
7435                            // conservative, and create many fewer cases that can negatively
7436                            // impact the user experience.
7437                            final PackageSetting sysPs = mSettings
7438                                    .getDisabledSystemPkgLPr(pkg.packageName);
7439                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7440                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7441                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7442                                        allowed = true;
7443                                        break;
7444                                    }
7445                                }
7446                            }
7447                        } else {
7448                            allowed = true;
7449                        }
7450                        if (allowed) {
7451                            if (!mSharedLibraries.containsKey(name)) {
7452                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7453                            } else if (!name.equals(pkg.packageName)) {
7454                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7455                                        + name + " already exists; skipping");
7456                            }
7457                        } else {
7458                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7459                                    + name + " that is not declared on system image; skipping");
7460                        }
7461                    }
7462                    if ((scanFlags & SCAN_BOOTING) == 0) {
7463                        // If we are not booting, we need to update any applications
7464                        // that are clients of our shared library.  If we are booting,
7465                        // this will all be done once the scan is complete.
7466                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7467                    }
7468                }
7469            }
7470        }
7471
7472        // Request the ActivityManager to kill the process(only for existing packages)
7473        // so that we do not end up in a confused state while the user is still using the older
7474        // version of the application while the new one gets installed.
7475        if ((scanFlags & SCAN_REPLACING) != 0) {
7476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7477
7478            killApplication(pkg.applicationInfo.packageName,
7479                        pkg.applicationInfo.uid, "replace pkg");
7480
7481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7482        }
7483
7484        // Also need to kill any apps that are dependent on the library.
7485        if (clientLibPkgs != null) {
7486            for (int i=0; i<clientLibPkgs.size(); i++) {
7487                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7488                killApplication(clientPkg.applicationInfo.packageName,
7489                        clientPkg.applicationInfo.uid, "update lib");
7490            }
7491        }
7492
7493        // Make sure we're not adding any bogus keyset info
7494        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7495        ksms.assertScannedPackageValid(pkg);
7496
7497        // writer
7498        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7499
7500        boolean createIdmapFailed = false;
7501        synchronized (mPackages) {
7502            // We don't expect installation to fail beyond this point
7503
7504            // Add the new setting to mSettings
7505            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7506            // Add the new setting to mPackages
7507            mPackages.put(pkg.applicationInfo.packageName, pkg);
7508            // Make sure we don't accidentally delete its data.
7509            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7510            while (iter.hasNext()) {
7511                PackageCleanItem item = iter.next();
7512                if (pkgName.equals(item.packageName)) {
7513                    iter.remove();
7514                }
7515            }
7516
7517            // Take care of first install / last update times.
7518            if (currentTime != 0) {
7519                if (pkgSetting.firstInstallTime == 0) {
7520                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7521                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7522                    pkgSetting.lastUpdateTime = currentTime;
7523                }
7524            } else if (pkgSetting.firstInstallTime == 0) {
7525                // We need *something*.  Take time time stamp of the file.
7526                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7527            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7528                if (scanFileTime != pkgSetting.timeStamp) {
7529                    // A package on the system image has changed; consider this
7530                    // to be an update.
7531                    pkgSetting.lastUpdateTime = scanFileTime;
7532                }
7533            }
7534
7535            // Add the package's KeySets to the global KeySetManagerService
7536            ksms.addScannedPackageLPw(pkg);
7537
7538            int N = pkg.providers.size();
7539            StringBuilder r = null;
7540            int i;
7541            for (i=0; i<N; i++) {
7542                PackageParser.Provider p = pkg.providers.get(i);
7543                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7544                        p.info.processName, pkg.applicationInfo.uid);
7545                mProviders.addProvider(p);
7546                p.syncable = p.info.isSyncable;
7547                if (p.info.authority != null) {
7548                    String names[] = p.info.authority.split(";");
7549                    p.info.authority = null;
7550                    for (int j = 0; j < names.length; j++) {
7551                        if (j == 1 && p.syncable) {
7552                            // We only want the first authority for a provider to possibly be
7553                            // syncable, so if we already added this provider using a different
7554                            // authority clear the syncable flag. We copy the provider before
7555                            // changing it because the mProviders object contains a reference
7556                            // to a provider that we don't want to change.
7557                            // Only do this for the second authority since the resulting provider
7558                            // object can be the same for all future authorities for this provider.
7559                            p = new PackageParser.Provider(p);
7560                            p.syncable = false;
7561                        }
7562                        if (!mProvidersByAuthority.containsKey(names[j])) {
7563                            mProvidersByAuthority.put(names[j], p);
7564                            if (p.info.authority == null) {
7565                                p.info.authority = names[j];
7566                            } else {
7567                                p.info.authority = p.info.authority + ";" + names[j];
7568                            }
7569                            if (DEBUG_PACKAGE_SCANNING) {
7570                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7571                                    Log.d(TAG, "Registered content provider: " + names[j]
7572                                            + ", className = " + p.info.name + ", isSyncable = "
7573                                            + p.info.isSyncable);
7574                            }
7575                        } else {
7576                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7577                            Slog.w(TAG, "Skipping provider name " + names[j] +
7578                                    " (in package " + pkg.applicationInfo.packageName +
7579                                    "): name already used by "
7580                                    + ((other != null && other.getComponentName() != null)
7581                                            ? other.getComponentName().getPackageName() : "?"));
7582                        }
7583                    }
7584                }
7585                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7586                    if (r == null) {
7587                        r = new StringBuilder(256);
7588                    } else {
7589                        r.append(' ');
7590                    }
7591                    r.append(p.info.name);
7592                }
7593            }
7594            if (r != null) {
7595                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7596            }
7597
7598            N = pkg.services.size();
7599            r = null;
7600            for (i=0; i<N; i++) {
7601                PackageParser.Service s = pkg.services.get(i);
7602                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7603                        s.info.processName, pkg.applicationInfo.uid);
7604                mServices.addService(s);
7605                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7606                    if (r == null) {
7607                        r = new StringBuilder(256);
7608                    } else {
7609                        r.append(' ');
7610                    }
7611                    r.append(s.info.name);
7612                }
7613            }
7614            if (r != null) {
7615                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7616            }
7617
7618            N = pkg.receivers.size();
7619            r = null;
7620            for (i=0; i<N; i++) {
7621                PackageParser.Activity a = pkg.receivers.get(i);
7622                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7623                        a.info.processName, pkg.applicationInfo.uid);
7624                mReceivers.addActivity(a, "receiver");
7625                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7626                    if (r == null) {
7627                        r = new StringBuilder(256);
7628                    } else {
7629                        r.append(' ');
7630                    }
7631                    r.append(a.info.name);
7632                }
7633            }
7634            if (r != null) {
7635                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7636            }
7637
7638            N = pkg.activities.size();
7639            r = null;
7640            for (i=0; i<N; i++) {
7641                PackageParser.Activity a = pkg.activities.get(i);
7642                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7643                        a.info.processName, pkg.applicationInfo.uid);
7644                mActivities.addActivity(a, "activity");
7645                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7646                    if (r == null) {
7647                        r = new StringBuilder(256);
7648                    } else {
7649                        r.append(' ');
7650                    }
7651                    r.append(a.info.name);
7652                }
7653            }
7654            if (r != null) {
7655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7656            }
7657
7658            N = pkg.permissionGroups.size();
7659            r = null;
7660            for (i=0; i<N; i++) {
7661                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7662                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7663                if (cur == null) {
7664                    mPermissionGroups.put(pg.info.name, pg);
7665                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                        if (r == null) {
7667                            r = new StringBuilder(256);
7668                        } else {
7669                            r.append(' ');
7670                        }
7671                        r.append(pg.info.name);
7672                    }
7673                } else {
7674                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7675                            + pg.info.packageName + " ignored: original from "
7676                            + cur.info.packageName);
7677                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7678                        if (r == null) {
7679                            r = new StringBuilder(256);
7680                        } else {
7681                            r.append(' ');
7682                        }
7683                        r.append("DUP:");
7684                        r.append(pg.info.name);
7685                    }
7686                }
7687            }
7688            if (r != null) {
7689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7690            }
7691
7692            N = pkg.permissions.size();
7693            r = null;
7694            for (i=0; i<N; i++) {
7695                PackageParser.Permission p = pkg.permissions.get(i);
7696
7697                // Assume by default that we did not install this permission into the system.
7698                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7699
7700                // Now that permission groups have a special meaning, we ignore permission
7701                // groups for legacy apps to prevent unexpected behavior. In particular,
7702                // permissions for one app being granted to someone just becuase they happen
7703                // to be in a group defined by another app (before this had no implications).
7704                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7705                    p.group = mPermissionGroups.get(p.info.group);
7706                    // Warn for a permission in an unknown group.
7707                    if (p.info.group != null && p.group == null) {
7708                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7709                                + p.info.packageName + " in an unknown group " + p.info.group);
7710                    }
7711                }
7712
7713                ArrayMap<String, BasePermission> permissionMap =
7714                        p.tree ? mSettings.mPermissionTrees
7715                                : mSettings.mPermissions;
7716                BasePermission bp = permissionMap.get(p.info.name);
7717
7718                // Allow system apps to redefine non-system permissions
7719                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7720                    final boolean currentOwnerIsSystem = (bp.perm != null
7721                            && isSystemApp(bp.perm.owner));
7722                    if (isSystemApp(p.owner)) {
7723                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7724                            // It's a built-in permission and no owner, take ownership now
7725                            bp.packageSetting = pkgSetting;
7726                            bp.perm = p;
7727                            bp.uid = pkg.applicationInfo.uid;
7728                            bp.sourcePackage = p.info.packageName;
7729                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7730                        } else if (!currentOwnerIsSystem) {
7731                            String msg = "New decl " + p.owner + " of permission  "
7732                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7733                            reportSettingsProblem(Log.WARN, msg);
7734                            bp = null;
7735                        }
7736                    }
7737                }
7738
7739                if (bp == null) {
7740                    bp = new BasePermission(p.info.name, p.info.packageName,
7741                            BasePermission.TYPE_NORMAL);
7742                    permissionMap.put(p.info.name, bp);
7743                }
7744
7745                if (bp.perm == null) {
7746                    if (bp.sourcePackage == null
7747                            || bp.sourcePackage.equals(p.info.packageName)) {
7748                        BasePermission tree = findPermissionTreeLP(p.info.name);
7749                        if (tree == null
7750                                || tree.sourcePackage.equals(p.info.packageName)) {
7751                            bp.packageSetting = pkgSetting;
7752                            bp.perm = p;
7753                            bp.uid = pkg.applicationInfo.uid;
7754                            bp.sourcePackage = p.info.packageName;
7755                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7756                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7757                                if (r == null) {
7758                                    r = new StringBuilder(256);
7759                                } else {
7760                                    r.append(' ');
7761                                }
7762                                r.append(p.info.name);
7763                            }
7764                        } else {
7765                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7766                                    + p.info.packageName + " ignored: base tree "
7767                                    + tree.name + " is from package "
7768                                    + tree.sourcePackage);
7769                        }
7770                    } else {
7771                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7772                                + p.info.packageName + " ignored: original from "
7773                                + bp.sourcePackage);
7774                    }
7775                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7776                    if (r == null) {
7777                        r = new StringBuilder(256);
7778                    } else {
7779                        r.append(' ');
7780                    }
7781                    r.append("DUP:");
7782                    r.append(p.info.name);
7783                }
7784                if (bp.perm == p) {
7785                    bp.protectionLevel = p.info.protectionLevel;
7786                }
7787            }
7788
7789            if (r != null) {
7790                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7791            }
7792
7793            N = pkg.instrumentation.size();
7794            r = null;
7795            for (i=0; i<N; i++) {
7796                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7797                a.info.packageName = pkg.applicationInfo.packageName;
7798                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7799                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7800                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7801                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7802                a.info.dataDir = pkg.applicationInfo.dataDir;
7803                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7804                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7805
7806                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7807                // need other information about the application, like the ABI and what not ?
7808                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7809                mInstrumentation.put(a.getComponentName(), a);
7810                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7811                    if (r == null) {
7812                        r = new StringBuilder(256);
7813                    } else {
7814                        r.append(' ');
7815                    }
7816                    r.append(a.info.name);
7817                }
7818            }
7819            if (r != null) {
7820                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7821            }
7822
7823            if (pkg.protectedBroadcasts != null) {
7824                N = pkg.protectedBroadcasts.size();
7825                for (i=0; i<N; i++) {
7826                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7827                }
7828            }
7829
7830            pkgSetting.setTimeStamp(scanFileTime);
7831
7832            // Create idmap files for pairs of (packages, overlay packages).
7833            // Note: "android", ie framework-res.apk, is handled by native layers.
7834            if (pkg.mOverlayTarget != null) {
7835                // This is an overlay package.
7836                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7837                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7838                        mOverlays.put(pkg.mOverlayTarget,
7839                                new ArrayMap<String, PackageParser.Package>());
7840                    }
7841                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7842                    map.put(pkg.packageName, pkg);
7843                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7844                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7845                        createIdmapFailed = true;
7846                    }
7847                }
7848            } else if (mOverlays.containsKey(pkg.packageName) &&
7849                    !pkg.packageName.equals("android")) {
7850                // This is a regular package, with one or more known overlay packages.
7851                createIdmapsForPackageLI(pkg);
7852            }
7853        }
7854
7855        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7856
7857        if (createIdmapFailed) {
7858            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7859                    "scanPackageLI failed to createIdmap");
7860        }
7861        return pkg;
7862    }
7863
7864    /**
7865     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7866     * is derived purely on the basis of the contents of {@code scanFile} and
7867     * {@code cpuAbiOverride}.
7868     *
7869     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7870     */
7871    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7872                                 String cpuAbiOverride, boolean extractLibs)
7873            throws PackageManagerException {
7874        // TODO: We can probably be smarter about this stuff. For installed apps,
7875        // we can calculate this information at install time once and for all. For
7876        // system apps, we can probably assume that this information doesn't change
7877        // after the first boot scan. As things stand, we do lots of unnecessary work.
7878
7879        // Give ourselves some initial paths; we'll come back for another
7880        // pass once we've determined ABI below.
7881        setNativeLibraryPaths(pkg);
7882
7883        // We would never need to extract libs for forward-locked and external packages,
7884        // since the container service will do it for us. We shouldn't attempt to
7885        // extract libs from system app when it was not updated.
7886        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7887                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7888            extractLibs = false;
7889        }
7890
7891        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7892        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7893
7894        NativeLibraryHelper.Handle handle = null;
7895        try {
7896            handle = NativeLibraryHelper.Handle.create(pkg);
7897            // TODO(multiArch): This can be null for apps that didn't go through the
7898            // usual installation process. We can calculate it again, like we
7899            // do during install time.
7900            //
7901            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7902            // unnecessary.
7903            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7904
7905            // Null out the abis so that they can be recalculated.
7906            pkg.applicationInfo.primaryCpuAbi = null;
7907            pkg.applicationInfo.secondaryCpuAbi = null;
7908            if (isMultiArch(pkg.applicationInfo)) {
7909                // Warn if we've set an abiOverride for multi-lib packages..
7910                // By definition, we need to copy both 32 and 64 bit libraries for
7911                // such packages.
7912                if (pkg.cpuAbiOverride != null
7913                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7914                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7915                }
7916
7917                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7918                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7919                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7920                    if (extractLibs) {
7921                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7922                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7923                                useIsaSpecificSubdirs);
7924                    } else {
7925                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7926                    }
7927                }
7928
7929                maybeThrowExceptionForMultiArchCopy(
7930                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7931
7932                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7933                    if (extractLibs) {
7934                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7935                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7936                                useIsaSpecificSubdirs);
7937                    } else {
7938                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7939                    }
7940                }
7941
7942                maybeThrowExceptionForMultiArchCopy(
7943                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7944
7945                if (abi64 >= 0) {
7946                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7947                }
7948
7949                if (abi32 >= 0) {
7950                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7951                    if (abi64 >= 0) {
7952                        pkg.applicationInfo.secondaryCpuAbi = abi;
7953                    } else {
7954                        pkg.applicationInfo.primaryCpuAbi = abi;
7955                    }
7956                }
7957            } else {
7958                String[] abiList = (cpuAbiOverride != null) ?
7959                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7960
7961                // Enable gross and lame hacks for apps that are built with old
7962                // SDK tools. We must scan their APKs for renderscript bitcode and
7963                // not launch them if it's present. Don't bother checking on devices
7964                // that don't have 64 bit support.
7965                boolean needsRenderScriptOverride = false;
7966                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7967                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7968                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7969                    needsRenderScriptOverride = true;
7970                }
7971
7972                final int copyRet;
7973                if (extractLibs) {
7974                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7975                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7976                } else {
7977                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7978                }
7979
7980                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7981                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7982                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7983                }
7984
7985                if (copyRet >= 0) {
7986                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7987                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7988                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7989                } else if (needsRenderScriptOverride) {
7990                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7991                }
7992            }
7993        } catch (IOException ioe) {
7994            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7995        } finally {
7996            IoUtils.closeQuietly(handle);
7997        }
7998
7999        // Now that we've calculated the ABIs and determined if it's an internal app,
8000        // we will go ahead and populate the nativeLibraryPath.
8001        setNativeLibraryPaths(pkg);
8002    }
8003
8004    /**
8005     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8006     * i.e, so that all packages can be run inside a single process if required.
8007     *
8008     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8009     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8010     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8011     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8012     * updating a package that belongs to a shared user.
8013     *
8014     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8015     * adds unnecessary complexity.
8016     */
8017    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8018            PackageParser.Package scannedPackage, boolean bootComplete) {
8019        String requiredInstructionSet = null;
8020        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8021            requiredInstructionSet = VMRuntime.getInstructionSet(
8022                     scannedPackage.applicationInfo.primaryCpuAbi);
8023        }
8024
8025        PackageSetting requirer = null;
8026        for (PackageSetting ps : packagesForUser) {
8027            // If packagesForUser contains scannedPackage, we skip it. This will happen
8028            // when scannedPackage is an update of an existing package. Without this check,
8029            // we will never be able to change the ABI of any package belonging to a shared
8030            // user, even if it's compatible with other packages.
8031            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8032                if (ps.primaryCpuAbiString == null) {
8033                    continue;
8034                }
8035
8036                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8037                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8038                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8039                    // this but there's not much we can do.
8040                    String errorMessage = "Instruction set mismatch, "
8041                            + ((requirer == null) ? "[caller]" : requirer)
8042                            + " requires " + requiredInstructionSet + " whereas " + ps
8043                            + " requires " + instructionSet;
8044                    Slog.w(TAG, errorMessage);
8045                }
8046
8047                if (requiredInstructionSet == null) {
8048                    requiredInstructionSet = instructionSet;
8049                    requirer = ps;
8050                }
8051            }
8052        }
8053
8054        if (requiredInstructionSet != null) {
8055            String adjustedAbi;
8056            if (requirer != null) {
8057                // requirer != null implies that either scannedPackage was null or that scannedPackage
8058                // did not require an ABI, in which case we have to adjust scannedPackage to match
8059                // the ABI of the set (which is the same as requirer's ABI)
8060                adjustedAbi = requirer.primaryCpuAbiString;
8061                if (scannedPackage != null) {
8062                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8063                }
8064            } else {
8065                // requirer == null implies that we're updating all ABIs in the set to
8066                // match scannedPackage.
8067                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8068            }
8069
8070            for (PackageSetting ps : packagesForUser) {
8071                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8072                    if (ps.primaryCpuAbiString != null) {
8073                        continue;
8074                    }
8075
8076                    ps.primaryCpuAbiString = adjustedAbi;
8077                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8078                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8079                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8080                        try {
8081                            mInstaller.rmdex(ps.codePathString,
8082                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8083                        } catch (InstallerException ignored) {
8084                        }
8085                    }
8086                }
8087            }
8088        }
8089    }
8090
8091    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8092        synchronized (mPackages) {
8093            mResolverReplaced = true;
8094            // Set up information for custom user intent resolution activity.
8095            mResolveActivity.applicationInfo = pkg.applicationInfo;
8096            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8097            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8098            mResolveActivity.processName = pkg.applicationInfo.packageName;
8099            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8100            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8101                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8102            mResolveActivity.theme = 0;
8103            mResolveActivity.exported = true;
8104            mResolveActivity.enabled = true;
8105            mResolveInfo.activityInfo = mResolveActivity;
8106            mResolveInfo.priority = 0;
8107            mResolveInfo.preferredOrder = 0;
8108            mResolveInfo.match = 0;
8109            mResolveComponentName = mCustomResolverComponentName;
8110            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8111                    mResolveComponentName);
8112        }
8113    }
8114
8115    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8116        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8117
8118        // Set up information for ephemeral installer activity
8119        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8120        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8121        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8122        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8123        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8124        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8125                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8126        mEphemeralInstallerActivity.theme = 0;
8127        mEphemeralInstallerActivity.exported = true;
8128        mEphemeralInstallerActivity.enabled = true;
8129        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8130        mEphemeralInstallerInfo.priority = 0;
8131        mEphemeralInstallerInfo.preferredOrder = 0;
8132        mEphemeralInstallerInfo.match = 0;
8133
8134        if (DEBUG_EPHEMERAL) {
8135            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8136        }
8137    }
8138
8139    private static String calculateBundledApkRoot(final String codePathString) {
8140        final File codePath = new File(codePathString);
8141        final File codeRoot;
8142        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8143            codeRoot = Environment.getRootDirectory();
8144        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8145            codeRoot = Environment.getOemDirectory();
8146        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8147            codeRoot = Environment.getVendorDirectory();
8148        } else {
8149            // Unrecognized code path; take its top real segment as the apk root:
8150            // e.g. /something/app/blah.apk => /something
8151            try {
8152                File f = codePath.getCanonicalFile();
8153                File parent = f.getParentFile();    // non-null because codePath is a file
8154                File tmp;
8155                while ((tmp = parent.getParentFile()) != null) {
8156                    f = parent;
8157                    parent = tmp;
8158                }
8159                codeRoot = f;
8160                Slog.w(TAG, "Unrecognized code path "
8161                        + codePath + " - using " + codeRoot);
8162            } catch (IOException e) {
8163                // Can't canonicalize the code path -- shenanigans?
8164                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8165                return Environment.getRootDirectory().getPath();
8166            }
8167        }
8168        return codeRoot.getPath();
8169    }
8170
8171    /**
8172     * Derive and set the location of native libraries for the given package,
8173     * which varies depending on where and how the package was installed.
8174     */
8175    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8176        final ApplicationInfo info = pkg.applicationInfo;
8177        final String codePath = pkg.codePath;
8178        final File codeFile = new File(codePath);
8179        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8180        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8181
8182        info.nativeLibraryRootDir = null;
8183        info.nativeLibraryRootRequiresIsa = false;
8184        info.nativeLibraryDir = null;
8185        info.secondaryNativeLibraryDir = null;
8186
8187        if (isApkFile(codeFile)) {
8188            // Monolithic install
8189            if (bundledApp) {
8190                // If "/system/lib64/apkname" exists, assume that is the per-package
8191                // native library directory to use; otherwise use "/system/lib/apkname".
8192                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8193                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8194                        getPrimaryInstructionSet(info));
8195
8196                // This is a bundled system app so choose the path based on the ABI.
8197                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8198                // is just the default path.
8199                final String apkName = deriveCodePathName(codePath);
8200                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8201                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8202                        apkName).getAbsolutePath();
8203
8204                if (info.secondaryCpuAbi != null) {
8205                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8206                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8207                            secondaryLibDir, apkName).getAbsolutePath();
8208                }
8209            } else if (asecApp) {
8210                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8211                        .getAbsolutePath();
8212            } else {
8213                final String apkName = deriveCodePathName(codePath);
8214                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8215                        .getAbsolutePath();
8216            }
8217
8218            info.nativeLibraryRootRequiresIsa = false;
8219            info.nativeLibraryDir = info.nativeLibraryRootDir;
8220        } else {
8221            // Cluster install
8222            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8223            info.nativeLibraryRootRequiresIsa = true;
8224
8225            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8226                    getPrimaryInstructionSet(info)).getAbsolutePath();
8227
8228            if (info.secondaryCpuAbi != null) {
8229                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8230                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8231            }
8232        }
8233    }
8234
8235    /**
8236     * Calculate the abis and roots for a bundled app. These can uniquely
8237     * be determined from the contents of the system partition, i.e whether
8238     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8239     * of this information, and instead assume that the system was built
8240     * sensibly.
8241     */
8242    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8243                                           PackageSetting pkgSetting) {
8244        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8245
8246        // If "/system/lib64/apkname" exists, assume that is the per-package
8247        // native library directory to use; otherwise use "/system/lib/apkname".
8248        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8249        setBundledAppAbi(pkg, apkRoot, apkName);
8250        // pkgSetting might be null during rescan following uninstall of updates
8251        // to a bundled app, so accommodate that possibility.  The settings in
8252        // that case will be established later from the parsed package.
8253        //
8254        // If the settings aren't null, sync them up with what we've just derived.
8255        // note that apkRoot isn't stored in the package settings.
8256        if (pkgSetting != null) {
8257            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8258            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8259        }
8260    }
8261
8262    /**
8263     * Deduces the ABI of a bundled app and sets the relevant fields on the
8264     * parsed pkg object.
8265     *
8266     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8267     *        under which system libraries are installed.
8268     * @param apkName the name of the installed package.
8269     */
8270    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8271        final File codeFile = new File(pkg.codePath);
8272
8273        final boolean has64BitLibs;
8274        final boolean has32BitLibs;
8275        if (isApkFile(codeFile)) {
8276            // Monolithic install
8277            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8278            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8279        } else {
8280            // Cluster install
8281            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8282            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8283                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8284                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8285                has64BitLibs = (new File(rootDir, isa)).exists();
8286            } else {
8287                has64BitLibs = false;
8288            }
8289            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8290                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8291                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8292                has32BitLibs = (new File(rootDir, isa)).exists();
8293            } else {
8294                has32BitLibs = false;
8295            }
8296        }
8297
8298        if (has64BitLibs && !has32BitLibs) {
8299            // The package has 64 bit libs, but not 32 bit libs. Its primary
8300            // ABI should be 64 bit. We can safely assume here that the bundled
8301            // native libraries correspond to the most preferred ABI in the list.
8302
8303            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8304            pkg.applicationInfo.secondaryCpuAbi = null;
8305        } else if (has32BitLibs && !has64BitLibs) {
8306            // The package has 32 bit libs but not 64 bit libs. Its primary
8307            // ABI should be 32 bit.
8308
8309            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8310            pkg.applicationInfo.secondaryCpuAbi = null;
8311        } else if (has32BitLibs && has64BitLibs) {
8312            // The application has both 64 and 32 bit bundled libraries. We check
8313            // here that the app declares multiArch support, and warn if it doesn't.
8314            //
8315            // We will be lenient here and record both ABIs. The primary will be the
8316            // ABI that's higher on the list, i.e, a device that's configured to prefer
8317            // 64 bit apps will see a 64 bit primary ABI,
8318
8319            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8320                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8321            }
8322
8323            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8324                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8325                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8326            } else {
8327                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8328                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8329            }
8330        } else {
8331            pkg.applicationInfo.primaryCpuAbi = null;
8332            pkg.applicationInfo.secondaryCpuAbi = null;
8333        }
8334    }
8335
8336    private void killApplication(String pkgName, int appId, String reason) {
8337        // Request the ActivityManager to kill the process(only for existing packages)
8338        // so that we do not end up in a confused state while the user is still using the older
8339        // version of the application while the new one gets installed.
8340        IActivityManager am = ActivityManagerNative.getDefault();
8341        if (am != null) {
8342            try {
8343                am.killApplicationWithAppId(pkgName, appId, reason);
8344            } catch (RemoteException e) {
8345            }
8346        }
8347    }
8348
8349    void removePackageLI(PackageSetting ps, boolean chatty) {
8350        if (DEBUG_INSTALL) {
8351            if (chatty)
8352                Log.d(TAG, "Removing package " + ps.name);
8353        }
8354
8355        // writer
8356        synchronized (mPackages) {
8357            mPackages.remove(ps.name);
8358            final PackageParser.Package pkg = ps.pkg;
8359            if (pkg != null) {
8360                cleanPackageDataStructuresLILPw(pkg, chatty);
8361            }
8362        }
8363    }
8364
8365    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8366        if (DEBUG_INSTALL) {
8367            if (chatty)
8368                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8369        }
8370
8371        // writer
8372        synchronized (mPackages) {
8373            mPackages.remove(pkg.applicationInfo.packageName);
8374            cleanPackageDataStructuresLILPw(pkg, chatty);
8375        }
8376    }
8377
8378    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8379        int N = pkg.providers.size();
8380        StringBuilder r = null;
8381        int i;
8382        for (i=0; i<N; i++) {
8383            PackageParser.Provider p = pkg.providers.get(i);
8384            mProviders.removeProvider(p);
8385            if (p.info.authority == null) {
8386
8387                /* There was another ContentProvider with this authority when
8388                 * this app was installed so this authority is null,
8389                 * Ignore it as we don't have to unregister the provider.
8390                 */
8391                continue;
8392            }
8393            String names[] = p.info.authority.split(";");
8394            for (int j = 0; j < names.length; j++) {
8395                if (mProvidersByAuthority.get(names[j]) == p) {
8396                    mProvidersByAuthority.remove(names[j]);
8397                    if (DEBUG_REMOVE) {
8398                        if (chatty)
8399                            Log.d(TAG, "Unregistered content provider: " + names[j]
8400                                    + ", className = " + p.info.name + ", isSyncable = "
8401                                    + p.info.isSyncable);
8402                    }
8403                }
8404            }
8405            if (DEBUG_REMOVE && chatty) {
8406                if (r == null) {
8407                    r = new StringBuilder(256);
8408                } else {
8409                    r.append(' ');
8410                }
8411                r.append(p.info.name);
8412            }
8413        }
8414        if (r != null) {
8415            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8416        }
8417
8418        N = pkg.services.size();
8419        r = null;
8420        for (i=0; i<N; i++) {
8421            PackageParser.Service s = pkg.services.get(i);
8422            mServices.removeService(s);
8423            if (chatty) {
8424                if (r == null) {
8425                    r = new StringBuilder(256);
8426                } else {
8427                    r.append(' ');
8428                }
8429                r.append(s.info.name);
8430            }
8431        }
8432        if (r != null) {
8433            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8434        }
8435
8436        N = pkg.receivers.size();
8437        r = null;
8438        for (i=0; i<N; i++) {
8439            PackageParser.Activity a = pkg.receivers.get(i);
8440            mReceivers.removeActivity(a, "receiver");
8441            if (DEBUG_REMOVE && chatty) {
8442                if (r == null) {
8443                    r = new StringBuilder(256);
8444                } else {
8445                    r.append(' ');
8446                }
8447                r.append(a.info.name);
8448            }
8449        }
8450        if (r != null) {
8451            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8452        }
8453
8454        N = pkg.activities.size();
8455        r = null;
8456        for (i=0; i<N; i++) {
8457            PackageParser.Activity a = pkg.activities.get(i);
8458            mActivities.removeActivity(a, "activity");
8459            if (DEBUG_REMOVE && chatty) {
8460                if (r == null) {
8461                    r = new StringBuilder(256);
8462                } else {
8463                    r.append(' ');
8464                }
8465                r.append(a.info.name);
8466            }
8467        }
8468        if (r != null) {
8469            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8470        }
8471
8472        N = pkg.permissions.size();
8473        r = null;
8474        for (i=0; i<N; i++) {
8475            PackageParser.Permission p = pkg.permissions.get(i);
8476            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8477            if (bp == null) {
8478                bp = mSettings.mPermissionTrees.get(p.info.name);
8479            }
8480            if (bp != null && bp.perm == p) {
8481                bp.perm = null;
8482                if (DEBUG_REMOVE && chatty) {
8483                    if (r == null) {
8484                        r = new StringBuilder(256);
8485                    } else {
8486                        r.append(' ');
8487                    }
8488                    r.append(p.info.name);
8489                }
8490            }
8491            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8492                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8493                if (appOpPkgs != null) {
8494                    appOpPkgs.remove(pkg.packageName);
8495                }
8496            }
8497        }
8498        if (r != null) {
8499            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8500        }
8501
8502        N = pkg.requestedPermissions.size();
8503        r = null;
8504        for (i=0; i<N; i++) {
8505            String perm = pkg.requestedPermissions.get(i);
8506            BasePermission bp = mSettings.mPermissions.get(perm);
8507            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8508                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8509                if (appOpPkgs != null) {
8510                    appOpPkgs.remove(pkg.packageName);
8511                    if (appOpPkgs.isEmpty()) {
8512                        mAppOpPermissionPackages.remove(perm);
8513                    }
8514                }
8515            }
8516        }
8517        if (r != null) {
8518            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8519        }
8520
8521        N = pkg.instrumentation.size();
8522        r = null;
8523        for (i=0; i<N; i++) {
8524            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8525            mInstrumentation.remove(a.getComponentName());
8526            if (DEBUG_REMOVE && chatty) {
8527                if (r == null) {
8528                    r = new StringBuilder(256);
8529                } else {
8530                    r.append(' ');
8531                }
8532                r.append(a.info.name);
8533            }
8534        }
8535        if (r != null) {
8536            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8537        }
8538
8539        r = null;
8540        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8541            // Only system apps can hold shared libraries.
8542            if (pkg.libraryNames != null) {
8543                for (i=0; i<pkg.libraryNames.size(); i++) {
8544                    String name = pkg.libraryNames.get(i);
8545                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8546                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8547                        mSharedLibraries.remove(name);
8548                        if (DEBUG_REMOVE && chatty) {
8549                            if (r == null) {
8550                                r = new StringBuilder(256);
8551                            } else {
8552                                r.append(' ');
8553                            }
8554                            r.append(name);
8555                        }
8556                    }
8557                }
8558            }
8559        }
8560        if (r != null) {
8561            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8562        }
8563    }
8564
8565    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8566        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8567            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8568                return true;
8569            }
8570        }
8571        return false;
8572    }
8573
8574    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8575    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8576    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8577
8578    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8579            int flags) {
8580        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8581        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8582    }
8583
8584    private void updatePermissionsLPw(String changingPkg,
8585            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8586        // Make sure there are no dangling permission trees.
8587        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8588        while (it.hasNext()) {
8589            final BasePermission bp = it.next();
8590            if (bp.packageSetting == null) {
8591                // We may not yet have parsed the package, so just see if
8592                // we still know about its settings.
8593                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8594            }
8595            if (bp.packageSetting == null) {
8596                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8597                        + " from package " + bp.sourcePackage);
8598                it.remove();
8599            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8600                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8601                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8602                            + " from package " + bp.sourcePackage);
8603                    flags |= UPDATE_PERMISSIONS_ALL;
8604                    it.remove();
8605                }
8606            }
8607        }
8608
8609        // Make sure all dynamic permissions have been assigned to a package,
8610        // and make sure there are no dangling permissions.
8611        it = mSettings.mPermissions.values().iterator();
8612        while (it.hasNext()) {
8613            final BasePermission bp = it.next();
8614            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8615                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8616                        + bp.name + " pkg=" + bp.sourcePackage
8617                        + " info=" + bp.pendingInfo);
8618                if (bp.packageSetting == null && bp.pendingInfo != null) {
8619                    final BasePermission tree = findPermissionTreeLP(bp.name);
8620                    if (tree != null && tree.perm != null) {
8621                        bp.packageSetting = tree.packageSetting;
8622                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8623                                new PermissionInfo(bp.pendingInfo));
8624                        bp.perm.info.packageName = tree.perm.info.packageName;
8625                        bp.perm.info.name = bp.name;
8626                        bp.uid = tree.uid;
8627                    }
8628                }
8629            }
8630            if (bp.packageSetting == null) {
8631                // We may not yet have parsed the package, so just see if
8632                // we still know about its settings.
8633                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8634            }
8635            if (bp.packageSetting == null) {
8636                Slog.w(TAG, "Removing dangling permission: " + bp.name
8637                        + " from package " + bp.sourcePackage);
8638                it.remove();
8639            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8640                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8641                    Slog.i(TAG, "Removing old permission: " + bp.name
8642                            + " from package " + bp.sourcePackage);
8643                    flags |= UPDATE_PERMISSIONS_ALL;
8644                    it.remove();
8645                }
8646            }
8647        }
8648
8649        // Now update the permissions for all packages, in particular
8650        // replace the granted permissions of the system packages.
8651        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8652            for (PackageParser.Package pkg : mPackages.values()) {
8653                if (pkg != pkgInfo) {
8654                    // Only replace for packages on requested volume
8655                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8656                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8657                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8658                    grantPermissionsLPw(pkg, replace, changingPkg);
8659                }
8660            }
8661        }
8662
8663        if (pkgInfo != null) {
8664            // Only replace for packages on requested volume
8665            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8666            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8667                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8668            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8669        }
8670    }
8671
8672    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8673            String packageOfInterest) {
8674        // IMPORTANT: There are two types of permissions: install and runtime.
8675        // Install time permissions are granted when the app is installed to
8676        // all device users and users added in the future. Runtime permissions
8677        // are granted at runtime explicitly to specific users. Normal and signature
8678        // protected permissions are install time permissions. Dangerous permissions
8679        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8680        // otherwise they are runtime permissions. This function does not manage
8681        // runtime permissions except for the case an app targeting Lollipop MR1
8682        // being upgraded to target a newer SDK, in which case dangerous permissions
8683        // are transformed from install time to runtime ones.
8684
8685        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8686        if (ps == null) {
8687            return;
8688        }
8689
8690        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8691
8692        PermissionsState permissionsState = ps.getPermissionsState();
8693        PermissionsState origPermissions = permissionsState;
8694
8695        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8696
8697        boolean runtimePermissionsRevoked = false;
8698        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8699
8700        boolean changedInstallPermission = false;
8701
8702        if (replace) {
8703            ps.installPermissionsFixed = false;
8704            if (!ps.isSharedUser()) {
8705                origPermissions = new PermissionsState(permissionsState);
8706                permissionsState.reset();
8707            } else {
8708                // We need to know only about runtime permission changes since the
8709                // calling code always writes the install permissions state but
8710                // the runtime ones are written only if changed. The only cases of
8711                // changed runtime permissions here are promotion of an install to
8712                // runtime and revocation of a runtime from a shared user.
8713                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8714                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8715                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8716                    runtimePermissionsRevoked = true;
8717                }
8718            }
8719        }
8720
8721        permissionsState.setGlobalGids(mGlobalGids);
8722
8723        final int N = pkg.requestedPermissions.size();
8724        for (int i=0; i<N; i++) {
8725            final String name = pkg.requestedPermissions.get(i);
8726            final BasePermission bp = mSettings.mPermissions.get(name);
8727
8728            if (DEBUG_INSTALL) {
8729                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8730            }
8731
8732            if (bp == null || bp.packageSetting == null) {
8733                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8734                    Slog.w(TAG, "Unknown permission " + name
8735                            + " in package " + pkg.packageName);
8736                }
8737                continue;
8738            }
8739
8740            final String perm = bp.name;
8741            boolean allowedSig = false;
8742            int grant = GRANT_DENIED;
8743
8744            // Keep track of app op permissions.
8745            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8746                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8747                if (pkgs == null) {
8748                    pkgs = new ArraySet<>();
8749                    mAppOpPermissionPackages.put(bp.name, pkgs);
8750                }
8751                pkgs.add(pkg.packageName);
8752            }
8753
8754            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8755            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8756                    >= Build.VERSION_CODES.M;
8757            switch (level) {
8758                case PermissionInfo.PROTECTION_NORMAL: {
8759                    // For all apps normal permissions are install time ones.
8760                    grant = GRANT_INSTALL;
8761                } break;
8762
8763                case PermissionInfo.PROTECTION_DANGEROUS: {
8764                    // If a permission review is required for legacy apps we represent
8765                    // their permissions as always granted runtime ones since we need
8766                    // to keep the review required permission flag per user while an
8767                    // install permission's state is shared across all users.
8768                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8769                        // For legacy apps dangerous permissions are install time ones.
8770                        grant = GRANT_INSTALL;
8771                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8772                        // For legacy apps that became modern, install becomes runtime.
8773                        grant = GRANT_UPGRADE;
8774                    } else if (mPromoteSystemApps
8775                            && isSystemApp(ps)
8776                            && mExistingSystemPackages.contains(ps.name)) {
8777                        // For legacy system apps, install becomes runtime.
8778                        // We cannot check hasInstallPermission() for system apps since those
8779                        // permissions were granted implicitly and not persisted pre-M.
8780                        grant = GRANT_UPGRADE;
8781                    } else {
8782                        // For modern apps keep runtime permissions unchanged.
8783                        grant = GRANT_RUNTIME;
8784                    }
8785                } break;
8786
8787                case PermissionInfo.PROTECTION_SIGNATURE: {
8788                    // For all apps signature permissions are install time ones.
8789                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8790                    if (allowedSig) {
8791                        grant = GRANT_INSTALL;
8792                    }
8793                } break;
8794            }
8795
8796            if (DEBUG_INSTALL) {
8797                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8798            }
8799
8800            if (grant != GRANT_DENIED) {
8801                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8802                    // If this is an existing, non-system package, then
8803                    // we can't add any new permissions to it.
8804                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8805                        // Except...  if this is a permission that was added
8806                        // to the platform (note: need to only do this when
8807                        // updating the platform).
8808                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8809                            grant = GRANT_DENIED;
8810                        }
8811                    }
8812                }
8813
8814                switch (grant) {
8815                    case GRANT_INSTALL: {
8816                        // Revoke this as runtime permission to handle the case of
8817                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8818                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8819                            if (origPermissions.getRuntimePermissionState(
8820                                    bp.name, userId) != null) {
8821                                // Revoke the runtime permission and clear the flags.
8822                                origPermissions.revokeRuntimePermission(bp, userId);
8823                                origPermissions.updatePermissionFlags(bp, userId,
8824                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8825                                // If we revoked a permission permission, we have to write.
8826                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8827                                        changedRuntimePermissionUserIds, userId);
8828                            }
8829                        }
8830                        // Grant an install permission.
8831                        if (permissionsState.grantInstallPermission(bp) !=
8832                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8833                            changedInstallPermission = true;
8834                        }
8835                    } break;
8836
8837                    case GRANT_RUNTIME: {
8838                        // Grant previously granted runtime permissions.
8839                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8840                            PermissionState permissionState = origPermissions
8841                                    .getRuntimePermissionState(bp.name, userId);
8842                            int flags = permissionState != null
8843                                    ? permissionState.getFlags() : 0;
8844                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8845                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8846                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8847                                    // If we cannot put the permission as it was, we have to write.
8848                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8849                                            changedRuntimePermissionUserIds, userId);
8850                                }
8851                                // If the app supports runtime permissions no need for a review.
8852                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8853                                        && appSupportsRuntimePermissions
8854                                        && (flags & PackageManager
8855                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8856                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8857                                    // Since we changed the flags, we have to write.
8858                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8859                                            changedRuntimePermissionUserIds, userId);
8860                                }
8861                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8862                                    && !appSupportsRuntimePermissions) {
8863                                // For legacy apps that need a permission review, every new
8864                                // runtime permission is granted but it is pending a review.
8865                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8866                                    permissionsState.grantRuntimePermission(bp, userId);
8867                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8868                                    // We changed the permission and flags, hence have to write.
8869                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8870                                            changedRuntimePermissionUserIds, userId);
8871                                }
8872                            }
8873                            // Propagate the permission flags.
8874                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8875                        }
8876                    } break;
8877
8878                    case GRANT_UPGRADE: {
8879                        // Grant runtime permissions for a previously held install permission.
8880                        PermissionState permissionState = origPermissions
8881                                .getInstallPermissionState(bp.name);
8882                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8883
8884                        if (origPermissions.revokeInstallPermission(bp)
8885                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8886                            // We will be transferring the permission flags, so clear them.
8887                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8888                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8889                            changedInstallPermission = true;
8890                        }
8891
8892                        // If the permission is not to be promoted to runtime we ignore it and
8893                        // also its other flags as they are not applicable to install permissions.
8894                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8895                            for (int userId : currentUserIds) {
8896                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8897                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8898                                    // Transfer the permission flags.
8899                                    permissionsState.updatePermissionFlags(bp, userId,
8900                                            flags, flags);
8901                                    // If we granted the permission, we have to write.
8902                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8903                                            changedRuntimePermissionUserIds, userId);
8904                                }
8905                            }
8906                        }
8907                    } break;
8908
8909                    default: {
8910                        if (packageOfInterest == null
8911                                || packageOfInterest.equals(pkg.packageName)) {
8912                            Slog.w(TAG, "Not granting permission " + perm
8913                                    + " to package " + pkg.packageName
8914                                    + " because it was previously installed without");
8915                        }
8916                    } break;
8917                }
8918            } else {
8919                if (permissionsState.revokeInstallPermission(bp) !=
8920                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8921                    // Also drop the permission flags.
8922                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8923                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8924                    changedInstallPermission = true;
8925                    Slog.i(TAG, "Un-granting permission " + perm
8926                            + " from package " + pkg.packageName
8927                            + " (protectionLevel=" + bp.protectionLevel
8928                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8929                            + ")");
8930                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8931                    // Don't print warning for app op permissions, since it is fine for them
8932                    // not to be granted, there is a UI for the user to decide.
8933                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8934                        Slog.w(TAG, "Not granting permission " + perm
8935                                + " to package " + pkg.packageName
8936                                + " (protectionLevel=" + bp.protectionLevel
8937                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8938                                + ")");
8939                    }
8940                }
8941            }
8942        }
8943
8944        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8945                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8946            // This is the first that we have heard about this package, so the
8947            // permissions we have now selected are fixed until explicitly
8948            // changed.
8949            ps.installPermissionsFixed = true;
8950        }
8951
8952        // Persist the runtime permissions state for users with changes. If permissions
8953        // were revoked because no app in the shared user declares them we have to
8954        // write synchronously to avoid losing runtime permissions state.
8955        for (int userId : changedRuntimePermissionUserIds) {
8956            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8957        }
8958
8959        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8960    }
8961
8962    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8963        boolean allowed = false;
8964        final int NP = PackageParser.NEW_PERMISSIONS.length;
8965        for (int ip=0; ip<NP; ip++) {
8966            final PackageParser.NewPermissionInfo npi
8967                    = PackageParser.NEW_PERMISSIONS[ip];
8968            if (npi.name.equals(perm)
8969                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8970                allowed = true;
8971                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8972                        + pkg.packageName);
8973                break;
8974            }
8975        }
8976        return allowed;
8977    }
8978
8979    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8980            BasePermission bp, PermissionsState origPermissions) {
8981        boolean allowed;
8982        allowed = (compareSignatures(
8983                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8984                        == PackageManager.SIGNATURE_MATCH)
8985                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8986                        == PackageManager.SIGNATURE_MATCH);
8987        if (!allowed && (bp.protectionLevel
8988                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8989            if (isSystemApp(pkg)) {
8990                // For updated system applications, a system permission
8991                // is granted only if it had been defined by the original application.
8992                if (pkg.isUpdatedSystemApp()) {
8993                    final PackageSetting sysPs = mSettings
8994                            .getDisabledSystemPkgLPr(pkg.packageName);
8995                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8996                        // If the original was granted this permission, we take
8997                        // that grant decision as read and propagate it to the
8998                        // update.
8999                        if (sysPs.isPrivileged()) {
9000                            allowed = true;
9001                        }
9002                    } else {
9003                        // The system apk may have been updated with an older
9004                        // version of the one on the data partition, but which
9005                        // granted a new system permission that it didn't have
9006                        // before.  In this case we do want to allow the app to
9007                        // now get the new permission if the ancestral apk is
9008                        // privileged to get it.
9009                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9010                            for (int j=0;
9011                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9012                                if (perm.equals(
9013                                        sysPs.pkg.requestedPermissions.get(j))) {
9014                                    allowed = true;
9015                                    break;
9016                                }
9017                            }
9018                        }
9019                    }
9020                } else {
9021                    allowed = isPrivilegedApp(pkg);
9022                }
9023            }
9024        }
9025        if (!allowed) {
9026            if (!allowed && (bp.protectionLevel
9027                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9028                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9029                // If this was a previously normal/dangerous permission that got moved
9030                // to a system permission as part of the runtime permission redesign, then
9031                // we still want to blindly grant it to old apps.
9032                allowed = true;
9033            }
9034            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9035                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9036                // If this permission is to be granted to the system installer and
9037                // this app is an installer, then it gets the permission.
9038                allowed = true;
9039            }
9040            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9041                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9042                // If this permission is to be granted to the system verifier and
9043                // this app is a verifier, then it gets the permission.
9044                allowed = true;
9045            }
9046            if (!allowed && (bp.protectionLevel
9047                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9048                    && isSystemApp(pkg)) {
9049                // Any pre-installed system app is allowed to get this permission.
9050                allowed = true;
9051            }
9052            if (!allowed && (bp.protectionLevel
9053                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9054                // For development permissions, a development permission
9055                // is granted only if it was already granted.
9056                allowed = origPermissions.hasInstallPermission(perm);
9057            }
9058        }
9059        return allowed;
9060    }
9061
9062    final class ActivityIntentResolver
9063            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9064        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9065                boolean defaultOnly, int userId) {
9066            if (!sUserManager.exists(userId)) return null;
9067            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9068            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9069        }
9070
9071        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9072                int userId) {
9073            if (!sUserManager.exists(userId)) return null;
9074            mFlags = flags;
9075            return super.queryIntent(intent, resolvedType,
9076                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9077        }
9078
9079        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9080                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9081            if (!sUserManager.exists(userId)) return null;
9082            if (packageActivities == null) {
9083                return null;
9084            }
9085            mFlags = flags;
9086            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9087            final int N = packageActivities.size();
9088            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9089                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9090
9091            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9092            for (int i = 0; i < N; ++i) {
9093                intentFilters = packageActivities.get(i).intents;
9094                if (intentFilters != null && intentFilters.size() > 0) {
9095                    PackageParser.ActivityIntentInfo[] array =
9096                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9097                    intentFilters.toArray(array);
9098                    listCut.add(array);
9099                }
9100            }
9101            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9102        }
9103
9104        public final void addActivity(PackageParser.Activity a, String type) {
9105            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9106            mActivities.put(a.getComponentName(), a);
9107            if (DEBUG_SHOW_INFO)
9108                Log.v(
9109                TAG, "  " + type + " " +
9110                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9111            if (DEBUG_SHOW_INFO)
9112                Log.v(TAG, "    Class=" + a.info.name);
9113            final int NI = a.intents.size();
9114            for (int j=0; j<NI; j++) {
9115                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9116                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9117                    intent.setPriority(0);
9118                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9119                            + a.className + " with priority > 0, forcing to 0");
9120                }
9121                if (DEBUG_SHOW_INFO) {
9122                    Log.v(TAG, "    IntentFilter:");
9123                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9124                }
9125                if (!intent.debugCheck()) {
9126                    Log.w(TAG, "==> For Activity " + a.info.name);
9127                }
9128                addFilter(intent);
9129            }
9130        }
9131
9132        public final void removeActivity(PackageParser.Activity a, String type) {
9133            mActivities.remove(a.getComponentName());
9134            if (DEBUG_SHOW_INFO) {
9135                Log.v(TAG, "  " + type + " "
9136                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9137                                : a.info.name) + ":");
9138                Log.v(TAG, "    Class=" + a.info.name);
9139            }
9140            final int NI = a.intents.size();
9141            for (int j=0; j<NI; j++) {
9142                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9143                if (DEBUG_SHOW_INFO) {
9144                    Log.v(TAG, "    IntentFilter:");
9145                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9146                }
9147                removeFilter(intent);
9148            }
9149        }
9150
9151        @Override
9152        protected boolean allowFilterResult(
9153                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9154            ActivityInfo filterAi = filter.activity.info;
9155            for (int i=dest.size()-1; i>=0; i--) {
9156                ActivityInfo destAi = dest.get(i).activityInfo;
9157                if (destAi.name == filterAi.name
9158                        && destAi.packageName == filterAi.packageName) {
9159                    return false;
9160                }
9161            }
9162            return true;
9163        }
9164
9165        @Override
9166        protected ActivityIntentInfo[] newArray(int size) {
9167            return new ActivityIntentInfo[size];
9168        }
9169
9170        @Override
9171        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9172            if (!sUserManager.exists(userId)) return true;
9173            PackageParser.Package p = filter.activity.owner;
9174            if (p != null) {
9175                PackageSetting ps = (PackageSetting)p.mExtras;
9176                if (ps != null) {
9177                    // System apps are never considered stopped for purposes of
9178                    // filtering, because there may be no way for the user to
9179                    // actually re-launch them.
9180                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9181                            && ps.getStopped(userId);
9182                }
9183            }
9184            return false;
9185        }
9186
9187        @Override
9188        protected boolean isPackageForFilter(String packageName,
9189                PackageParser.ActivityIntentInfo info) {
9190            return packageName.equals(info.activity.owner.packageName);
9191        }
9192
9193        @Override
9194        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9195                int match, int userId) {
9196            if (!sUserManager.exists(userId)) return null;
9197            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9198                return null;
9199            }
9200            final PackageParser.Activity activity = info.activity;
9201            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9202            if (ps == null) {
9203                return null;
9204            }
9205            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9206                    ps.readUserState(userId), userId);
9207            if (ai == null) {
9208                return null;
9209            }
9210            final ResolveInfo res = new ResolveInfo();
9211            res.activityInfo = ai;
9212            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9213                res.filter = info;
9214            }
9215            if (info != null) {
9216                res.handleAllWebDataURI = info.handleAllWebDataURI();
9217            }
9218            res.priority = info.getPriority();
9219            res.preferredOrder = activity.owner.mPreferredOrder;
9220            //System.out.println("Result: " + res.activityInfo.className +
9221            //                   " = " + res.priority);
9222            res.match = match;
9223            res.isDefault = info.hasDefault;
9224            res.labelRes = info.labelRes;
9225            res.nonLocalizedLabel = info.nonLocalizedLabel;
9226            if (userNeedsBadging(userId)) {
9227                res.noResourceId = true;
9228            } else {
9229                res.icon = info.icon;
9230            }
9231            res.iconResourceId = info.icon;
9232            res.system = res.activityInfo.applicationInfo.isSystemApp();
9233            return res;
9234        }
9235
9236        @Override
9237        protected void sortResults(List<ResolveInfo> results) {
9238            Collections.sort(results, mResolvePrioritySorter);
9239        }
9240
9241        @Override
9242        protected void dumpFilter(PrintWriter out, String prefix,
9243                PackageParser.ActivityIntentInfo filter) {
9244            out.print(prefix); out.print(
9245                    Integer.toHexString(System.identityHashCode(filter.activity)));
9246                    out.print(' ');
9247                    filter.activity.printComponentShortName(out);
9248                    out.print(" filter ");
9249                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9250        }
9251
9252        @Override
9253        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9254            return filter.activity;
9255        }
9256
9257        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9258            PackageParser.Activity activity = (PackageParser.Activity)label;
9259            out.print(prefix); out.print(
9260                    Integer.toHexString(System.identityHashCode(activity)));
9261                    out.print(' ');
9262                    activity.printComponentShortName(out);
9263            if (count > 1) {
9264                out.print(" ("); out.print(count); out.print(" filters)");
9265            }
9266            out.println();
9267        }
9268
9269//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9270//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9271//            final List<ResolveInfo> retList = Lists.newArrayList();
9272//            while (i.hasNext()) {
9273//                final ResolveInfo resolveInfo = i.next();
9274//                if (isEnabledLP(resolveInfo.activityInfo)) {
9275//                    retList.add(resolveInfo);
9276//                }
9277//            }
9278//            return retList;
9279//        }
9280
9281        // Keys are String (activity class name), values are Activity.
9282        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9283                = new ArrayMap<ComponentName, PackageParser.Activity>();
9284        private int mFlags;
9285    }
9286
9287    private final class ServiceIntentResolver
9288            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9289        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9290                boolean defaultOnly, int userId) {
9291            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9292            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9293        }
9294
9295        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9296                int userId) {
9297            if (!sUserManager.exists(userId)) return null;
9298            mFlags = flags;
9299            return super.queryIntent(intent, resolvedType,
9300                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9301        }
9302
9303        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9304                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9305            if (!sUserManager.exists(userId)) return null;
9306            if (packageServices == null) {
9307                return null;
9308            }
9309            mFlags = flags;
9310            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9311            final int N = packageServices.size();
9312            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9313                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9314
9315            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9316            for (int i = 0; i < N; ++i) {
9317                intentFilters = packageServices.get(i).intents;
9318                if (intentFilters != null && intentFilters.size() > 0) {
9319                    PackageParser.ServiceIntentInfo[] array =
9320                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9321                    intentFilters.toArray(array);
9322                    listCut.add(array);
9323                }
9324            }
9325            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9326        }
9327
9328        public final void addService(PackageParser.Service s) {
9329            mServices.put(s.getComponentName(), s);
9330            if (DEBUG_SHOW_INFO) {
9331                Log.v(TAG, "  "
9332                        + (s.info.nonLocalizedLabel != null
9333                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9334                Log.v(TAG, "    Class=" + s.info.name);
9335            }
9336            final int NI = s.intents.size();
9337            int j;
9338            for (j=0; j<NI; j++) {
9339                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9340                if (DEBUG_SHOW_INFO) {
9341                    Log.v(TAG, "    IntentFilter:");
9342                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9343                }
9344                if (!intent.debugCheck()) {
9345                    Log.w(TAG, "==> For Service " + s.info.name);
9346                }
9347                addFilter(intent);
9348            }
9349        }
9350
9351        public final void removeService(PackageParser.Service s) {
9352            mServices.remove(s.getComponentName());
9353            if (DEBUG_SHOW_INFO) {
9354                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9355                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9356                Log.v(TAG, "    Class=" + s.info.name);
9357            }
9358            final int NI = s.intents.size();
9359            int j;
9360            for (j=0; j<NI; j++) {
9361                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9362                if (DEBUG_SHOW_INFO) {
9363                    Log.v(TAG, "    IntentFilter:");
9364                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9365                }
9366                removeFilter(intent);
9367            }
9368        }
9369
9370        @Override
9371        protected boolean allowFilterResult(
9372                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9373            ServiceInfo filterSi = filter.service.info;
9374            for (int i=dest.size()-1; i>=0; i--) {
9375                ServiceInfo destAi = dest.get(i).serviceInfo;
9376                if (destAi.name == filterSi.name
9377                        && destAi.packageName == filterSi.packageName) {
9378                    return false;
9379                }
9380            }
9381            return true;
9382        }
9383
9384        @Override
9385        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9386            return new PackageParser.ServiceIntentInfo[size];
9387        }
9388
9389        @Override
9390        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9391            if (!sUserManager.exists(userId)) return true;
9392            PackageParser.Package p = filter.service.owner;
9393            if (p != null) {
9394                PackageSetting ps = (PackageSetting)p.mExtras;
9395                if (ps != null) {
9396                    // System apps are never considered stopped for purposes of
9397                    // filtering, because there may be no way for the user to
9398                    // actually re-launch them.
9399                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9400                            && ps.getStopped(userId);
9401                }
9402            }
9403            return false;
9404        }
9405
9406        @Override
9407        protected boolean isPackageForFilter(String packageName,
9408                PackageParser.ServiceIntentInfo info) {
9409            return packageName.equals(info.service.owner.packageName);
9410        }
9411
9412        @Override
9413        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9414                int match, int userId) {
9415            if (!sUserManager.exists(userId)) return null;
9416            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9417            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9418                return null;
9419            }
9420            final PackageParser.Service service = info.service;
9421            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9422            if (ps == null) {
9423                return null;
9424            }
9425            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9426                    ps.readUserState(userId), userId);
9427            if (si == null) {
9428                return null;
9429            }
9430            final ResolveInfo res = new ResolveInfo();
9431            res.serviceInfo = si;
9432            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9433                res.filter = filter;
9434            }
9435            res.priority = info.getPriority();
9436            res.preferredOrder = service.owner.mPreferredOrder;
9437            res.match = match;
9438            res.isDefault = info.hasDefault;
9439            res.labelRes = info.labelRes;
9440            res.nonLocalizedLabel = info.nonLocalizedLabel;
9441            res.icon = info.icon;
9442            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9443            return res;
9444        }
9445
9446        @Override
9447        protected void sortResults(List<ResolveInfo> results) {
9448            Collections.sort(results, mResolvePrioritySorter);
9449        }
9450
9451        @Override
9452        protected void dumpFilter(PrintWriter out, String prefix,
9453                PackageParser.ServiceIntentInfo filter) {
9454            out.print(prefix); out.print(
9455                    Integer.toHexString(System.identityHashCode(filter.service)));
9456                    out.print(' ');
9457                    filter.service.printComponentShortName(out);
9458                    out.print(" filter ");
9459                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9460        }
9461
9462        @Override
9463        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9464            return filter.service;
9465        }
9466
9467        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9468            PackageParser.Service service = (PackageParser.Service)label;
9469            out.print(prefix); out.print(
9470                    Integer.toHexString(System.identityHashCode(service)));
9471                    out.print(' ');
9472                    service.printComponentShortName(out);
9473            if (count > 1) {
9474                out.print(" ("); out.print(count); out.print(" filters)");
9475            }
9476            out.println();
9477        }
9478
9479//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9480//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9481//            final List<ResolveInfo> retList = Lists.newArrayList();
9482//            while (i.hasNext()) {
9483//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9484//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9485//                    retList.add(resolveInfo);
9486//                }
9487//            }
9488//            return retList;
9489//        }
9490
9491        // Keys are String (activity class name), values are Activity.
9492        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9493                = new ArrayMap<ComponentName, PackageParser.Service>();
9494        private int mFlags;
9495    };
9496
9497    private final class ProviderIntentResolver
9498            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9499        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9500                boolean defaultOnly, int userId) {
9501            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9502            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9503        }
9504
9505        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9506                int userId) {
9507            if (!sUserManager.exists(userId))
9508                return null;
9509            mFlags = flags;
9510            return super.queryIntent(intent, resolvedType,
9511                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9512        }
9513
9514        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9515                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9516            if (!sUserManager.exists(userId))
9517                return null;
9518            if (packageProviders == null) {
9519                return null;
9520            }
9521            mFlags = flags;
9522            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9523            final int N = packageProviders.size();
9524            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9525                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9526
9527            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9528            for (int i = 0; i < N; ++i) {
9529                intentFilters = packageProviders.get(i).intents;
9530                if (intentFilters != null && intentFilters.size() > 0) {
9531                    PackageParser.ProviderIntentInfo[] array =
9532                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9533                    intentFilters.toArray(array);
9534                    listCut.add(array);
9535                }
9536            }
9537            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9538        }
9539
9540        public final void addProvider(PackageParser.Provider p) {
9541            if (mProviders.containsKey(p.getComponentName())) {
9542                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9543                return;
9544            }
9545
9546            mProviders.put(p.getComponentName(), p);
9547            if (DEBUG_SHOW_INFO) {
9548                Log.v(TAG, "  "
9549                        + (p.info.nonLocalizedLabel != null
9550                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9551                Log.v(TAG, "    Class=" + p.info.name);
9552            }
9553            final int NI = p.intents.size();
9554            int j;
9555            for (j = 0; j < NI; j++) {
9556                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9557                if (DEBUG_SHOW_INFO) {
9558                    Log.v(TAG, "    IntentFilter:");
9559                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9560                }
9561                if (!intent.debugCheck()) {
9562                    Log.w(TAG, "==> For Provider " + p.info.name);
9563                }
9564                addFilter(intent);
9565            }
9566        }
9567
9568        public final void removeProvider(PackageParser.Provider p) {
9569            mProviders.remove(p.getComponentName());
9570            if (DEBUG_SHOW_INFO) {
9571                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9572                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9573                Log.v(TAG, "    Class=" + p.info.name);
9574            }
9575            final int NI = p.intents.size();
9576            int j;
9577            for (j = 0; j < NI; j++) {
9578                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9579                if (DEBUG_SHOW_INFO) {
9580                    Log.v(TAG, "    IntentFilter:");
9581                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9582                }
9583                removeFilter(intent);
9584            }
9585        }
9586
9587        @Override
9588        protected boolean allowFilterResult(
9589                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9590            ProviderInfo filterPi = filter.provider.info;
9591            for (int i = dest.size() - 1; i >= 0; i--) {
9592                ProviderInfo destPi = dest.get(i).providerInfo;
9593                if (destPi.name == filterPi.name
9594                        && destPi.packageName == filterPi.packageName) {
9595                    return false;
9596                }
9597            }
9598            return true;
9599        }
9600
9601        @Override
9602        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9603            return new PackageParser.ProviderIntentInfo[size];
9604        }
9605
9606        @Override
9607        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9608            if (!sUserManager.exists(userId))
9609                return true;
9610            PackageParser.Package p = filter.provider.owner;
9611            if (p != null) {
9612                PackageSetting ps = (PackageSetting) p.mExtras;
9613                if (ps != null) {
9614                    // System apps are never considered stopped for purposes of
9615                    // filtering, because there may be no way for the user to
9616                    // actually re-launch them.
9617                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9618                            && ps.getStopped(userId);
9619                }
9620            }
9621            return false;
9622        }
9623
9624        @Override
9625        protected boolean isPackageForFilter(String packageName,
9626                PackageParser.ProviderIntentInfo info) {
9627            return packageName.equals(info.provider.owner.packageName);
9628        }
9629
9630        @Override
9631        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9632                int match, int userId) {
9633            if (!sUserManager.exists(userId))
9634                return null;
9635            final PackageParser.ProviderIntentInfo info = filter;
9636            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9637                return null;
9638            }
9639            final PackageParser.Provider provider = info.provider;
9640            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9641            if (ps == null) {
9642                return null;
9643            }
9644            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9645                    ps.readUserState(userId), userId);
9646            if (pi == null) {
9647                return null;
9648            }
9649            final ResolveInfo res = new ResolveInfo();
9650            res.providerInfo = pi;
9651            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9652                res.filter = filter;
9653            }
9654            res.priority = info.getPriority();
9655            res.preferredOrder = provider.owner.mPreferredOrder;
9656            res.match = match;
9657            res.isDefault = info.hasDefault;
9658            res.labelRes = info.labelRes;
9659            res.nonLocalizedLabel = info.nonLocalizedLabel;
9660            res.icon = info.icon;
9661            res.system = res.providerInfo.applicationInfo.isSystemApp();
9662            return res;
9663        }
9664
9665        @Override
9666        protected void sortResults(List<ResolveInfo> results) {
9667            Collections.sort(results, mResolvePrioritySorter);
9668        }
9669
9670        @Override
9671        protected void dumpFilter(PrintWriter out, String prefix,
9672                PackageParser.ProviderIntentInfo filter) {
9673            out.print(prefix);
9674            out.print(
9675                    Integer.toHexString(System.identityHashCode(filter.provider)));
9676            out.print(' ');
9677            filter.provider.printComponentShortName(out);
9678            out.print(" filter ");
9679            out.println(Integer.toHexString(System.identityHashCode(filter)));
9680        }
9681
9682        @Override
9683        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9684            return filter.provider;
9685        }
9686
9687        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9688            PackageParser.Provider provider = (PackageParser.Provider)label;
9689            out.print(prefix); out.print(
9690                    Integer.toHexString(System.identityHashCode(provider)));
9691                    out.print(' ');
9692                    provider.printComponentShortName(out);
9693            if (count > 1) {
9694                out.print(" ("); out.print(count); out.print(" filters)");
9695            }
9696            out.println();
9697        }
9698
9699        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9700                = new ArrayMap<ComponentName, PackageParser.Provider>();
9701        private int mFlags;
9702    }
9703
9704    private static final class EphemeralIntentResolver
9705            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9706        @Override
9707        protected EphemeralResolveIntentInfo[] newArray(int size) {
9708            return new EphemeralResolveIntentInfo[size];
9709        }
9710
9711        @Override
9712        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9713            return true;
9714        }
9715
9716        @Override
9717        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9718                int userId) {
9719            if (!sUserManager.exists(userId)) {
9720                return null;
9721            }
9722            return info.getEphemeralResolveInfo();
9723        }
9724    }
9725
9726    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9727            new Comparator<ResolveInfo>() {
9728        public int compare(ResolveInfo r1, ResolveInfo r2) {
9729            int v1 = r1.priority;
9730            int v2 = r2.priority;
9731            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9732            if (v1 != v2) {
9733                return (v1 > v2) ? -1 : 1;
9734            }
9735            v1 = r1.preferredOrder;
9736            v2 = r2.preferredOrder;
9737            if (v1 != v2) {
9738                return (v1 > v2) ? -1 : 1;
9739            }
9740            if (r1.isDefault != r2.isDefault) {
9741                return r1.isDefault ? -1 : 1;
9742            }
9743            v1 = r1.match;
9744            v2 = r2.match;
9745            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9746            if (v1 != v2) {
9747                return (v1 > v2) ? -1 : 1;
9748            }
9749            if (r1.system != r2.system) {
9750                return r1.system ? -1 : 1;
9751            }
9752            if (r1.activityInfo != null) {
9753                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9754            }
9755            if (r1.serviceInfo != null) {
9756                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9757            }
9758            if (r1.providerInfo != null) {
9759                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9760            }
9761            return 0;
9762        }
9763    };
9764
9765    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9766            new Comparator<ProviderInfo>() {
9767        public int compare(ProviderInfo p1, ProviderInfo p2) {
9768            final int v1 = p1.initOrder;
9769            final int v2 = p2.initOrder;
9770            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9771        }
9772    };
9773
9774    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9775            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9776            final int[] userIds) {
9777        mHandler.post(new Runnable() {
9778            @Override
9779            public void run() {
9780                try {
9781                    final IActivityManager am = ActivityManagerNative.getDefault();
9782                    if (am == null) return;
9783                    final int[] resolvedUserIds;
9784                    if (userIds == null) {
9785                        resolvedUserIds = am.getRunningUserIds();
9786                    } else {
9787                        resolvedUserIds = userIds;
9788                    }
9789                    for (int id : resolvedUserIds) {
9790                        final Intent intent = new Intent(action,
9791                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9792                        if (extras != null) {
9793                            intent.putExtras(extras);
9794                        }
9795                        if (targetPkg != null) {
9796                            intent.setPackage(targetPkg);
9797                        }
9798                        // Modify the UID when posting to other users
9799                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9800                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9801                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9802                            intent.putExtra(Intent.EXTRA_UID, uid);
9803                        }
9804                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9805                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9806                        if (DEBUG_BROADCASTS) {
9807                            RuntimeException here = new RuntimeException("here");
9808                            here.fillInStackTrace();
9809                            Slog.d(TAG, "Sending to user " + id + ": "
9810                                    + intent.toShortString(false, true, false, false)
9811                                    + " " + intent.getExtras(), here);
9812                        }
9813                        am.broadcastIntent(null, intent, null, finishedReceiver,
9814                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9815                                null, finishedReceiver != null, false, id);
9816                    }
9817                } catch (RemoteException ex) {
9818                }
9819            }
9820        });
9821    }
9822
9823    /**
9824     * Check if the external storage media is available. This is true if there
9825     * is a mounted external storage medium or if the external storage is
9826     * emulated.
9827     */
9828    private boolean isExternalMediaAvailable() {
9829        return mMediaMounted || Environment.isExternalStorageEmulated();
9830    }
9831
9832    @Override
9833    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9834        // writer
9835        synchronized (mPackages) {
9836            if (!isExternalMediaAvailable()) {
9837                // If the external storage is no longer mounted at this point,
9838                // the caller may not have been able to delete all of this
9839                // packages files and can not delete any more.  Bail.
9840                return null;
9841            }
9842            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9843            if (lastPackage != null) {
9844                pkgs.remove(lastPackage);
9845            }
9846            if (pkgs.size() > 0) {
9847                return pkgs.get(0);
9848            }
9849        }
9850        return null;
9851    }
9852
9853    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9854        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9855                userId, andCode ? 1 : 0, packageName);
9856        if (mSystemReady) {
9857            msg.sendToTarget();
9858        } else {
9859            if (mPostSystemReadyMessages == null) {
9860                mPostSystemReadyMessages = new ArrayList<>();
9861            }
9862            mPostSystemReadyMessages.add(msg);
9863        }
9864    }
9865
9866    void startCleaningPackages() {
9867        // reader
9868        synchronized (mPackages) {
9869            if (!isExternalMediaAvailable()) {
9870                return;
9871            }
9872            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9873                return;
9874            }
9875        }
9876        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9877        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9878        IActivityManager am = ActivityManagerNative.getDefault();
9879        if (am != null) {
9880            try {
9881                am.startService(null, intent, null, mContext.getOpPackageName(),
9882                        UserHandle.USER_SYSTEM);
9883            } catch (RemoteException e) {
9884            }
9885        }
9886    }
9887
9888    @Override
9889    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9890            int installFlags, String installerPackageName, VerificationParams verificationParams,
9891            String packageAbiOverride) {
9892        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9893                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9894    }
9895
9896    @Override
9897    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9898            int installFlags, String installerPackageName, VerificationParams verificationParams,
9899            String packageAbiOverride, int userId) {
9900        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9901
9902        final int callingUid = Binder.getCallingUid();
9903        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9904
9905        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9906            try {
9907                if (observer != null) {
9908                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9909                }
9910            } catch (RemoteException re) {
9911            }
9912            return;
9913        }
9914
9915        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9916            installFlags |= PackageManager.INSTALL_FROM_ADB;
9917
9918        } else {
9919            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9920            // about installerPackageName.
9921
9922            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9923            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9924        }
9925
9926        UserHandle user;
9927        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9928            user = UserHandle.ALL;
9929        } else {
9930            user = new UserHandle(userId);
9931        }
9932
9933        // Only system components can circumvent runtime permissions when installing.
9934        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9935                && mContext.checkCallingOrSelfPermission(Manifest.permission
9936                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9937            throw new SecurityException("You need the "
9938                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9939                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9940        }
9941
9942        verificationParams.setInstallerUid(callingUid);
9943
9944        final File originFile = new File(originPath);
9945        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9946
9947        final Message msg = mHandler.obtainMessage(INIT_COPY);
9948        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9949                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9950        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9951        msg.obj = params;
9952
9953        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9954                System.identityHashCode(msg.obj));
9955        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9956                System.identityHashCode(msg.obj));
9957
9958        mHandler.sendMessage(msg);
9959    }
9960
9961    void installStage(String packageName, File stagedDir, String stagedCid,
9962            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9963            String installerPackageName, int installerUid, UserHandle user) {
9964        if (DEBUG_EPHEMERAL) {
9965            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9966                Slog.d(TAG, "Ephemeral install of " + packageName);
9967            }
9968        }
9969        final VerificationParams verifParams = new VerificationParams(
9970                null, sessionParams.originatingUri, sessionParams.referrerUri,
9971                sessionParams.originatingUid);
9972        verifParams.setInstallerUid(installerUid);
9973
9974        final OriginInfo origin;
9975        if (stagedDir != null) {
9976            origin = OriginInfo.fromStagedFile(stagedDir);
9977        } else {
9978            origin = OriginInfo.fromStagedContainer(stagedCid);
9979        }
9980
9981        final Message msg = mHandler.obtainMessage(INIT_COPY);
9982        final InstallParams params = new InstallParams(origin, null, observer,
9983                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9984                verifParams, user, sessionParams.abiOverride,
9985                sessionParams.grantedRuntimePermissions);
9986        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9987        msg.obj = params;
9988
9989        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9990                System.identityHashCode(msg.obj));
9991        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9992                System.identityHashCode(msg.obj));
9993
9994        mHandler.sendMessage(msg);
9995    }
9996
9997    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9998        Bundle extras = new Bundle(1);
9999        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10000
10001        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10002                packageName, extras, 0, null, null, new int[] {userId});
10003        try {
10004            IActivityManager am = ActivityManagerNative.getDefault();
10005            final boolean isSystem =
10006                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10007            if (isSystem && am.isUserRunning(userId, 0)) {
10008                // The just-installed/enabled app is bundled on the system, so presumed
10009                // to be able to run automatically without needing an explicit launch.
10010                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10011                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10012                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10013                        .setPackage(packageName);
10014                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10015                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10016            }
10017        } catch (RemoteException e) {
10018            // shouldn't happen
10019            Slog.w(TAG, "Unable to bootstrap installed package", e);
10020        }
10021    }
10022
10023    @Override
10024    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10025            int userId) {
10026        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10027        PackageSetting pkgSetting;
10028        final int uid = Binder.getCallingUid();
10029        enforceCrossUserPermission(uid, userId, true, true,
10030                "setApplicationHiddenSetting for user " + userId);
10031
10032        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10033            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10034            return false;
10035        }
10036
10037        long callingId = Binder.clearCallingIdentity();
10038        try {
10039            boolean sendAdded = false;
10040            boolean sendRemoved = false;
10041            // writer
10042            synchronized (mPackages) {
10043                pkgSetting = mSettings.mPackages.get(packageName);
10044                if (pkgSetting == null) {
10045                    return false;
10046                }
10047                if (pkgSetting.getHidden(userId) != hidden) {
10048                    pkgSetting.setHidden(hidden, userId);
10049                    mSettings.writePackageRestrictionsLPr(userId);
10050                    if (hidden) {
10051                        sendRemoved = true;
10052                    } else {
10053                        sendAdded = true;
10054                    }
10055                }
10056            }
10057            if (sendAdded) {
10058                sendPackageAddedForUser(packageName, pkgSetting, userId);
10059                return true;
10060            }
10061            if (sendRemoved) {
10062                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10063                        "hiding pkg");
10064                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10065                return true;
10066            }
10067        } finally {
10068            Binder.restoreCallingIdentity(callingId);
10069        }
10070        return false;
10071    }
10072
10073    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10074            int userId) {
10075        final PackageRemovedInfo info = new PackageRemovedInfo();
10076        info.removedPackage = packageName;
10077        info.removedUsers = new int[] {userId};
10078        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10079        info.sendBroadcast(false, false, false);
10080    }
10081
10082    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10083        if (pkgList.length > 0) {
10084            Bundle extras = new Bundle(1);
10085            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10086
10087            sendPackageBroadcast(
10088                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10089                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10090                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10091                    new int[] {userId});
10092        }
10093    }
10094
10095    /**
10096     * Returns true if application is not found or there was an error. Otherwise it returns
10097     * the hidden state of the package for the given user.
10098     */
10099    @Override
10100    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10101        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10102        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10103                false, "getApplicationHidden for user " + userId);
10104        PackageSetting pkgSetting;
10105        long callingId = Binder.clearCallingIdentity();
10106        try {
10107            // writer
10108            synchronized (mPackages) {
10109                pkgSetting = mSettings.mPackages.get(packageName);
10110                if (pkgSetting == null) {
10111                    return true;
10112                }
10113                return pkgSetting.getHidden(userId);
10114            }
10115        } finally {
10116            Binder.restoreCallingIdentity(callingId);
10117        }
10118    }
10119
10120    /**
10121     * @hide
10122     */
10123    @Override
10124    public int installExistingPackageAsUser(String packageName, int userId) {
10125        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10126                null);
10127        PackageSetting pkgSetting;
10128        final int uid = Binder.getCallingUid();
10129        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10130                + userId);
10131        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10132            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10133        }
10134
10135        long callingId = Binder.clearCallingIdentity();
10136        try {
10137            boolean installed = false;
10138
10139            // writer
10140            synchronized (mPackages) {
10141                pkgSetting = mSettings.mPackages.get(packageName);
10142                if (pkgSetting == null) {
10143                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10144                }
10145                if (!pkgSetting.getInstalled(userId)) {
10146                    pkgSetting.setInstalled(true, userId);
10147                    pkgSetting.setHidden(false, userId);
10148                    mSettings.writePackageRestrictionsLPr(userId);
10149                    if (pkgSetting.pkg != null) {
10150                        prepareAppDataAfterInstall(pkgSetting.pkg);
10151                    }
10152                    installed = true;
10153                }
10154            }
10155
10156            if (installed) {
10157                sendPackageAddedForUser(packageName, pkgSetting, userId);
10158            }
10159        } finally {
10160            Binder.restoreCallingIdentity(callingId);
10161        }
10162
10163        return PackageManager.INSTALL_SUCCEEDED;
10164    }
10165
10166    boolean isUserRestricted(int userId, String restrictionKey) {
10167        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10168        if (restrictions.getBoolean(restrictionKey, false)) {
10169            Log.w(TAG, "User is restricted: " + restrictionKey);
10170            return true;
10171        }
10172        return false;
10173    }
10174
10175    @Override
10176    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10177        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10178        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10179                "setPackageSuspended for user " + userId);
10180
10181        long callingId = Binder.clearCallingIdentity();
10182        try {
10183            boolean changed = false;
10184            boolean success = false;
10185            synchronized (mPackages) {
10186                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10187                if (pkgSetting != null) {
10188                    if (pkgSetting.getSuspended(userId) != suspended) {
10189                        pkgSetting.setSuspended(suspended, userId);
10190                        mSettings.writePackageRestrictionsLPr(userId);
10191                        changed = true;
10192                    }
10193                    success = true;
10194                }
10195            }
10196
10197            if (changed) {
10198                // TODO:
10199                // * maybe kill application if suspended
10200                // * hide suspended app from recents
10201                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10202            }
10203            return success;
10204        } finally {
10205            Binder.restoreCallingIdentity(callingId);
10206        }
10207    }
10208
10209    @Override
10210    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10211        mContext.enforceCallingOrSelfPermission(
10212                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10213                "Only package verification agents can verify applications");
10214
10215        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10216        final PackageVerificationResponse response = new PackageVerificationResponse(
10217                verificationCode, Binder.getCallingUid());
10218        msg.arg1 = id;
10219        msg.obj = response;
10220        mHandler.sendMessage(msg);
10221    }
10222
10223    @Override
10224    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10225            long millisecondsToDelay) {
10226        mContext.enforceCallingOrSelfPermission(
10227                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10228                "Only package verification agents can extend verification timeouts");
10229
10230        final PackageVerificationState state = mPendingVerification.get(id);
10231        final PackageVerificationResponse response = new PackageVerificationResponse(
10232                verificationCodeAtTimeout, Binder.getCallingUid());
10233
10234        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10235            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10236        }
10237        if (millisecondsToDelay < 0) {
10238            millisecondsToDelay = 0;
10239        }
10240        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10241                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10242            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10243        }
10244
10245        if ((state != null) && !state.timeoutExtended()) {
10246            state.extendTimeout();
10247
10248            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10249            msg.arg1 = id;
10250            msg.obj = response;
10251            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10252        }
10253    }
10254
10255    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10256            int verificationCode, UserHandle user) {
10257        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10258        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10259        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10260        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10261        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10262
10263        mContext.sendBroadcastAsUser(intent, user,
10264                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10265    }
10266
10267    private ComponentName matchComponentForVerifier(String packageName,
10268            List<ResolveInfo> receivers) {
10269        ActivityInfo targetReceiver = null;
10270
10271        final int NR = receivers.size();
10272        for (int i = 0; i < NR; i++) {
10273            final ResolveInfo info = receivers.get(i);
10274            if (info.activityInfo == null) {
10275                continue;
10276            }
10277
10278            if (packageName.equals(info.activityInfo.packageName)) {
10279                targetReceiver = info.activityInfo;
10280                break;
10281            }
10282        }
10283
10284        if (targetReceiver == null) {
10285            return null;
10286        }
10287
10288        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10289    }
10290
10291    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10292            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10293        if (pkgInfo.verifiers.length == 0) {
10294            return null;
10295        }
10296
10297        final int N = pkgInfo.verifiers.length;
10298        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10299        for (int i = 0; i < N; i++) {
10300            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10301
10302            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10303                    receivers);
10304            if (comp == null) {
10305                continue;
10306            }
10307
10308            final int verifierUid = getUidForVerifier(verifierInfo);
10309            if (verifierUid == -1) {
10310                continue;
10311            }
10312
10313            if (DEBUG_VERIFY) {
10314                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10315                        + " with the correct signature");
10316            }
10317            sufficientVerifiers.add(comp);
10318            verificationState.addSufficientVerifier(verifierUid);
10319        }
10320
10321        return sufficientVerifiers;
10322    }
10323
10324    private int getUidForVerifier(VerifierInfo verifierInfo) {
10325        synchronized (mPackages) {
10326            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10327            if (pkg == null) {
10328                return -1;
10329            } else if (pkg.mSignatures.length != 1) {
10330                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10331                        + " has more than one signature; ignoring");
10332                return -1;
10333            }
10334
10335            /*
10336             * If the public key of the package's signature does not match
10337             * our expected public key, then this is a different package and
10338             * we should skip.
10339             */
10340
10341            final byte[] expectedPublicKey;
10342            try {
10343                final Signature verifierSig = pkg.mSignatures[0];
10344                final PublicKey publicKey = verifierSig.getPublicKey();
10345                expectedPublicKey = publicKey.getEncoded();
10346            } catch (CertificateException e) {
10347                return -1;
10348            }
10349
10350            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10351
10352            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10353                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10354                        + " does not have the expected public key; ignoring");
10355                return -1;
10356            }
10357
10358            return pkg.applicationInfo.uid;
10359        }
10360    }
10361
10362    @Override
10363    public void finishPackageInstall(int token) {
10364        enforceSystemOrRoot("Only the system is allowed to finish installs");
10365
10366        if (DEBUG_INSTALL) {
10367            Slog.v(TAG, "BM finishing package install for " + token);
10368        }
10369        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10370
10371        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10372        mHandler.sendMessage(msg);
10373    }
10374
10375    /**
10376     * Get the verification agent timeout.
10377     *
10378     * @return verification timeout in milliseconds
10379     */
10380    private long getVerificationTimeout() {
10381        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10382                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10383                DEFAULT_VERIFICATION_TIMEOUT);
10384    }
10385
10386    /**
10387     * Get the default verification agent response code.
10388     *
10389     * @return default verification response code
10390     */
10391    private int getDefaultVerificationResponse() {
10392        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10393                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10394                DEFAULT_VERIFICATION_RESPONSE);
10395    }
10396
10397    /**
10398     * Check whether or not package verification has been enabled.
10399     *
10400     * @return true if verification should be performed
10401     */
10402    private boolean isVerificationEnabled(int userId, int installFlags) {
10403        if (!DEFAULT_VERIFY_ENABLE) {
10404            return false;
10405        }
10406        // Ephemeral apps don't get the full verification treatment
10407        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10408            if (DEBUG_EPHEMERAL) {
10409                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10410            }
10411            return false;
10412        }
10413
10414        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10415
10416        // Check if installing from ADB
10417        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10418            // Do not run verification in a test harness environment
10419            if (ActivityManager.isRunningInTestHarness()) {
10420                return false;
10421            }
10422            if (ensureVerifyAppsEnabled) {
10423                return true;
10424            }
10425            // Check if the developer does not want package verification for ADB installs
10426            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10427                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10428                return false;
10429            }
10430        }
10431
10432        if (ensureVerifyAppsEnabled) {
10433            return true;
10434        }
10435
10436        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10437                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10438    }
10439
10440    @Override
10441    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10442            throws RemoteException {
10443        mContext.enforceCallingOrSelfPermission(
10444                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10445                "Only intentfilter verification agents can verify applications");
10446
10447        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10448        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10449                Binder.getCallingUid(), verificationCode, failedDomains);
10450        msg.arg1 = id;
10451        msg.obj = response;
10452        mHandler.sendMessage(msg);
10453    }
10454
10455    @Override
10456    public int getIntentVerificationStatus(String packageName, int userId) {
10457        synchronized (mPackages) {
10458            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10459        }
10460    }
10461
10462    @Override
10463    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10464        mContext.enforceCallingOrSelfPermission(
10465                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10466
10467        boolean result = false;
10468        synchronized (mPackages) {
10469            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10470        }
10471        if (result) {
10472            scheduleWritePackageRestrictionsLocked(userId);
10473        }
10474        return result;
10475    }
10476
10477    @Override
10478    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10479        synchronized (mPackages) {
10480            return mSettings.getIntentFilterVerificationsLPr(packageName);
10481        }
10482    }
10483
10484    @Override
10485    public List<IntentFilter> getAllIntentFilters(String packageName) {
10486        if (TextUtils.isEmpty(packageName)) {
10487            return Collections.<IntentFilter>emptyList();
10488        }
10489        synchronized (mPackages) {
10490            PackageParser.Package pkg = mPackages.get(packageName);
10491            if (pkg == null || pkg.activities == null) {
10492                return Collections.<IntentFilter>emptyList();
10493            }
10494            final int count = pkg.activities.size();
10495            ArrayList<IntentFilter> result = new ArrayList<>();
10496            for (int n=0; n<count; n++) {
10497                PackageParser.Activity activity = pkg.activities.get(n);
10498                if (activity.intents != null && activity.intents.size() > 0) {
10499                    result.addAll(activity.intents);
10500                }
10501            }
10502            return result;
10503        }
10504    }
10505
10506    @Override
10507    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10508        mContext.enforceCallingOrSelfPermission(
10509                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10510
10511        synchronized (mPackages) {
10512            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10513            if (packageName != null) {
10514                result |= updateIntentVerificationStatus(packageName,
10515                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10516                        userId);
10517                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10518                        packageName, userId);
10519            }
10520            return result;
10521        }
10522    }
10523
10524    @Override
10525    public String getDefaultBrowserPackageName(int userId) {
10526        synchronized (mPackages) {
10527            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10528        }
10529    }
10530
10531    /**
10532     * Get the "allow unknown sources" setting.
10533     *
10534     * @return the current "allow unknown sources" setting
10535     */
10536    private int getUnknownSourcesSettings() {
10537        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10538                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10539                -1);
10540    }
10541
10542    @Override
10543    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10544        final int uid = Binder.getCallingUid();
10545        // writer
10546        synchronized (mPackages) {
10547            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10548            if (targetPackageSetting == null) {
10549                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10550            }
10551
10552            PackageSetting installerPackageSetting;
10553            if (installerPackageName != null) {
10554                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10555                if (installerPackageSetting == null) {
10556                    throw new IllegalArgumentException("Unknown installer package: "
10557                            + installerPackageName);
10558                }
10559            } else {
10560                installerPackageSetting = null;
10561            }
10562
10563            Signature[] callerSignature;
10564            Object obj = mSettings.getUserIdLPr(uid);
10565            if (obj != null) {
10566                if (obj instanceof SharedUserSetting) {
10567                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10568                } else if (obj instanceof PackageSetting) {
10569                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10570                } else {
10571                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10572                }
10573            } else {
10574                throw new SecurityException("Unknown calling UID: " + uid);
10575            }
10576
10577            // Verify: can't set installerPackageName to a package that is
10578            // not signed with the same cert as the caller.
10579            if (installerPackageSetting != null) {
10580                if (compareSignatures(callerSignature,
10581                        installerPackageSetting.signatures.mSignatures)
10582                        != PackageManager.SIGNATURE_MATCH) {
10583                    throw new SecurityException(
10584                            "Caller does not have same cert as new installer package "
10585                            + installerPackageName);
10586                }
10587            }
10588
10589            // Verify: if target already has an installer package, it must
10590            // be signed with the same cert as the caller.
10591            if (targetPackageSetting.installerPackageName != null) {
10592                PackageSetting setting = mSettings.mPackages.get(
10593                        targetPackageSetting.installerPackageName);
10594                // If the currently set package isn't valid, then it's always
10595                // okay to change it.
10596                if (setting != null) {
10597                    if (compareSignatures(callerSignature,
10598                            setting.signatures.mSignatures)
10599                            != PackageManager.SIGNATURE_MATCH) {
10600                        throw new SecurityException(
10601                                "Caller does not have same cert as old installer package "
10602                                + targetPackageSetting.installerPackageName);
10603                    }
10604                }
10605            }
10606
10607            // Okay!
10608            targetPackageSetting.installerPackageName = installerPackageName;
10609            scheduleWriteSettingsLocked();
10610        }
10611    }
10612
10613    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10614        // Queue up an async operation since the package installation may take a little while.
10615        mHandler.post(new Runnable() {
10616            public void run() {
10617                mHandler.removeCallbacks(this);
10618                 // Result object to be returned
10619                PackageInstalledInfo res = new PackageInstalledInfo();
10620                res.returnCode = currentStatus;
10621                res.uid = -1;
10622                res.pkg = null;
10623                res.removedInfo = new PackageRemovedInfo();
10624                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10625                    args.doPreInstall(res.returnCode);
10626                    synchronized (mInstallLock) {
10627                        installPackageTracedLI(args, res);
10628                    }
10629                    args.doPostInstall(res.returnCode, res.uid);
10630                }
10631
10632                // A restore should be performed at this point if (a) the install
10633                // succeeded, (b) the operation is not an update, and (c) the new
10634                // package has not opted out of backup participation.
10635                final boolean update = res.removedInfo.removedPackage != null;
10636                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10637                boolean doRestore = !update
10638                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10639
10640                // Set up the post-install work request bookkeeping.  This will be used
10641                // and cleaned up by the post-install event handling regardless of whether
10642                // there's a restore pass performed.  Token values are >= 1.
10643                int token;
10644                if (mNextInstallToken < 0) mNextInstallToken = 1;
10645                token = mNextInstallToken++;
10646
10647                PostInstallData data = new PostInstallData(args, res);
10648                mRunningInstalls.put(token, data);
10649                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10650
10651                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10652                    // Pass responsibility to the Backup Manager.  It will perform a
10653                    // restore if appropriate, then pass responsibility back to the
10654                    // Package Manager to run the post-install observer callbacks
10655                    // and broadcasts.
10656                    IBackupManager bm = IBackupManager.Stub.asInterface(
10657                            ServiceManager.getService(Context.BACKUP_SERVICE));
10658                    if (bm != null) {
10659                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10660                                + " to BM for possible restore");
10661                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10662                        try {
10663                            // TODO: http://b/22388012
10664                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10665                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10666                            } else {
10667                                doRestore = false;
10668                            }
10669                        } catch (RemoteException e) {
10670                            // can't happen; the backup manager is local
10671                        } catch (Exception e) {
10672                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10673                            doRestore = false;
10674                        }
10675                    } else {
10676                        Slog.e(TAG, "Backup Manager not found!");
10677                        doRestore = false;
10678                    }
10679                }
10680
10681                if (!doRestore) {
10682                    // No restore possible, or the Backup Manager was mysteriously not
10683                    // available -- just fire the post-install work request directly.
10684                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10685
10686                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10687
10688                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10689                    mHandler.sendMessage(msg);
10690                }
10691            }
10692        });
10693    }
10694
10695    private abstract class HandlerParams {
10696        private static final int MAX_RETRIES = 4;
10697
10698        /**
10699         * Number of times startCopy() has been attempted and had a non-fatal
10700         * error.
10701         */
10702        private int mRetries = 0;
10703
10704        /** User handle for the user requesting the information or installation. */
10705        private final UserHandle mUser;
10706        String traceMethod;
10707        int traceCookie;
10708
10709        HandlerParams(UserHandle user) {
10710            mUser = user;
10711        }
10712
10713        UserHandle getUser() {
10714            return mUser;
10715        }
10716
10717        HandlerParams setTraceMethod(String traceMethod) {
10718            this.traceMethod = traceMethod;
10719            return this;
10720        }
10721
10722        HandlerParams setTraceCookie(int traceCookie) {
10723            this.traceCookie = traceCookie;
10724            return this;
10725        }
10726
10727        final boolean startCopy() {
10728            boolean res;
10729            try {
10730                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10731
10732                if (++mRetries > MAX_RETRIES) {
10733                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10734                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10735                    handleServiceError();
10736                    return false;
10737                } else {
10738                    handleStartCopy();
10739                    res = true;
10740                }
10741            } catch (RemoteException e) {
10742                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10743                mHandler.sendEmptyMessage(MCS_RECONNECT);
10744                res = false;
10745            }
10746            handleReturnCode();
10747            return res;
10748        }
10749
10750        final void serviceError() {
10751            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10752            handleServiceError();
10753            handleReturnCode();
10754        }
10755
10756        abstract void handleStartCopy() throws RemoteException;
10757        abstract void handleServiceError();
10758        abstract void handleReturnCode();
10759    }
10760
10761    class MeasureParams extends HandlerParams {
10762        private final PackageStats mStats;
10763        private boolean mSuccess;
10764
10765        private final IPackageStatsObserver mObserver;
10766
10767        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10768            super(new UserHandle(stats.userHandle));
10769            mObserver = observer;
10770            mStats = stats;
10771        }
10772
10773        @Override
10774        public String toString() {
10775            return "MeasureParams{"
10776                + Integer.toHexString(System.identityHashCode(this))
10777                + " " + mStats.packageName + "}";
10778        }
10779
10780        @Override
10781        void handleStartCopy() throws RemoteException {
10782            synchronized (mInstallLock) {
10783                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10784            }
10785
10786            if (mSuccess) {
10787                final boolean mounted;
10788                if (Environment.isExternalStorageEmulated()) {
10789                    mounted = true;
10790                } else {
10791                    final String status = Environment.getExternalStorageState();
10792                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10793                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10794                }
10795
10796                if (mounted) {
10797                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10798
10799                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10800                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10801
10802                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10803                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10804
10805                    // Always subtract cache size, since it's a subdirectory
10806                    mStats.externalDataSize -= mStats.externalCacheSize;
10807
10808                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10809                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10810
10811                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10812                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10813                }
10814            }
10815        }
10816
10817        @Override
10818        void handleReturnCode() {
10819            if (mObserver != null) {
10820                try {
10821                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10822                } catch (RemoteException e) {
10823                    Slog.i(TAG, "Observer no longer exists.");
10824                }
10825            }
10826        }
10827
10828        @Override
10829        void handleServiceError() {
10830            Slog.e(TAG, "Could not measure application " + mStats.packageName
10831                            + " external storage");
10832        }
10833    }
10834
10835    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10836            throws RemoteException {
10837        long result = 0;
10838        for (File path : paths) {
10839            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10840        }
10841        return result;
10842    }
10843
10844    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10845        for (File path : paths) {
10846            try {
10847                mcs.clearDirectory(path.getAbsolutePath());
10848            } catch (RemoteException e) {
10849            }
10850        }
10851    }
10852
10853    static class OriginInfo {
10854        /**
10855         * Location where install is coming from, before it has been
10856         * copied/renamed into place. This could be a single monolithic APK
10857         * file, or a cluster directory. This location may be untrusted.
10858         */
10859        final File file;
10860        final String cid;
10861
10862        /**
10863         * Flag indicating that {@link #file} or {@link #cid} has already been
10864         * staged, meaning downstream users don't need to defensively copy the
10865         * contents.
10866         */
10867        final boolean staged;
10868
10869        /**
10870         * Flag indicating that {@link #file} or {@link #cid} is an already
10871         * installed app that is being moved.
10872         */
10873        final boolean existing;
10874
10875        final String resolvedPath;
10876        final File resolvedFile;
10877
10878        static OriginInfo fromNothing() {
10879            return new OriginInfo(null, null, false, false);
10880        }
10881
10882        static OriginInfo fromUntrustedFile(File file) {
10883            return new OriginInfo(file, null, false, false);
10884        }
10885
10886        static OriginInfo fromExistingFile(File file) {
10887            return new OriginInfo(file, null, false, true);
10888        }
10889
10890        static OriginInfo fromStagedFile(File file) {
10891            return new OriginInfo(file, null, true, false);
10892        }
10893
10894        static OriginInfo fromStagedContainer(String cid) {
10895            return new OriginInfo(null, cid, true, false);
10896        }
10897
10898        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10899            this.file = file;
10900            this.cid = cid;
10901            this.staged = staged;
10902            this.existing = existing;
10903
10904            if (cid != null) {
10905                resolvedPath = PackageHelper.getSdDir(cid);
10906                resolvedFile = new File(resolvedPath);
10907            } else if (file != null) {
10908                resolvedPath = file.getAbsolutePath();
10909                resolvedFile = file;
10910            } else {
10911                resolvedPath = null;
10912                resolvedFile = null;
10913            }
10914        }
10915    }
10916
10917    static class MoveInfo {
10918        final int moveId;
10919        final String fromUuid;
10920        final String toUuid;
10921        final String packageName;
10922        final String dataAppName;
10923        final int appId;
10924        final String seinfo;
10925        final int targetSdkVersion;
10926
10927        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10928                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
10929            this.moveId = moveId;
10930            this.fromUuid = fromUuid;
10931            this.toUuid = toUuid;
10932            this.packageName = packageName;
10933            this.dataAppName = dataAppName;
10934            this.appId = appId;
10935            this.seinfo = seinfo;
10936            this.targetSdkVersion = targetSdkVersion;
10937        }
10938    }
10939
10940    class InstallParams extends HandlerParams {
10941        final OriginInfo origin;
10942        final MoveInfo move;
10943        final IPackageInstallObserver2 observer;
10944        int installFlags;
10945        final String installerPackageName;
10946        final String volumeUuid;
10947        final VerificationParams verificationParams;
10948        private InstallArgs mArgs;
10949        private int mRet;
10950        final String packageAbiOverride;
10951        final String[] grantedRuntimePermissions;
10952
10953        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10954                int installFlags, String installerPackageName, String volumeUuid,
10955                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10956                String[] grantedPermissions) {
10957            super(user);
10958            this.origin = origin;
10959            this.move = move;
10960            this.observer = observer;
10961            this.installFlags = installFlags;
10962            this.installerPackageName = installerPackageName;
10963            this.volumeUuid = volumeUuid;
10964            this.verificationParams = verificationParams;
10965            this.packageAbiOverride = packageAbiOverride;
10966            this.grantedRuntimePermissions = grantedPermissions;
10967        }
10968
10969        @Override
10970        public String toString() {
10971            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10972                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10973        }
10974
10975        private int installLocationPolicy(PackageInfoLite pkgLite) {
10976            String packageName = pkgLite.packageName;
10977            int installLocation = pkgLite.installLocation;
10978            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10979            // reader
10980            synchronized (mPackages) {
10981                PackageParser.Package pkg = mPackages.get(packageName);
10982                if (pkg != null) {
10983                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10984                        // Check for downgrading.
10985                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10986                            try {
10987                                checkDowngrade(pkg, pkgLite);
10988                            } catch (PackageManagerException e) {
10989                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10990                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10991                            }
10992                        }
10993                        // Check for updated system application.
10994                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10995                            if (onSd) {
10996                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10997                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10998                            }
10999                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11000                        } else {
11001                            if (onSd) {
11002                                // Install flag overrides everything.
11003                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11004                            }
11005                            // If current upgrade specifies particular preference
11006                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11007                                // Application explicitly specified internal.
11008                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11009                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11010                                // App explictly prefers external. Let policy decide
11011                            } else {
11012                                // Prefer previous location
11013                                if (isExternal(pkg)) {
11014                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11015                                }
11016                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11017                            }
11018                        }
11019                    } else {
11020                        // Invalid install. Return error code
11021                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11022                    }
11023                }
11024            }
11025            // All the special cases have been taken care of.
11026            // Return result based on recommended install location.
11027            if (onSd) {
11028                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11029            }
11030            return pkgLite.recommendedInstallLocation;
11031        }
11032
11033        /*
11034         * Invoke remote method to get package information and install
11035         * location values. Override install location based on default
11036         * policy if needed and then create install arguments based
11037         * on the install location.
11038         */
11039        public void handleStartCopy() throws RemoteException {
11040            int ret = PackageManager.INSTALL_SUCCEEDED;
11041
11042            // If we're already staged, we've firmly committed to an install location
11043            if (origin.staged) {
11044                if (origin.file != null) {
11045                    installFlags |= PackageManager.INSTALL_INTERNAL;
11046                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11047                } else if (origin.cid != null) {
11048                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11049                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11050                } else {
11051                    throw new IllegalStateException("Invalid stage location");
11052                }
11053            }
11054
11055            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11056            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11057            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11058            PackageInfoLite pkgLite = null;
11059
11060            if (onInt && onSd) {
11061                // Check if both bits are set.
11062                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11063                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11064            } else if (onSd && ephemeral) {
11065                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11066                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11067            } else {
11068                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11069                        packageAbiOverride);
11070
11071                if (DEBUG_EPHEMERAL && ephemeral) {
11072                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11073                }
11074
11075                /*
11076                 * If we have too little free space, try to free cache
11077                 * before giving up.
11078                 */
11079                if (!origin.staged && pkgLite.recommendedInstallLocation
11080                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11081                    // TODO: focus freeing disk space on the target device
11082                    final StorageManager storage = StorageManager.from(mContext);
11083                    final long lowThreshold = storage.getStorageLowBytes(
11084                            Environment.getDataDirectory());
11085
11086                    final long sizeBytes = mContainerService.calculateInstalledSize(
11087                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11088
11089                    try {
11090                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11091                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11092                                installFlags, packageAbiOverride);
11093                    } catch (InstallerException e) {
11094                        Slog.w(TAG, "Failed to free cache", e);
11095                    }
11096
11097                    /*
11098                     * The cache free must have deleted the file we
11099                     * downloaded to install.
11100                     *
11101                     * TODO: fix the "freeCache" call to not delete
11102                     *       the file we care about.
11103                     */
11104                    if (pkgLite.recommendedInstallLocation
11105                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11106                        pkgLite.recommendedInstallLocation
11107                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11108                    }
11109                }
11110            }
11111
11112            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11113                int loc = pkgLite.recommendedInstallLocation;
11114                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11115                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11116                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11117                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11118                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11119                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11120                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11121                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11122                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11123                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11124                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11125                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11126                } else {
11127                    // Override with defaults if needed.
11128                    loc = installLocationPolicy(pkgLite);
11129                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11130                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11131                    } else if (!onSd && !onInt) {
11132                        // Override install location with flags
11133                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11134                            // Set the flag to install on external media.
11135                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11136                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11137                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11138                            if (DEBUG_EPHEMERAL) {
11139                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11140                            }
11141                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11142                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11143                                    |PackageManager.INSTALL_INTERNAL);
11144                        } else {
11145                            // Make sure the flag for installing on external
11146                            // media is unset
11147                            installFlags |= PackageManager.INSTALL_INTERNAL;
11148                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11149                        }
11150                    }
11151                }
11152            }
11153
11154            final InstallArgs args = createInstallArgs(this);
11155            mArgs = args;
11156
11157            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11158                // TODO: http://b/22976637
11159                // Apps installed for "all" users use the device owner to verify the app
11160                UserHandle verifierUser = getUser();
11161                if (verifierUser == UserHandle.ALL) {
11162                    verifierUser = UserHandle.SYSTEM;
11163                }
11164
11165                /*
11166                 * Determine if we have any installed package verifiers. If we
11167                 * do, then we'll defer to them to verify the packages.
11168                 */
11169                final int requiredUid = mRequiredVerifierPackage == null ? -1
11170                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11171                                verifierUser.getIdentifier());
11172                if (!origin.existing && requiredUid != -1
11173                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11174                    final Intent verification = new Intent(
11175                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11176                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11177                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11178                            PACKAGE_MIME_TYPE);
11179                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11180
11181                    // Query all live verifiers based on current user state
11182                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11183                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11184
11185                    if (DEBUG_VERIFY) {
11186                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11187                                + verification.toString() + " with " + pkgLite.verifiers.length
11188                                + " optional verifiers");
11189                    }
11190
11191                    final int verificationId = mPendingVerificationToken++;
11192
11193                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11194
11195                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11196                            installerPackageName);
11197
11198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11199                            installFlags);
11200
11201                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11202                            pkgLite.packageName);
11203
11204                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11205                            pkgLite.versionCode);
11206
11207                    if (verificationParams != null) {
11208                        if (verificationParams.getVerificationURI() != null) {
11209                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11210                                 verificationParams.getVerificationURI());
11211                        }
11212                        if (verificationParams.getOriginatingURI() != null) {
11213                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11214                                  verificationParams.getOriginatingURI());
11215                        }
11216                        if (verificationParams.getReferrer() != null) {
11217                            verification.putExtra(Intent.EXTRA_REFERRER,
11218                                  verificationParams.getReferrer());
11219                        }
11220                        if (verificationParams.getOriginatingUid() >= 0) {
11221                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11222                                  verificationParams.getOriginatingUid());
11223                        }
11224                        if (verificationParams.getInstallerUid() >= 0) {
11225                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11226                                  verificationParams.getInstallerUid());
11227                        }
11228                    }
11229
11230                    final PackageVerificationState verificationState = new PackageVerificationState(
11231                            requiredUid, args);
11232
11233                    mPendingVerification.append(verificationId, verificationState);
11234
11235                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11236                            receivers, verificationState);
11237
11238                    /*
11239                     * If any sufficient verifiers were listed in the package
11240                     * manifest, attempt to ask them.
11241                     */
11242                    if (sufficientVerifiers != null) {
11243                        final int N = sufficientVerifiers.size();
11244                        if (N == 0) {
11245                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11246                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11247                        } else {
11248                            for (int i = 0; i < N; i++) {
11249                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11250
11251                                final Intent sufficientIntent = new Intent(verification);
11252                                sufficientIntent.setComponent(verifierComponent);
11253                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11254                            }
11255                        }
11256                    }
11257
11258                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11259                            mRequiredVerifierPackage, receivers);
11260                    if (ret == PackageManager.INSTALL_SUCCEEDED
11261                            && mRequiredVerifierPackage != null) {
11262                        Trace.asyncTraceBegin(
11263                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11264                        /*
11265                         * Send the intent to the required verification agent,
11266                         * but only start the verification timeout after the
11267                         * target BroadcastReceivers have run.
11268                         */
11269                        verification.setComponent(requiredVerifierComponent);
11270                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11271                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11272                                new BroadcastReceiver() {
11273                                    @Override
11274                                    public void onReceive(Context context, Intent intent) {
11275                                        final Message msg = mHandler
11276                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11277                                        msg.arg1 = verificationId;
11278                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11279                                    }
11280                                }, null, 0, null, null);
11281
11282                        /*
11283                         * We don't want the copy to proceed until verification
11284                         * succeeds, so null out this field.
11285                         */
11286                        mArgs = null;
11287                    }
11288                } else {
11289                    /*
11290                     * No package verification is enabled, so immediately start
11291                     * the remote call to initiate copy using temporary file.
11292                     */
11293                    ret = args.copyApk(mContainerService, true);
11294                }
11295            }
11296
11297            mRet = ret;
11298        }
11299
11300        @Override
11301        void handleReturnCode() {
11302            // If mArgs is null, then MCS couldn't be reached. When it
11303            // reconnects, it will try again to install. At that point, this
11304            // will succeed.
11305            if (mArgs != null) {
11306                processPendingInstall(mArgs, mRet);
11307            }
11308        }
11309
11310        @Override
11311        void handleServiceError() {
11312            mArgs = createInstallArgs(this);
11313            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11314        }
11315
11316        public boolean isForwardLocked() {
11317            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11318        }
11319    }
11320
11321    /**
11322     * Used during creation of InstallArgs
11323     *
11324     * @param installFlags package installation flags
11325     * @return true if should be installed on external storage
11326     */
11327    private static boolean installOnExternalAsec(int installFlags) {
11328        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11329            return false;
11330        }
11331        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11332            return true;
11333        }
11334        return false;
11335    }
11336
11337    /**
11338     * Used during creation of InstallArgs
11339     *
11340     * @param installFlags package installation flags
11341     * @return true if should be installed as forward locked
11342     */
11343    private static boolean installForwardLocked(int installFlags) {
11344        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11345    }
11346
11347    private InstallArgs createInstallArgs(InstallParams params) {
11348        if (params.move != null) {
11349            return new MoveInstallArgs(params);
11350        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11351            return new AsecInstallArgs(params);
11352        } else {
11353            return new FileInstallArgs(params);
11354        }
11355    }
11356
11357    /**
11358     * Create args that describe an existing installed package. Typically used
11359     * when cleaning up old installs, or used as a move source.
11360     */
11361    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11362            String resourcePath, String[] instructionSets) {
11363        final boolean isInAsec;
11364        if (installOnExternalAsec(installFlags)) {
11365            /* Apps on SD card are always in ASEC containers. */
11366            isInAsec = true;
11367        } else if (installForwardLocked(installFlags)
11368                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11369            /*
11370             * Forward-locked apps are only in ASEC containers if they're the
11371             * new style
11372             */
11373            isInAsec = true;
11374        } else {
11375            isInAsec = false;
11376        }
11377
11378        if (isInAsec) {
11379            return new AsecInstallArgs(codePath, instructionSets,
11380                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11381        } else {
11382            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11383        }
11384    }
11385
11386    static abstract class InstallArgs {
11387        /** @see InstallParams#origin */
11388        final OriginInfo origin;
11389        /** @see InstallParams#move */
11390        final MoveInfo move;
11391
11392        final IPackageInstallObserver2 observer;
11393        // Always refers to PackageManager flags only
11394        final int installFlags;
11395        final String installerPackageName;
11396        final String volumeUuid;
11397        final UserHandle user;
11398        final String abiOverride;
11399        final String[] installGrantPermissions;
11400        /** If non-null, drop an async trace when the install completes */
11401        final String traceMethod;
11402        final int traceCookie;
11403
11404        // The list of instruction sets supported by this app. This is currently
11405        // only used during the rmdex() phase to clean up resources. We can get rid of this
11406        // if we move dex files under the common app path.
11407        /* nullable */ String[] instructionSets;
11408
11409        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11410                int installFlags, String installerPackageName, String volumeUuid,
11411                UserHandle user, String[] instructionSets,
11412                String abiOverride, String[] installGrantPermissions,
11413                String traceMethod, int traceCookie) {
11414            this.origin = origin;
11415            this.move = move;
11416            this.installFlags = installFlags;
11417            this.observer = observer;
11418            this.installerPackageName = installerPackageName;
11419            this.volumeUuid = volumeUuid;
11420            this.user = user;
11421            this.instructionSets = instructionSets;
11422            this.abiOverride = abiOverride;
11423            this.installGrantPermissions = installGrantPermissions;
11424            this.traceMethod = traceMethod;
11425            this.traceCookie = traceCookie;
11426        }
11427
11428        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11429        abstract int doPreInstall(int status);
11430
11431        /**
11432         * Rename package into final resting place. All paths on the given
11433         * scanned package should be updated to reflect the rename.
11434         */
11435        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11436        abstract int doPostInstall(int status, int uid);
11437
11438        /** @see PackageSettingBase#codePathString */
11439        abstract String getCodePath();
11440        /** @see PackageSettingBase#resourcePathString */
11441        abstract String getResourcePath();
11442
11443        // Need installer lock especially for dex file removal.
11444        abstract void cleanUpResourcesLI();
11445        abstract boolean doPostDeleteLI(boolean delete);
11446
11447        /**
11448         * Called before the source arguments are copied. This is used mostly
11449         * for MoveParams when it needs to read the source file to put it in the
11450         * destination.
11451         */
11452        int doPreCopy() {
11453            return PackageManager.INSTALL_SUCCEEDED;
11454        }
11455
11456        /**
11457         * Called after the source arguments are copied. This is used mostly for
11458         * MoveParams when it needs to read the source file to put it in the
11459         * destination.
11460         *
11461         * @return
11462         */
11463        int doPostCopy(int uid) {
11464            return PackageManager.INSTALL_SUCCEEDED;
11465        }
11466
11467        protected boolean isFwdLocked() {
11468            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11469        }
11470
11471        protected boolean isExternalAsec() {
11472            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11473        }
11474
11475        protected boolean isEphemeral() {
11476            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11477        }
11478
11479        UserHandle getUser() {
11480            return user;
11481        }
11482    }
11483
11484    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11485        if (!allCodePaths.isEmpty()) {
11486            if (instructionSets == null) {
11487                throw new IllegalStateException("instructionSet == null");
11488            }
11489            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11490            for (String codePath : allCodePaths) {
11491                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11492                    try {
11493                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11494                    } catch (InstallerException ignored) {
11495                    }
11496                }
11497            }
11498        }
11499    }
11500
11501    /**
11502     * Logic to handle installation of non-ASEC applications, including copying
11503     * and renaming logic.
11504     */
11505    class FileInstallArgs extends InstallArgs {
11506        private File codeFile;
11507        private File resourceFile;
11508
11509        // Example topology:
11510        // /data/app/com.example/base.apk
11511        // /data/app/com.example/split_foo.apk
11512        // /data/app/com.example/lib/arm/libfoo.so
11513        // /data/app/com.example/lib/arm64/libfoo.so
11514        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11515
11516        /** New install */
11517        FileInstallArgs(InstallParams params) {
11518            super(params.origin, params.move, params.observer, params.installFlags,
11519                    params.installerPackageName, params.volumeUuid,
11520                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11521                    params.grantedRuntimePermissions,
11522                    params.traceMethod, params.traceCookie);
11523            if (isFwdLocked()) {
11524                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11525            }
11526        }
11527
11528        /** Existing install */
11529        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11530            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11531                    null, null, null, 0);
11532            this.codeFile = (codePath != null) ? new File(codePath) : null;
11533            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11534        }
11535
11536        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11537            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11538            try {
11539                return doCopyApk(imcs, temp);
11540            } finally {
11541                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11542            }
11543        }
11544
11545        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11546            if (origin.staged) {
11547                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11548                codeFile = origin.file;
11549                resourceFile = origin.file;
11550                return PackageManager.INSTALL_SUCCEEDED;
11551            }
11552
11553            try {
11554                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11555                final File tempDir =
11556                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11557                codeFile = tempDir;
11558                resourceFile = tempDir;
11559            } catch (IOException e) {
11560                Slog.w(TAG, "Failed to create copy file: " + e);
11561                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11562            }
11563
11564            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11565                @Override
11566                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11567                    if (!FileUtils.isValidExtFilename(name)) {
11568                        throw new IllegalArgumentException("Invalid filename: " + name);
11569                    }
11570                    try {
11571                        final File file = new File(codeFile, name);
11572                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11573                                O_RDWR | O_CREAT, 0644);
11574                        Os.chmod(file.getAbsolutePath(), 0644);
11575                        return new ParcelFileDescriptor(fd);
11576                    } catch (ErrnoException e) {
11577                        throw new RemoteException("Failed to open: " + e.getMessage());
11578                    }
11579                }
11580            };
11581
11582            int ret = PackageManager.INSTALL_SUCCEEDED;
11583            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11584            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11585                Slog.e(TAG, "Failed to copy package");
11586                return ret;
11587            }
11588
11589            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11590            NativeLibraryHelper.Handle handle = null;
11591            try {
11592                handle = NativeLibraryHelper.Handle.create(codeFile);
11593                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11594                        abiOverride);
11595            } catch (IOException e) {
11596                Slog.e(TAG, "Copying native libraries failed", e);
11597                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11598            } finally {
11599                IoUtils.closeQuietly(handle);
11600            }
11601
11602            return ret;
11603        }
11604
11605        int doPreInstall(int status) {
11606            if (status != PackageManager.INSTALL_SUCCEEDED) {
11607                cleanUp();
11608            }
11609            return status;
11610        }
11611
11612        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11613            if (status != PackageManager.INSTALL_SUCCEEDED) {
11614                cleanUp();
11615                return false;
11616            }
11617
11618            final File targetDir = codeFile.getParentFile();
11619            final File beforeCodeFile = codeFile;
11620            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11621
11622            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11623            try {
11624                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11625            } catch (ErrnoException e) {
11626                Slog.w(TAG, "Failed to rename", e);
11627                return false;
11628            }
11629
11630            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11631                Slog.w(TAG, "Failed to restorecon");
11632                return false;
11633            }
11634
11635            // Reflect the rename internally
11636            codeFile = afterCodeFile;
11637            resourceFile = afterCodeFile;
11638
11639            // Reflect the rename in scanned details
11640            pkg.codePath = afterCodeFile.getAbsolutePath();
11641            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11642                    pkg.baseCodePath);
11643            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11644                    pkg.splitCodePaths);
11645
11646            // Reflect the rename in app info
11647            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11648            pkg.applicationInfo.setCodePath(pkg.codePath);
11649            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11650            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11651            pkg.applicationInfo.setResourcePath(pkg.codePath);
11652            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11653            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11654
11655            return true;
11656        }
11657
11658        int doPostInstall(int status, int uid) {
11659            if (status != PackageManager.INSTALL_SUCCEEDED) {
11660                cleanUp();
11661            }
11662            return status;
11663        }
11664
11665        @Override
11666        String getCodePath() {
11667            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11668        }
11669
11670        @Override
11671        String getResourcePath() {
11672            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11673        }
11674
11675        private boolean cleanUp() {
11676            if (codeFile == null || !codeFile.exists()) {
11677                return false;
11678            }
11679
11680            removeCodePathLI(codeFile);
11681
11682            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11683                resourceFile.delete();
11684            }
11685
11686            return true;
11687        }
11688
11689        void cleanUpResourcesLI() {
11690            // Try enumerating all code paths before deleting
11691            List<String> allCodePaths = Collections.EMPTY_LIST;
11692            if (codeFile != null && codeFile.exists()) {
11693                try {
11694                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11695                    allCodePaths = pkg.getAllCodePaths();
11696                } catch (PackageParserException e) {
11697                    // Ignored; we tried our best
11698                }
11699            }
11700
11701            cleanUp();
11702            removeDexFiles(allCodePaths, instructionSets);
11703        }
11704
11705        boolean doPostDeleteLI(boolean delete) {
11706            // XXX err, shouldn't we respect the delete flag?
11707            cleanUpResourcesLI();
11708            return true;
11709        }
11710    }
11711
11712    private boolean isAsecExternal(String cid) {
11713        final String asecPath = PackageHelper.getSdFilesystem(cid);
11714        return !asecPath.startsWith(mAsecInternalPath);
11715    }
11716
11717    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11718            PackageManagerException {
11719        if (copyRet < 0) {
11720            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11721                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11722                throw new PackageManagerException(copyRet, message);
11723            }
11724        }
11725    }
11726
11727    /**
11728     * Extract the MountService "container ID" from the full code path of an
11729     * .apk.
11730     */
11731    static String cidFromCodePath(String fullCodePath) {
11732        int eidx = fullCodePath.lastIndexOf("/");
11733        String subStr1 = fullCodePath.substring(0, eidx);
11734        int sidx = subStr1.lastIndexOf("/");
11735        return subStr1.substring(sidx+1, eidx);
11736    }
11737
11738    /**
11739     * Logic to handle installation of ASEC applications, including copying and
11740     * renaming logic.
11741     */
11742    class AsecInstallArgs extends InstallArgs {
11743        static final String RES_FILE_NAME = "pkg.apk";
11744        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11745
11746        String cid;
11747        String packagePath;
11748        String resourcePath;
11749
11750        /** New install */
11751        AsecInstallArgs(InstallParams params) {
11752            super(params.origin, params.move, params.observer, params.installFlags,
11753                    params.installerPackageName, params.volumeUuid,
11754                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11755                    params.grantedRuntimePermissions,
11756                    params.traceMethod, params.traceCookie);
11757        }
11758
11759        /** Existing install */
11760        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11761                        boolean isExternal, boolean isForwardLocked) {
11762            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11763                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11764                    instructionSets, null, null, null, 0);
11765            // Hackily pretend we're still looking at a full code path
11766            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11767                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11768            }
11769
11770            // Extract cid from fullCodePath
11771            int eidx = fullCodePath.lastIndexOf("/");
11772            String subStr1 = fullCodePath.substring(0, eidx);
11773            int sidx = subStr1.lastIndexOf("/");
11774            cid = subStr1.substring(sidx+1, eidx);
11775            setMountPath(subStr1);
11776        }
11777
11778        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11779            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11780                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11781                    instructionSets, null, null, null, 0);
11782            this.cid = cid;
11783            setMountPath(PackageHelper.getSdDir(cid));
11784        }
11785
11786        void createCopyFile() {
11787            cid = mInstallerService.allocateExternalStageCidLegacy();
11788        }
11789
11790        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11791            if (origin.staged && origin.cid != null) {
11792                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11793                cid = origin.cid;
11794                setMountPath(PackageHelper.getSdDir(cid));
11795                return PackageManager.INSTALL_SUCCEEDED;
11796            }
11797
11798            if (temp) {
11799                createCopyFile();
11800            } else {
11801                /*
11802                 * Pre-emptively destroy the container since it's destroyed if
11803                 * copying fails due to it existing anyway.
11804                 */
11805                PackageHelper.destroySdDir(cid);
11806            }
11807
11808            final String newMountPath = imcs.copyPackageToContainer(
11809                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11810                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11811
11812            if (newMountPath != null) {
11813                setMountPath(newMountPath);
11814                return PackageManager.INSTALL_SUCCEEDED;
11815            } else {
11816                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11817            }
11818        }
11819
11820        @Override
11821        String getCodePath() {
11822            return packagePath;
11823        }
11824
11825        @Override
11826        String getResourcePath() {
11827            return resourcePath;
11828        }
11829
11830        int doPreInstall(int status) {
11831            if (status != PackageManager.INSTALL_SUCCEEDED) {
11832                // Destroy container
11833                PackageHelper.destroySdDir(cid);
11834            } else {
11835                boolean mounted = PackageHelper.isContainerMounted(cid);
11836                if (!mounted) {
11837                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11838                            Process.SYSTEM_UID);
11839                    if (newMountPath != null) {
11840                        setMountPath(newMountPath);
11841                    } else {
11842                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11843                    }
11844                }
11845            }
11846            return status;
11847        }
11848
11849        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11850            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11851            String newMountPath = null;
11852            if (PackageHelper.isContainerMounted(cid)) {
11853                // Unmount the container
11854                if (!PackageHelper.unMountSdDir(cid)) {
11855                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11856                    return false;
11857                }
11858            }
11859            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11860                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11861                        " which might be stale. Will try to clean up.");
11862                // Clean up the stale container and proceed to recreate.
11863                if (!PackageHelper.destroySdDir(newCacheId)) {
11864                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11865                    return false;
11866                }
11867                // Successfully cleaned up stale container. Try to rename again.
11868                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11869                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11870                            + " inspite of cleaning it up.");
11871                    return false;
11872                }
11873            }
11874            if (!PackageHelper.isContainerMounted(newCacheId)) {
11875                Slog.w(TAG, "Mounting container " + newCacheId);
11876                newMountPath = PackageHelper.mountSdDir(newCacheId,
11877                        getEncryptKey(), Process.SYSTEM_UID);
11878            } else {
11879                newMountPath = PackageHelper.getSdDir(newCacheId);
11880            }
11881            if (newMountPath == null) {
11882                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11883                return false;
11884            }
11885            Log.i(TAG, "Succesfully renamed " + cid +
11886                    " to " + newCacheId +
11887                    " at new path: " + newMountPath);
11888            cid = newCacheId;
11889
11890            final File beforeCodeFile = new File(packagePath);
11891            setMountPath(newMountPath);
11892            final File afterCodeFile = new File(packagePath);
11893
11894            // Reflect the rename in scanned details
11895            pkg.codePath = afterCodeFile.getAbsolutePath();
11896            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11897                    pkg.baseCodePath);
11898            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11899                    pkg.splitCodePaths);
11900
11901            // Reflect the rename in app info
11902            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11903            pkg.applicationInfo.setCodePath(pkg.codePath);
11904            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11905            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11906            pkg.applicationInfo.setResourcePath(pkg.codePath);
11907            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11908            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11909
11910            return true;
11911        }
11912
11913        private void setMountPath(String mountPath) {
11914            final File mountFile = new File(mountPath);
11915
11916            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11917            if (monolithicFile.exists()) {
11918                packagePath = monolithicFile.getAbsolutePath();
11919                if (isFwdLocked()) {
11920                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11921                } else {
11922                    resourcePath = packagePath;
11923                }
11924            } else {
11925                packagePath = mountFile.getAbsolutePath();
11926                resourcePath = packagePath;
11927            }
11928        }
11929
11930        int doPostInstall(int status, int uid) {
11931            if (status != PackageManager.INSTALL_SUCCEEDED) {
11932                cleanUp();
11933            } else {
11934                final int groupOwner;
11935                final String protectedFile;
11936                if (isFwdLocked()) {
11937                    groupOwner = UserHandle.getSharedAppGid(uid);
11938                    protectedFile = RES_FILE_NAME;
11939                } else {
11940                    groupOwner = -1;
11941                    protectedFile = null;
11942                }
11943
11944                if (uid < Process.FIRST_APPLICATION_UID
11945                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11946                    Slog.e(TAG, "Failed to finalize " + cid);
11947                    PackageHelper.destroySdDir(cid);
11948                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11949                }
11950
11951                boolean mounted = PackageHelper.isContainerMounted(cid);
11952                if (!mounted) {
11953                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11954                }
11955            }
11956            return status;
11957        }
11958
11959        private void cleanUp() {
11960            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11961
11962            // Destroy secure container
11963            PackageHelper.destroySdDir(cid);
11964        }
11965
11966        private List<String> getAllCodePaths() {
11967            final File codeFile = new File(getCodePath());
11968            if (codeFile != null && codeFile.exists()) {
11969                try {
11970                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11971                    return pkg.getAllCodePaths();
11972                } catch (PackageParserException e) {
11973                    // Ignored; we tried our best
11974                }
11975            }
11976            return Collections.EMPTY_LIST;
11977        }
11978
11979        void cleanUpResourcesLI() {
11980            // Enumerate all code paths before deleting
11981            cleanUpResourcesLI(getAllCodePaths());
11982        }
11983
11984        private void cleanUpResourcesLI(List<String> allCodePaths) {
11985            cleanUp();
11986            removeDexFiles(allCodePaths, instructionSets);
11987        }
11988
11989        String getPackageName() {
11990            return getAsecPackageName(cid);
11991        }
11992
11993        boolean doPostDeleteLI(boolean delete) {
11994            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11995            final List<String> allCodePaths = getAllCodePaths();
11996            boolean mounted = PackageHelper.isContainerMounted(cid);
11997            if (mounted) {
11998                // Unmount first
11999                if (PackageHelper.unMountSdDir(cid)) {
12000                    mounted = false;
12001                }
12002            }
12003            if (!mounted && delete) {
12004                cleanUpResourcesLI(allCodePaths);
12005            }
12006            return !mounted;
12007        }
12008
12009        @Override
12010        int doPreCopy() {
12011            if (isFwdLocked()) {
12012                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12013                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12014                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12015                }
12016            }
12017
12018            return PackageManager.INSTALL_SUCCEEDED;
12019        }
12020
12021        @Override
12022        int doPostCopy(int uid) {
12023            if (isFwdLocked()) {
12024                if (uid < Process.FIRST_APPLICATION_UID
12025                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12026                                RES_FILE_NAME)) {
12027                    Slog.e(TAG, "Failed to finalize " + cid);
12028                    PackageHelper.destroySdDir(cid);
12029                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12030                }
12031            }
12032
12033            return PackageManager.INSTALL_SUCCEEDED;
12034        }
12035    }
12036
12037    /**
12038     * Logic to handle movement of existing installed applications.
12039     */
12040    class MoveInstallArgs extends InstallArgs {
12041        private File codeFile;
12042        private File resourceFile;
12043
12044        /** New install */
12045        MoveInstallArgs(InstallParams params) {
12046            super(params.origin, params.move, params.observer, params.installFlags,
12047                    params.installerPackageName, params.volumeUuid,
12048                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12049                    params.grantedRuntimePermissions,
12050                    params.traceMethod, params.traceCookie);
12051        }
12052
12053        int copyApk(IMediaContainerService imcs, boolean temp) {
12054            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12055                    + move.fromUuid + " to " + move.toUuid);
12056            synchronized (mInstaller) {
12057                try {
12058                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12059                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12060                } catch (InstallerException e) {
12061                    Slog.w(TAG, "Failed to move app", e);
12062                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12063                }
12064            }
12065
12066            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12067            resourceFile = codeFile;
12068            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12069
12070            return PackageManager.INSTALL_SUCCEEDED;
12071        }
12072
12073        int doPreInstall(int status) {
12074            if (status != PackageManager.INSTALL_SUCCEEDED) {
12075                cleanUp(move.toUuid);
12076            }
12077            return status;
12078        }
12079
12080        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12081            if (status != PackageManager.INSTALL_SUCCEEDED) {
12082                cleanUp(move.toUuid);
12083                return false;
12084            }
12085
12086            // Reflect the move in app info
12087            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12088            pkg.applicationInfo.setCodePath(pkg.codePath);
12089            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12090            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12091            pkg.applicationInfo.setResourcePath(pkg.codePath);
12092            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12093            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12094
12095            return true;
12096        }
12097
12098        int doPostInstall(int status, int uid) {
12099            if (status == PackageManager.INSTALL_SUCCEEDED) {
12100                cleanUp(move.fromUuid);
12101            } else {
12102                cleanUp(move.toUuid);
12103            }
12104            return status;
12105        }
12106
12107        @Override
12108        String getCodePath() {
12109            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12110        }
12111
12112        @Override
12113        String getResourcePath() {
12114            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12115        }
12116
12117        private boolean cleanUp(String volumeUuid) {
12118            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12119                    move.dataAppName);
12120            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12121            synchronized (mInstallLock) {
12122                // Clean up both app data and code
12123                removeDataDirsLI(volumeUuid, move.packageName);
12124                removeCodePathLI(codeFile);
12125            }
12126            return true;
12127        }
12128
12129        void cleanUpResourcesLI() {
12130            throw new UnsupportedOperationException();
12131        }
12132
12133        boolean doPostDeleteLI(boolean delete) {
12134            throw new UnsupportedOperationException();
12135        }
12136    }
12137
12138    static String getAsecPackageName(String packageCid) {
12139        int idx = packageCid.lastIndexOf("-");
12140        if (idx == -1) {
12141            return packageCid;
12142        }
12143        return packageCid.substring(0, idx);
12144    }
12145
12146    // Utility method used to create code paths based on package name and available index.
12147    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12148        String idxStr = "";
12149        int idx = 1;
12150        // Fall back to default value of idx=1 if prefix is not
12151        // part of oldCodePath
12152        if (oldCodePath != null) {
12153            String subStr = oldCodePath;
12154            // Drop the suffix right away
12155            if (suffix != null && subStr.endsWith(suffix)) {
12156                subStr = subStr.substring(0, subStr.length() - suffix.length());
12157            }
12158            // If oldCodePath already contains prefix find out the
12159            // ending index to either increment or decrement.
12160            int sidx = subStr.lastIndexOf(prefix);
12161            if (sidx != -1) {
12162                subStr = subStr.substring(sidx + prefix.length());
12163                if (subStr != null) {
12164                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12165                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12166                    }
12167                    try {
12168                        idx = Integer.parseInt(subStr);
12169                        if (idx <= 1) {
12170                            idx++;
12171                        } else {
12172                            idx--;
12173                        }
12174                    } catch(NumberFormatException e) {
12175                    }
12176                }
12177            }
12178        }
12179        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12180        return prefix + idxStr;
12181    }
12182
12183    private File getNextCodePath(File targetDir, String packageName) {
12184        int suffix = 1;
12185        File result;
12186        do {
12187            result = new File(targetDir, packageName + "-" + suffix);
12188            suffix++;
12189        } while (result.exists());
12190        return result;
12191    }
12192
12193    // Utility method that returns the relative package path with respect
12194    // to the installation directory. Like say for /data/data/com.test-1.apk
12195    // string com.test-1 is returned.
12196    static String deriveCodePathName(String codePath) {
12197        if (codePath == null) {
12198            return null;
12199        }
12200        final File codeFile = new File(codePath);
12201        final String name = codeFile.getName();
12202        if (codeFile.isDirectory()) {
12203            return name;
12204        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12205            final int lastDot = name.lastIndexOf('.');
12206            return name.substring(0, lastDot);
12207        } else {
12208            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12209            return null;
12210        }
12211    }
12212
12213    static class PackageInstalledInfo {
12214        String name;
12215        int uid;
12216        // The set of users that originally had this package installed.
12217        int[] origUsers;
12218        // The set of users that now have this package installed.
12219        int[] newUsers;
12220        PackageParser.Package pkg;
12221        int returnCode;
12222        String returnMsg;
12223        PackageRemovedInfo removedInfo;
12224
12225        public void setError(int code, String msg) {
12226            returnCode = code;
12227            returnMsg = msg;
12228            Slog.w(TAG, msg);
12229        }
12230
12231        public void setError(String msg, PackageParserException e) {
12232            returnCode = e.error;
12233            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12234            Slog.w(TAG, msg, e);
12235        }
12236
12237        public void setError(String msg, PackageManagerException e) {
12238            returnCode = e.error;
12239            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12240            Slog.w(TAG, msg, e);
12241        }
12242
12243        // In some error cases we want to convey more info back to the observer
12244        String origPackage;
12245        String origPermission;
12246    }
12247
12248    /*
12249     * Install a non-existing package.
12250     */
12251    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12252            UserHandle user, String installerPackageName, String volumeUuid,
12253            PackageInstalledInfo res) {
12254        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12255
12256        // Remember this for later, in case we need to rollback this install
12257        String pkgName = pkg.packageName;
12258
12259        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12260        // TODO: b/23350563
12261        final boolean dataDirExists = Environment
12262                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12263
12264        synchronized(mPackages) {
12265            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12266                // A package with the same name is already installed, though
12267                // it has been renamed to an older name.  The package we
12268                // are trying to install should be installed as an update to
12269                // the existing one, but that has not been requested, so bail.
12270                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12271                        + " without first uninstalling package running as "
12272                        + mSettings.mRenamedPackages.get(pkgName));
12273                return;
12274            }
12275            if (mPackages.containsKey(pkgName)) {
12276                // Don't allow installation over an existing package with the same name.
12277                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12278                        + " without first uninstalling.");
12279                return;
12280            }
12281        }
12282
12283        try {
12284            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12285                    System.currentTimeMillis(), user);
12286
12287            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12288            prepareAppDataAfterInstall(newPackage);
12289
12290            // delete the partially installed application. the data directory will have to be
12291            // restored if it was already existing
12292            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12293                // remove package from internal structures.  Note that we want deletePackageX to
12294                // delete the package data and cache directories that it created in
12295                // scanPackageLocked, unless those directories existed before we even tried to
12296                // install.
12297                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12298                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12299                                res.removedInfo, true);
12300            }
12301
12302        } catch (PackageManagerException e) {
12303            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12304        }
12305
12306        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12307    }
12308
12309    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12310        // Can't rotate keys during boot or if sharedUser.
12311        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12312                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12313            return false;
12314        }
12315        // app is using upgradeKeySets; make sure all are valid
12316        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12317        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12318        for (int i = 0; i < upgradeKeySets.length; i++) {
12319            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12320                Slog.wtf(TAG, "Package "
12321                         + (oldPs.name != null ? oldPs.name : "<null>")
12322                         + " contains upgrade-key-set reference to unknown key-set: "
12323                         + upgradeKeySets[i]
12324                         + " reverting to signatures check.");
12325                return false;
12326            }
12327        }
12328        return true;
12329    }
12330
12331    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12332        // Upgrade keysets are being used.  Determine if new package has a superset of the
12333        // required keys.
12334        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12335        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12336        for (int i = 0; i < upgradeKeySets.length; i++) {
12337            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12338            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12339                return true;
12340            }
12341        }
12342        return false;
12343    }
12344
12345    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12346            UserHandle user, String installerPackageName, String volumeUuid,
12347            PackageInstalledInfo res) {
12348        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12349
12350        final PackageParser.Package oldPackage;
12351        final String pkgName = pkg.packageName;
12352        final int[] allUsers;
12353        final boolean[] perUserInstalled;
12354
12355        // First find the old package info and check signatures
12356        synchronized(mPackages) {
12357            oldPackage = mPackages.get(pkgName);
12358            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12359            if (isEphemeral && !oldIsEphemeral) {
12360                // can't downgrade from full to ephemeral
12361                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12362                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12363                return;
12364            }
12365            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12366            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12367            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12368                if(!checkUpgradeKeySetLP(ps, pkg)) {
12369                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12370                            "New package not signed by keys specified by upgrade-keysets: "
12371                            + pkgName);
12372                    return;
12373                }
12374            } else {
12375                // default to original signature matching
12376                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12377                    != PackageManager.SIGNATURE_MATCH) {
12378                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12379                            "New package has a different signature: " + pkgName);
12380                    return;
12381                }
12382            }
12383
12384            // In case of rollback, remember per-user/profile install state
12385            allUsers = sUserManager.getUserIds();
12386            perUserInstalled = new boolean[allUsers.length];
12387            for (int i = 0; i < allUsers.length; i++) {
12388                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12389            }
12390        }
12391
12392        boolean sysPkg = (isSystemApp(oldPackage));
12393        if (sysPkg) {
12394            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12395                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12396        } else {
12397            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12398                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12399        }
12400    }
12401
12402    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12403            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12404            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12405            String volumeUuid, PackageInstalledInfo res) {
12406        String pkgName = deletedPackage.packageName;
12407        boolean deletedPkg = true;
12408        boolean updatedSettings = false;
12409
12410        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12411                + deletedPackage);
12412        long origUpdateTime;
12413        if (pkg.mExtras != null) {
12414            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12415        } else {
12416            origUpdateTime = 0;
12417        }
12418
12419        // First delete the existing package while retaining the data directory
12420        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12421                res.removedInfo, true)) {
12422            // If the existing package wasn't successfully deleted
12423            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12424            deletedPkg = false;
12425        } else {
12426            // Successfully deleted the old package; proceed with replace.
12427
12428            // If deleted package lived in a container, give users a chance to
12429            // relinquish resources before killing.
12430            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12431                if (DEBUG_INSTALL) {
12432                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12433                }
12434                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12435                final ArrayList<String> pkgList = new ArrayList<String>(1);
12436                pkgList.add(deletedPackage.applicationInfo.packageName);
12437                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12438            }
12439
12440            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12441            try {
12442                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12443                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12444                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12445                        perUserInstalled, res, user);
12446                prepareAppDataAfterInstall(newPackage);
12447                updatedSettings = true;
12448            } catch (PackageManagerException e) {
12449                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12450            }
12451        }
12452
12453        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12454            // remove package from internal structures.  Note that we want deletePackageX to
12455            // delete the package data and cache directories that it created in
12456            // scanPackageLocked, unless those directories existed before we even tried to
12457            // install.
12458            if(updatedSettings) {
12459                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12460                deletePackageLI(
12461                        pkgName, null, true, allUsers, perUserInstalled,
12462                        PackageManager.DELETE_KEEP_DATA,
12463                                res.removedInfo, true);
12464            }
12465            // Since we failed to install the new package we need to restore the old
12466            // package that we deleted.
12467            if (deletedPkg) {
12468                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12469                File restoreFile = new File(deletedPackage.codePath);
12470                // Parse old package
12471                boolean oldExternal = isExternal(deletedPackage);
12472                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12473                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12474                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12475                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12476                try {
12477                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12478                            null);
12479                } catch (PackageManagerException e) {
12480                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12481                            + e.getMessage());
12482                    return;
12483                }
12484                // Restore of old package succeeded. Update permissions.
12485                // writer
12486                synchronized (mPackages) {
12487                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12488                            UPDATE_PERMISSIONS_ALL);
12489                    // can downgrade to reader
12490                    mSettings.writeLPr();
12491                }
12492                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12493            }
12494        }
12495    }
12496
12497    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12498            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12499            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12500            String volumeUuid, PackageInstalledInfo res) {
12501        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12502                + ", old=" + deletedPackage);
12503        boolean disabledSystem = false;
12504        boolean updatedSettings = false;
12505        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12506        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12507                != 0) {
12508            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12509        }
12510        String packageName = deletedPackage.packageName;
12511        if (packageName == null) {
12512            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12513                    "Attempt to delete null packageName.");
12514            return;
12515        }
12516        PackageParser.Package oldPkg;
12517        PackageSetting oldPkgSetting;
12518        // reader
12519        synchronized (mPackages) {
12520            oldPkg = mPackages.get(packageName);
12521            oldPkgSetting = mSettings.mPackages.get(packageName);
12522            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12523                    (oldPkgSetting == null)) {
12524                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12525                        "Couldn't find package " + packageName + " information");
12526                return;
12527            }
12528        }
12529
12530        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12531
12532        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12533        res.removedInfo.removedPackage = packageName;
12534        // Remove existing system package
12535        removePackageLI(oldPkgSetting, true);
12536        // writer
12537        synchronized (mPackages) {
12538            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12539            if (!disabledSystem && deletedPackage != null) {
12540                // We didn't need to disable the .apk as a current system package,
12541                // which means we are replacing another update that is already
12542                // installed.  We need to make sure to delete the older one's .apk.
12543                res.removedInfo.args = createInstallArgsForExisting(0,
12544                        deletedPackage.applicationInfo.getCodePath(),
12545                        deletedPackage.applicationInfo.getResourcePath(),
12546                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12547            } else {
12548                res.removedInfo.args = null;
12549            }
12550        }
12551
12552        // Successfully disabled the old package. Now proceed with re-installation
12553        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12554
12555        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12556        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12557
12558        PackageParser.Package newPackage = null;
12559        try {
12560            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12561            if (newPackage.mExtras != null) {
12562                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12563                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12564                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12565
12566                // is the update attempting to change shared user? that isn't going to work...
12567                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12568                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12569                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12570                            + " to " + newPkgSetting.sharedUser);
12571                    updatedSettings = true;
12572                }
12573            }
12574
12575            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12576                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12577                        perUserInstalled, res, user);
12578                prepareAppDataAfterInstall(newPackage);
12579                updatedSettings = true;
12580            }
12581
12582        } catch (PackageManagerException e) {
12583            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12584        }
12585
12586        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12587            // Re installation failed. Restore old information
12588            // Remove new pkg information
12589            if (newPackage != null) {
12590                removeInstalledPackageLI(newPackage, true);
12591            }
12592            // Add back the old system package
12593            try {
12594                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12595            } catch (PackageManagerException e) {
12596                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12597            }
12598            // Restore the old system information in Settings
12599            synchronized (mPackages) {
12600                if (disabledSystem) {
12601                    mSettings.enableSystemPackageLPw(packageName);
12602                }
12603                if (updatedSettings) {
12604                    mSettings.setInstallerPackageName(packageName,
12605                            oldPkgSetting.installerPackageName);
12606                }
12607                mSettings.writeLPr();
12608            }
12609        }
12610    }
12611
12612    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12613        // Collect all used permissions in the UID
12614        ArraySet<String> usedPermissions = new ArraySet<>();
12615        final int packageCount = su.packages.size();
12616        for (int i = 0; i < packageCount; i++) {
12617            PackageSetting ps = su.packages.valueAt(i);
12618            if (ps.pkg == null) {
12619                continue;
12620            }
12621            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12622            for (int j = 0; j < requestedPermCount; j++) {
12623                String permission = ps.pkg.requestedPermissions.get(j);
12624                BasePermission bp = mSettings.mPermissions.get(permission);
12625                if (bp != null) {
12626                    usedPermissions.add(permission);
12627                }
12628            }
12629        }
12630
12631        PermissionsState permissionsState = su.getPermissionsState();
12632        // Prune install permissions
12633        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12634        final int installPermCount = installPermStates.size();
12635        for (int i = installPermCount - 1; i >= 0;  i--) {
12636            PermissionState permissionState = installPermStates.get(i);
12637            if (!usedPermissions.contains(permissionState.getName())) {
12638                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12639                if (bp != null) {
12640                    permissionsState.revokeInstallPermission(bp);
12641                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12642                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12643                }
12644            }
12645        }
12646
12647        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12648
12649        // Prune runtime permissions
12650        for (int userId : allUserIds) {
12651            List<PermissionState> runtimePermStates = permissionsState
12652                    .getRuntimePermissionStates(userId);
12653            final int runtimePermCount = runtimePermStates.size();
12654            for (int i = runtimePermCount - 1; i >= 0; i--) {
12655                PermissionState permissionState = runtimePermStates.get(i);
12656                if (!usedPermissions.contains(permissionState.getName())) {
12657                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12658                    if (bp != null) {
12659                        permissionsState.revokeRuntimePermission(bp, userId);
12660                        permissionsState.updatePermissionFlags(bp, userId,
12661                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12662                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12663                                runtimePermissionChangedUserIds, userId);
12664                    }
12665                }
12666            }
12667        }
12668
12669        return runtimePermissionChangedUserIds;
12670    }
12671
12672    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12673            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12674            UserHandle user) {
12675        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12676
12677        String pkgName = newPackage.packageName;
12678        synchronized (mPackages) {
12679            //write settings. the installStatus will be incomplete at this stage.
12680            //note that the new package setting would have already been
12681            //added to mPackages. It hasn't been persisted yet.
12682            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12683            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12684            mSettings.writeLPr();
12685            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12686        }
12687
12688        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12689        synchronized (mPackages) {
12690            updatePermissionsLPw(newPackage.packageName, newPackage,
12691                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12692                            ? UPDATE_PERMISSIONS_ALL : 0));
12693            // For system-bundled packages, we assume that installing an upgraded version
12694            // of the package implies that the user actually wants to run that new code,
12695            // so we enable the package.
12696            PackageSetting ps = mSettings.mPackages.get(pkgName);
12697            if (ps != null) {
12698                if (isSystemApp(newPackage)) {
12699                    // NB: implicit assumption that system package upgrades apply to all users
12700                    if (DEBUG_INSTALL) {
12701                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12702                    }
12703                    if (res.origUsers != null) {
12704                        for (int userHandle : res.origUsers) {
12705                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12706                                    userHandle, installerPackageName);
12707                        }
12708                    }
12709                    // Also convey the prior install/uninstall state
12710                    if (allUsers != null && perUserInstalled != null) {
12711                        for (int i = 0; i < allUsers.length; i++) {
12712                            if (DEBUG_INSTALL) {
12713                                Slog.d(TAG, "    user " + allUsers[i]
12714                                        + " => " + perUserInstalled[i]);
12715                            }
12716                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12717                        }
12718                        // these install state changes will be persisted in the
12719                        // upcoming call to mSettings.writeLPr().
12720                    }
12721                }
12722                // It's implied that when a user requests installation, they want the app to be
12723                // installed and enabled.
12724                int userId = user.getIdentifier();
12725                if (userId != UserHandle.USER_ALL) {
12726                    ps.setInstalled(true, userId);
12727                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12728                }
12729            }
12730            res.name = pkgName;
12731            res.uid = newPackage.applicationInfo.uid;
12732            res.pkg = newPackage;
12733            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12734            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12735            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12736            //to update install status
12737            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12738            mSettings.writeLPr();
12739            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12740        }
12741
12742        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12743    }
12744
12745    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12746        try {
12747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12748            installPackageLI(args, res);
12749        } finally {
12750            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12751        }
12752    }
12753
12754    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12755        final int installFlags = args.installFlags;
12756        final String installerPackageName = args.installerPackageName;
12757        final String volumeUuid = args.volumeUuid;
12758        final File tmpPackageFile = new File(args.getCodePath());
12759        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12760        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12761                || (args.volumeUuid != null));
12762        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12763        boolean replace = false;
12764        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12765        if (args.move != null) {
12766            // moving a complete application; perfom an initial scan on the new install location
12767            scanFlags |= SCAN_INITIAL;
12768        }
12769        // Result object to be returned
12770        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12771
12772        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12773
12774        // Sanity check
12775        if (ephemeral && (forwardLocked || onExternal)) {
12776            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12777                    + " external=" + onExternal);
12778            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12779            return;
12780        }
12781
12782        // Retrieve PackageSettings and parse package
12783        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12784                | PackageParser.PARSE_ENFORCE_CODE
12785                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12786                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12787                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12788        PackageParser pp = new PackageParser();
12789        pp.setSeparateProcesses(mSeparateProcesses);
12790        pp.setDisplayMetrics(mMetrics);
12791
12792        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12793        final PackageParser.Package pkg;
12794        try {
12795            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12796        } catch (PackageParserException e) {
12797            res.setError("Failed parse during installPackageLI", e);
12798            return;
12799        } finally {
12800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12801        }
12802
12803        // Mark that we have an install time CPU ABI override.
12804        pkg.cpuAbiOverride = args.abiOverride;
12805
12806        String pkgName = res.name = pkg.packageName;
12807        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12808            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12809                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12810                return;
12811            }
12812        }
12813
12814        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12815        try {
12816            pp.collectCertificates(pkg, parseFlags);
12817        } catch (PackageParserException e) {
12818            res.setError("Failed collect during installPackageLI", e);
12819            return;
12820        } finally {
12821            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12822        }
12823
12824        // Get rid of all references to package scan path via parser.
12825        pp = null;
12826        String oldCodePath = null;
12827        boolean systemApp = false;
12828        synchronized (mPackages) {
12829            // Check if installing already existing package
12830            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12831                String oldName = mSettings.mRenamedPackages.get(pkgName);
12832                if (pkg.mOriginalPackages != null
12833                        && pkg.mOriginalPackages.contains(oldName)
12834                        && mPackages.containsKey(oldName)) {
12835                    // This package is derived from an original package,
12836                    // and this device has been updating from that original
12837                    // name.  We must continue using the original name, so
12838                    // rename the new package here.
12839                    pkg.setPackageName(oldName);
12840                    pkgName = pkg.packageName;
12841                    replace = true;
12842                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12843                            + oldName + " pkgName=" + pkgName);
12844                } else if (mPackages.containsKey(pkgName)) {
12845                    // This package, under its official name, already exists
12846                    // on the device; we should replace it.
12847                    replace = true;
12848                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12849                }
12850
12851                // Prevent apps opting out from runtime permissions
12852                if (replace) {
12853                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12854                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12855                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12856                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12857                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12858                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12859                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12860                                        + " doesn't support runtime permissions but the old"
12861                                        + " target SDK " + oldTargetSdk + " does.");
12862                        return;
12863                    }
12864                }
12865            }
12866
12867            PackageSetting ps = mSettings.mPackages.get(pkgName);
12868            if (ps != null) {
12869                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12870
12871                // Quick sanity check that we're signed correctly if updating;
12872                // we'll check this again later when scanning, but we want to
12873                // bail early here before tripping over redefined permissions.
12874                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12875                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12876                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12877                                + pkg.packageName + " upgrade keys do not match the "
12878                                + "previously installed version");
12879                        return;
12880                    }
12881                } else {
12882                    try {
12883                        verifySignaturesLP(ps, pkg);
12884                    } catch (PackageManagerException e) {
12885                        res.setError(e.error, e.getMessage());
12886                        return;
12887                    }
12888                }
12889
12890                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12891                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12892                    systemApp = (ps.pkg.applicationInfo.flags &
12893                            ApplicationInfo.FLAG_SYSTEM) != 0;
12894                }
12895                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12896            }
12897
12898            // Check whether the newly-scanned package wants to define an already-defined perm
12899            int N = pkg.permissions.size();
12900            for (int i = N-1; i >= 0; i--) {
12901                PackageParser.Permission perm = pkg.permissions.get(i);
12902                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12903                if (bp != null) {
12904                    // If the defining package is signed with our cert, it's okay.  This
12905                    // also includes the "updating the same package" case, of course.
12906                    // "updating same package" could also involve key-rotation.
12907                    final boolean sigsOk;
12908                    if (bp.sourcePackage.equals(pkg.packageName)
12909                            && (bp.packageSetting instanceof PackageSetting)
12910                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12911                                    scanFlags))) {
12912                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12913                    } else {
12914                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12915                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12916                    }
12917                    if (!sigsOk) {
12918                        // If the owning package is the system itself, we log but allow
12919                        // install to proceed; we fail the install on all other permission
12920                        // redefinitions.
12921                        if (!bp.sourcePackage.equals("android")) {
12922                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12923                                    + pkg.packageName + " attempting to redeclare permission "
12924                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12925                            res.origPermission = perm.info.name;
12926                            res.origPackage = bp.sourcePackage;
12927                            return;
12928                        } else {
12929                            Slog.w(TAG, "Package " + pkg.packageName
12930                                    + " attempting to redeclare system permission "
12931                                    + perm.info.name + "; ignoring new declaration");
12932                            pkg.permissions.remove(i);
12933                        }
12934                    }
12935                }
12936            }
12937
12938        }
12939
12940        if (systemApp) {
12941            if (onExternal) {
12942                // Abort update; system app can't be replaced with app on sdcard
12943                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12944                        "Cannot install updates to system apps on sdcard");
12945                return;
12946            } else if (ephemeral) {
12947                // Abort update; system app can't be replaced with an ephemeral app
12948                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12949                        "Cannot update a system app with an ephemeral app");
12950                return;
12951            }
12952        }
12953
12954        if (args.move != null) {
12955            // We did an in-place move, so dex is ready to roll
12956            scanFlags |= SCAN_NO_DEX;
12957            scanFlags |= SCAN_MOVE;
12958
12959            synchronized (mPackages) {
12960                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12961                if (ps == null) {
12962                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12963                            "Missing settings for moved package " + pkgName);
12964                }
12965
12966                // We moved the entire application as-is, so bring over the
12967                // previously derived ABI information.
12968                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12969                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12970            }
12971
12972        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12973            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12974            scanFlags |= SCAN_NO_DEX;
12975
12976            try {
12977                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12978                        true /* extract libs */);
12979            } catch (PackageManagerException pme) {
12980                Slog.e(TAG, "Error deriving application ABI", pme);
12981                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12982                return;
12983            }
12984        }
12985
12986        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12987            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12988            return;
12989        }
12990
12991        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12992
12993        if (replace) {
12994            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12995                    installerPackageName, volumeUuid, res);
12996        } else {
12997            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12998                    args.user, installerPackageName, volumeUuid, res);
12999        }
13000        synchronized (mPackages) {
13001            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13002            if (ps != null) {
13003                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13004            }
13005        }
13006    }
13007
13008    private void startIntentFilterVerifications(int userId, boolean replacing,
13009            PackageParser.Package pkg) {
13010        if (mIntentFilterVerifierComponent == null) {
13011            Slog.w(TAG, "No IntentFilter verification will not be done as "
13012                    + "there is no IntentFilterVerifier available!");
13013            return;
13014        }
13015
13016        final int verifierUid = getPackageUid(
13017                mIntentFilterVerifierComponent.getPackageName(),
13018                MATCH_DEBUG_TRIAGED_MISSING,
13019                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13020
13021        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13022        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13023        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13024        mHandler.sendMessage(msg);
13025    }
13026
13027    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13028            PackageParser.Package pkg) {
13029        int size = pkg.activities.size();
13030        if (size == 0) {
13031            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13032                    "No activity, so no need to verify any IntentFilter!");
13033            return;
13034        }
13035
13036        final boolean hasDomainURLs = hasDomainURLs(pkg);
13037        if (!hasDomainURLs) {
13038            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13039                    "No domain URLs, so no need to verify any IntentFilter!");
13040            return;
13041        }
13042
13043        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13044                + " if any IntentFilter from the " + size
13045                + " Activities needs verification ...");
13046
13047        int count = 0;
13048        final String packageName = pkg.packageName;
13049
13050        synchronized (mPackages) {
13051            // If this is a new install and we see that we've already run verification for this
13052            // package, we have nothing to do: it means the state was restored from backup.
13053            if (!replacing) {
13054                IntentFilterVerificationInfo ivi =
13055                        mSettings.getIntentFilterVerificationLPr(packageName);
13056                if (ivi != null) {
13057                    if (DEBUG_DOMAIN_VERIFICATION) {
13058                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13059                                + ivi.getStatusString());
13060                    }
13061                    return;
13062                }
13063            }
13064
13065            // If any filters need to be verified, then all need to be.
13066            boolean needToVerify = false;
13067            for (PackageParser.Activity a : pkg.activities) {
13068                for (ActivityIntentInfo filter : a.intents) {
13069                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13070                        if (DEBUG_DOMAIN_VERIFICATION) {
13071                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13072                        }
13073                        needToVerify = true;
13074                        break;
13075                    }
13076                }
13077            }
13078
13079            if (needToVerify) {
13080                final int verificationId = mIntentFilterVerificationToken++;
13081                for (PackageParser.Activity a : pkg.activities) {
13082                    for (ActivityIntentInfo filter : a.intents) {
13083                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13084                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13085                                    "Verification needed for IntentFilter:" + filter.toString());
13086                            mIntentFilterVerifier.addOneIntentFilterVerification(
13087                                    verifierUid, userId, verificationId, filter, packageName);
13088                            count++;
13089                        }
13090                    }
13091                }
13092            }
13093        }
13094
13095        if (count > 0) {
13096            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13097                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13098                    +  " for userId:" + userId);
13099            mIntentFilterVerifier.startVerifications(userId);
13100        } else {
13101            if (DEBUG_DOMAIN_VERIFICATION) {
13102                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13103            }
13104        }
13105    }
13106
13107    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13108        final ComponentName cn  = filter.activity.getComponentName();
13109        final String packageName = cn.getPackageName();
13110
13111        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13112                packageName);
13113        if (ivi == null) {
13114            return true;
13115        }
13116        int status = ivi.getStatus();
13117        switch (status) {
13118            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13119            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13120                return true;
13121
13122            default:
13123                // Nothing to do
13124                return false;
13125        }
13126    }
13127
13128    private static boolean isMultiArch(ApplicationInfo info) {
13129        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13130    }
13131
13132    private static boolean isExternal(PackageParser.Package pkg) {
13133        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13134    }
13135
13136    private static boolean isExternal(PackageSetting ps) {
13137        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13138    }
13139
13140    private static boolean isEphemeral(PackageParser.Package pkg) {
13141        return pkg.applicationInfo.isEphemeralApp();
13142    }
13143
13144    private static boolean isEphemeral(PackageSetting ps) {
13145        return ps.pkg != null && isEphemeral(ps.pkg);
13146    }
13147
13148    private static boolean isSystemApp(PackageParser.Package pkg) {
13149        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13150    }
13151
13152    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13153        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13154    }
13155
13156    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13157        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13158    }
13159
13160    private static boolean isSystemApp(PackageSetting ps) {
13161        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13162    }
13163
13164    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13165        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13166    }
13167
13168    private int packageFlagsToInstallFlags(PackageSetting ps) {
13169        int installFlags = 0;
13170        if (isEphemeral(ps)) {
13171            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13172        }
13173        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13174            // This existing package was an external ASEC install when we have
13175            // the external flag without a UUID
13176            installFlags |= PackageManager.INSTALL_EXTERNAL;
13177        }
13178        if (ps.isForwardLocked()) {
13179            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13180        }
13181        return installFlags;
13182    }
13183
13184    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13185        if (isExternal(pkg)) {
13186            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13187                return StorageManager.UUID_PRIMARY_PHYSICAL;
13188            } else {
13189                return pkg.volumeUuid;
13190            }
13191        } else {
13192            return StorageManager.UUID_PRIVATE_INTERNAL;
13193        }
13194    }
13195
13196    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13197        if (isExternal(pkg)) {
13198            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13199                return mSettings.getExternalVersion();
13200            } else {
13201                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13202            }
13203        } else {
13204            return mSettings.getInternalVersion();
13205        }
13206    }
13207
13208    private void deleteTempPackageFiles() {
13209        final FilenameFilter filter = new FilenameFilter() {
13210            public boolean accept(File dir, String name) {
13211                return name.startsWith("vmdl") && name.endsWith(".tmp");
13212            }
13213        };
13214        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13215            file.delete();
13216        }
13217    }
13218
13219    @Override
13220    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13221            int flags) {
13222        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13223                flags);
13224    }
13225
13226    @Override
13227    public void deletePackage(final String packageName,
13228            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13229        mContext.enforceCallingOrSelfPermission(
13230                android.Manifest.permission.DELETE_PACKAGES, null);
13231        Preconditions.checkNotNull(packageName);
13232        Preconditions.checkNotNull(observer);
13233        final int uid = Binder.getCallingUid();
13234        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13235        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13236        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13237            mContext.enforceCallingOrSelfPermission(
13238                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13239                    "deletePackage for user " + userId);
13240        }
13241
13242        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13243            try {
13244                observer.onPackageDeleted(packageName,
13245                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13246            } catch (RemoteException re) {
13247            }
13248            return;
13249        }
13250
13251        for (int currentUserId : users) {
13252            if (getBlockUninstallForUser(packageName, currentUserId)) {
13253                try {
13254                    observer.onPackageDeleted(packageName,
13255                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13256                } catch (RemoteException re) {
13257                }
13258                return;
13259            }
13260        }
13261
13262        if (DEBUG_REMOVE) {
13263            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13264        }
13265        // Queue up an async operation since the package deletion may take a little while.
13266        mHandler.post(new Runnable() {
13267            public void run() {
13268                mHandler.removeCallbacks(this);
13269                final int returnCode = deletePackageX(packageName, userId, flags);
13270                try {
13271                    observer.onPackageDeleted(packageName, returnCode, null);
13272                } catch (RemoteException e) {
13273                    Log.i(TAG, "Observer no longer exists.");
13274                } //end catch
13275            } //end run
13276        });
13277    }
13278
13279    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13280        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13281                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13282        try {
13283            if (dpm != null) {
13284                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13285                        /* callingUserOnly =*/ false);
13286                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13287                        : deviceOwnerComponentName.getPackageName();
13288                // Does the package contains the device owner?
13289                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13290                // this check is probably not needed, since DO should be registered as a device
13291                // admin on some user too. (Original bug for this: b/17657954)
13292                if (packageName.equals(deviceOwnerPackageName)) {
13293                    return true;
13294                }
13295                // Does it contain a device admin for any user?
13296                int[] users;
13297                if (userId == UserHandle.USER_ALL) {
13298                    users = sUserManager.getUserIds();
13299                } else {
13300                    users = new int[]{userId};
13301                }
13302                for (int i = 0; i < users.length; ++i) {
13303                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13304                        return true;
13305                    }
13306                }
13307            }
13308        } catch (RemoteException e) {
13309        }
13310        return false;
13311    }
13312
13313    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13314        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13315    }
13316
13317    /**
13318     *  This method is an internal method that could be get invoked either
13319     *  to delete an installed package or to clean up a failed installation.
13320     *  After deleting an installed package, a broadcast is sent to notify any
13321     *  listeners that the package has been installed. For cleaning up a failed
13322     *  installation, the broadcast is not necessary since the package's
13323     *  installation wouldn't have sent the initial broadcast either
13324     *  The key steps in deleting a package are
13325     *  deleting the package information in internal structures like mPackages,
13326     *  deleting the packages base directories through installd
13327     *  updating mSettings to reflect current status
13328     *  persisting settings for later use
13329     *  sending a broadcast if necessary
13330     */
13331    private int deletePackageX(String packageName, int userId, int flags) {
13332        final PackageRemovedInfo info = new PackageRemovedInfo();
13333        final boolean res;
13334
13335        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13336                ? UserHandle.ALL : new UserHandle(userId);
13337
13338        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13339            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13340            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13341        }
13342
13343        boolean removedForAllUsers = false;
13344        boolean systemUpdate = false;
13345
13346        PackageParser.Package uninstalledPkg;
13347
13348        // for the uninstall-updates case and restricted profiles, remember the per-
13349        // userhandle installed state
13350        int[] allUsers;
13351        boolean[] perUserInstalled;
13352        synchronized (mPackages) {
13353            uninstalledPkg = mPackages.get(packageName);
13354            PackageSetting ps = mSettings.mPackages.get(packageName);
13355            allUsers = sUserManager.getUserIds();
13356            perUserInstalled = new boolean[allUsers.length];
13357            for (int i = 0; i < allUsers.length; i++) {
13358                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13359            }
13360        }
13361
13362        synchronized (mInstallLock) {
13363            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13364            res = deletePackageLI(packageName, removeForUser,
13365                    true, allUsers, perUserInstalled,
13366                    flags | REMOVE_CHATTY, info, true);
13367            systemUpdate = info.isRemovedPackageSystemUpdate;
13368            synchronized (mPackages) {
13369                if (res) {
13370                    if (!systemUpdate && mPackages.get(packageName) == null) {
13371                        removedForAllUsers = true;
13372                    }
13373                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13374                }
13375            }
13376            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13377                    + " removedForAllUsers=" + removedForAllUsers);
13378        }
13379
13380        if (res) {
13381            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13382
13383            // If the removed package was a system update, the old system package
13384            // was re-enabled; we need to broadcast this information
13385            if (systemUpdate) {
13386                Bundle extras = new Bundle(1);
13387                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13388                        ? info.removedAppId : info.uid);
13389                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13390
13391                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13392                        extras, 0, null, null, null);
13393                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13394                        extras, 0, null, null, null);
13395                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13396                        null, 0, packageName, null, null);
13397            }
13398        }
13399        // Force a gc here.
13400        Runtime.getRuntime().gc();
13401        // Delete the resources here after sending the broadcast to let
13402        // other processes clean up before deleting resources.
13403        if (info.args != null) {
13404            synchronized (mInstallLock) {
13405                info.args.doPostDeleteLI(true);
13406            }
13407        }
13408
13409        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13410    }
13411
13412    class PackageRemovedInfo {
13413        String removedPackage;
13414        int uid = -1;
13415        int removedAppId = -1;
13416        int[] removedUsers = null;
13417        boolean isRemovedPackageSystemUpdate = false;
13418        // Clean up resources deleted packages.
13419        InstallArgs args = null;
13420
13421        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13422            Bundle extras = new Bundle(1);
13423            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13424            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13425            if (replacing) {
13426                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13427            }
13428            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13429            if (removedPackage != null) {
13430                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13431                        extras, 0, null, null, removedUsers);
13432                if (fullRemove && !replacing) {
13433                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13434                            extras, 0, null, null, removedUsers);
13435                }
13436            }
13437            if (removedAppId >= 0) {
13438                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13439                        removedUsers);
13440            }
13441        }
13442    }
13443
13444    /*
13445     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13446     * flag is not set, the data directory is removed as well.
13447     * make sure this flag is set for partially installed apps. If not its meaningless to
13448     * delete a partially installed application.
13449     */
13450    private void removePackageDataLI(PackageSetting ps,
13451            int[] allUserHandles, boolean[] perUserInstalled,
13452            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13453        String packageName = ps.name;
13454        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13455        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13456        // Retrieve object to delete permissions for shared user later on
13457        final PackageSetting deletedPs;
13458        // reader
13459        synchronized (mPackages) {
13460            deletedPs = mSettings.mPackages.get(packageName);
13461            if (outInfo != null) {
13462                outInfo.removedPackage = packageName;
13463                outInfo.removedUsers = deletedPs != null
13464                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13465                        : null;
13466            }
13467        }
13468        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13469            removeDataDirsLI(ps.volumeUuid, packageName);
13470            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13471        }
13472        // writer
13473        synchronized (mPackages) {
13474            if (deletedPs != null) {
13475                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13476                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13477                    clearDefaultBrowserIfNeeded(packageName);
13478                    if (outInfo != null) {
13479                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13480                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13481                    }
13482                    updatePermissionsLPw(deletedPs.name, null, 0);
13483                    if (deletedPs.sharedUser != null) {
13484                        // Remove permissions associated with package. Since runtime
13485                        // permissions are per user we have to kill the removed package
13486                        // or packages running under the shared user of the removed
13487                        // package if revoking the permissions requested only by the removed
13488                        // package is successful and this causes a change in gids.
13489                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13490                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13491                                    userId);
13492                            if (userIdToKill == UserHandle.USER_ALL
13493                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13494                                // If gids changed for this user, kill all affected packages.
13495                                mHandler.post(new Runnable() {
13496                                    @Override
13497                                    public void run() {
13498                                        // This has to happen with no lock held.
13499                                        killApplication(deletedPs.name, deletedPs.appId,
13500                                                KILL_APP_REASON_GIDS_CHANGED);
13501                                    }
13502                                });
13503                                break;
13504                            }
13505                        }
13506                    }
13507                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13508                }
13509                // make sure to preserve per-user disabled state if this removal was just
13510                // a downgrade of a system app to the factory package
13511                if (allUserHandles != null && perUserInstalled != null) {
13512                    if (DEBUG_REMOVE) {
13513                        Slog.d(TAG, "Propagating install state across downgrade");
13514                    }
13515                    for (int i = 0; i < allUserHandles.length; i++) {
13516                        if (DEBUG_REMOVE) {
13517                            Slog.d(TAG, "    user " + allUserHandles[i]
13518                                    + " => " + perUserInstalled[i]);
13519                        }
13520                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13521                    }
13522                }
13523            }
13524            // can downgrade to reader
13525            if (writeSettings) {
13526                // Save settings now
13527                mSettings.writeLPr();
13528            }
13529        }
13530        if (outInfo != null) {
13531            // A user ID was deleted here. Go through all users and remove it
13532            // from KeyStore.
13533            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13534        }
13535    }
13536
13537    static boolean locationIsPrivileged(File path) {
13538        try {
13539            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13540                    .getCanonicalPath();
13541            return path.getCanonicalPath().startsWith(privilegedAppDir);
13542        } catch (IOException e) {
13543            Slog.e(TAG, "Unable to access code path " + path);
13544        }
13545        return false;
13546    }
13547
13548    /*
13549     * Tries to delete system package.
13550     */
13551    private boolean deleteSystemPackageLI(PackageSetting newPs,
13552            int[] allUserHandles, boolean[] perUserInstalled,
13553            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13554        final boolean applyUserRestrictions
13555                = (allUserHandles != null) && (perUserInstalled != null);
13556        PackageSetting disabledPs = null;
13557        // Confirm if the system package has been updated
13558        // An updated system app can be deleted. This will also have to restore
13559        // the system pkg from system partition
13560        // reader
13561        synchronized (mPackages) {
13562            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13563        }
13564        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13565                + " disabledPs=" + disabledPs);
13566        if (disabledPs == null) {
13567            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13568            return false;
13569        } else if (DEBUG_REMOVE) {
13570            Slog.d(TAG, "Deleting system pkg from data partition");
13571        }
13572        if (DEBUG_REMOVE) {
13573            if (applyUserRestrictions) {
13574                Slog.d(TAG, "Remembering install states:");
13575                for (int i = 0; i < allUserHandles.length; i++) {
13576                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13577                }
13578            }
13579        }
13580        // Delete the updated package
13581        outInfo.isRemovedPackageSystemUpdate = true;
13582        if (disabledPs.versionCode < newPs.versionCode) {
13583            // Delete data for downgrades
13584            flags &= ~PackageManager.DELETE_KEEP_DATA;
13585        } else {
13586            // Preserve data by setting flag
13587            flags |= PackageManager.DELETE_KEEP_DATA;
13588        }
13589        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13590                allUserHandles, perUserInstalled, outInfo, writeSettings);
13591        if (!ret) {
13592            return false;
13593        }
13594        // writer
13595        synchronized (mPackages) {
13596            // Reinstate the old system package
13597            mSettings.enableSystemPackageLPw(newPs.name);
13598            // Remove any native libraries from the upgraded package.
13599            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13600        }
13601        // Install the system package
13602        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13603        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13604        if (locationIsPrivileged(disabledPs.codePath)) {
13605            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13606        }
13607
13608        final PackageParser.Package newPkg;
13609        try {
13610            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13611        } catch (PackageManagerException e) {
13612            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13613            return false;
13614        }
13615
13616        prepareAppDataAfterInstall(newPkg);
13617
13618        // writer
13619        synchronized (mPackages) {
13620            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13621
13622            // Propagate the permissions state as we do not want to drop on the floor
13623            // runtime permissions. The update permissions method below will take
13624            // care of removing obsolete permissions and grant install permissions.
13625            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13626            updatePermissionsLPw(newPkg.packageName, newPkg,
13627                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13628
13629            if (applyUserRestrictions) {
13630                if (DEBUG_REMOVE) {
13631                    Slog.d(TAG, "Propagating install state across reinstall");
13632                }
13633                for (int i = 0; i < allUserHandles.length; i++) {
13634                    if (DEBUG_REMOVE) {
13635                        Slog.d(TAG, "    user " + allUserHandles[i]
13636                                + " => " + perUserInstalled[i]);
13637                    }
13638                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13639
13640                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13641                }
13642                // Regardless of writeSettings we need to ensure that this restriction
13643                // state propagation is persisted
13644                mSettings.writeAllUsersPackageRestrictionsLPr();
13645            }
13646            // can downgrade to reader here
13647            if (writeSettings) {
13648                mSettings.writeLPr();
13649            }
13650        }
13651        return true;
13652    }
13653
13654    private boolean deleteInstalledPackageLI(PackageSetting ps,
13655            boolean deleteCodeAndResources, int flags,
13656            int[] allUserHandles, boolean[] perUserInstalled,
13657            PackageRemovedInfo outInfo, boolean writeSettings) {
13658        if (outInfo != null) {
13659            outInfo.uid = ps.appId;
13660        }
13661
13662        // Delete package data from internal structures and also remove data if flag is set
13663        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13664
13665        // Delete application code and resources
13666        if (deleteCodeAndResources && (outInfo != null)) {
13667            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13668                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13669            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13670        }
13671        return true;
13672    }
13673
13674    @Override
13675    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13676            int userId) {
13677        mContext.enforceCallingOrSelfPermission(
13678                android.Manifest.permission.DELETE_PACKAGES, null);
13679        synchronized (mPackages) {
13680            PackageSetting ps = mSettings.mPackages.get(packageName);
13681            if (ps == null) {
13682                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13683                return false;
13684            }
13685            if (!ps.getInstalled(userId)) {
13686                // Can't block uninstall for an app that is not installed or enabled.
13687                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13688                return false;
13689            }
13690            ps.setBlockUninstall(blockUninstall, userId);
13691            mSettings.writePackageRestrictionsLPr(userId);
13692        }
13693        return true;
13694    }
13695
13696    @Override
13697    public boolean getBlockUninstallForUser(String packageName, int userId) {
13698        synchronized (mPackages) {
13699            PackageSetting ps = mSettings.mPackages.get(packageName);
13700            if (ps == null) {
13701                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13702                return false;
13703            }
13704            return ps.getBlockUninstall(userId);
13705        }
13706    }
13707
13708    @Override
13709    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13710        int callingUid = Binder.getCallingUid();
13711        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13712            throw new SecurityException(
13713                    "setRequiredForSystemUser can only be run by the system or root");
13714        }
13715        synchronized (mPackages) {
13716            PackageSetting ps = mSettings.mPackages.get(packageName);
13717            if (ps == null) {
13718                Log.w(TAG, "Package doesn't exist: " + packageName);
13719                return false;
13720            }
13721            if (systemUserApp) {
13722                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13723            } else {
13724                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13725            }
13726            mSettings.writeLPr();
13727        }
13728        return true;
13729    }
13730
13731    /*
13732     * This method handles package deletion in general
13733     */
13734    private boolean deletePackageLI(String packageName, UserHandle user,
13735            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13736            int flags, PackageRemovedInfo outInfo,
13737            boolean writeSettings) {
13738        if (packageName == null) {
13739            Slog.w(TAG, "Attempt to delete null packageName.");
13740            return false;
13741        }
13742        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13743        PackageSetting ps;
13744        boolean dataOnly = false;
13745        int removeUser = -1;
13746        int appId = -1;
13747        synchronized (mPackages) {
13748            ps = mSettings.mPackages.get(packageName);
13749            if (ps == null) {
13750                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13751                return false;
13752            }
13753            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13754                    && user.getIdentifier() != UserHandle.USER_ALL) {
13755                // The caller is asking that the package only be deleted for a single
13756                // user.  To do this, we just mark its uninstalled state and delete
13757                // its data.  If this is a system app, we only allow this to happen if
13758                // they have set the special DELETE_SYSTEM_APP which requests different
13759                // semantics than normal for uninstalling system apps.
13760                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13761                final int userId = user.getIdentifier();
13762                ps.setUserState(userId,
13763                        COMPONENT_ENABLED_STATE_DEFAULT,
13764                        false, //installed
13765                        true,  //stopped
13766                        true,  //notLaunched
13767                        false, //hidden
13768                        false, //suspended
13769                        null, null, null,
13770                        false, // blockUninstall
13771                        ps.readUserState(userId).domainVerificationStatus, 0);
13772                if (!isSystemApp(ps)) {
13773                    // Do not uninstall the APK if an app should be cached
13774                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13775                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13776                        // Other user still have this package installed, so all
13777                        // we need to do is clear this user's data and save that
13778                        // it is uninstalled.
13779                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13780                        removeUser = user.getIdentifier();
13781                        appId = ps.appId;
13782                        scheduleWritePackageRestrictionsLocked(removeUser);
13783                    } else {
13784                        // We need to set it back to 'installed' so the uninstall
13785                        // broadcasts will be sent correctly.
13786                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13787                        ps.setInstalled(true, user.getIdentifier());
13788                    }
13789                } else {
13790                    // This is a system app, so we assume that the
13791                    // other users still have this package installed, so all
13792                    // we need to do is clear this user's data and save that
13793                    // it is uninstalled.
13794                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13795                    removeUser = user.getIdentifier();
13796                    appId = ps.appId;
13797                    scheduleWritePackageRestrictionsLocked(removeUser);
13798                }
13799            }
13800        }
13801
13802        if (removeUser >= 0) {
13803            // From above, we determined that we are deleting this only
13804            // for a single user.  Continue the work here.
13805            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13806            if (outInfo != null) {
13807                outInfo.removedPackage = packageName;
13808                outInfo.removedAppId = appId;
13809                outInfo.removedUsers = new int[] {removeUser};
13810            }
13811            // TODO: triage flags as part of 26466827
13812            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13813            try {
13814                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13815            } catch (InstallerException e) {
13816                Slog.w(TAG, "Failed to delete app data", e);
13817            }
13818            removeKeystoreDataIfNeeded(removeUser, appId);
13819            schedulePackageCleaning(packageName, removeUser, false);
13820            synchronized (mPackages) {
13821                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13822                    scheduleWritePackageRestrictionsLocked(removeUser);
13823                }
13824                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13825            }
13826            return true;
13827        }
13828
13829        if (dataOnly) {
13830            // Delete application data first
13831            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13832            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13833            return true;
13834        }
13835
13836        boolean ret = false;
13837        if (isSystemApp(ps)) {
13838            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13839            // When an updated system application is deleted we delete the existing resources as well and
13840            // fall back to existing code in system partition
13841            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13842                    flags, outInfo, writeSettings);
13843        } else {
13844            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13845            // Kill application pre-emptively especially for apps on sd.
13846            killApplication(packageName, ps.appId, "uninstall pkg");
13847            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13848                    allUserHandles, perUserInstalled,
13849                    outInfo, writeSettings);
13850        }
13851
13852        return ret;
13853    }
13854
13855    private final static class ClearStorageConnection implements ServiceConnection {
13856        IMediaContainerService mContainerService;
13857
13858        @Override
13859        public void onServiceConnected(ComponentName name, IBinder service) {
13860            synchronized (this) {
13861                mContainerService = IMediaContainerService.Stub.asInterface(service);
13862                notifyAll();
13863            }
13864        }
13865
13866        @Override
13867        public void onServiceDisconnected(ComponentName name) {
13868        }
13869    }
13870
13871    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13872        final boolean mounted;
13873        if (Environment.isExternalStorageEmulated()) {
13874            mounted = true;
13875        } else {
13876            final String status = Environment.getExternalStorageState();
13877
13878            mounted = status.equals(Environment.MEDIA_MOUNTED)
13879                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13880        }
13881
13882        if (!mounted) {
13883            return;
13884        }
13885
13886        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13887        int[] users;
13888        if (userId == UserHandle.USER_ALL) {
13889            users = sUserManager.getUserIds();
13890        } else {
13891            users = new int[] { userId };
13892        }
13893        final ClearStorageConnection conn = new ClearStorageConnection();
13894        if (mContext.bindServiceAsUser(
13895                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13896            try {
13897                for (int curUser : users) {
13898                    long timeout = SystemClock.uptimeMillis() + 5000;
13899                    synchronized (conn) {
13900                        long now = SystemClock.uptimeMillis();
13901                        while (conn.mContainerService == null && now < timeout) {
13902                            try {
13903                                conn.wait(timeout - now);
13904                            } catch (InterruptedException e) {
13905                            }
13906                        }
13907                    }
13908                    if (conn.mContainerService == null) {
13909                        return;
13910                    }
13911
13912                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13913                    clearDirectory(conn.mContainerService,
13914                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13915                    if (allData) {
13916                        clearDirectory(conn.mContainerService,
13917                                userEnv.buildExternalStorageAppDataDirs(packageName));
13918                        clearDirectory(conn.mContainerService,
13919                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13920                    }
13921                }
13922            } finally {
13923                mContext.unbindService(conn);
13924            }
13925        }
13926    }
13927
13928    @Override
13929    public void clearApplicationUserData(final String packageName,
13930            final IPackageDataObserver observer, final int userId) {
13931        mContext.enforceCallingOrSelfPermission(
13932                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13933        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13934        // Queue up an async operation since the package deletion may take a little while.
13935        mHandler.post(new Runnable() {
13936            public void run() {
13937                mHandler.removeCallbacks(this);
13938                final boolean succeeded;
13939                synchronized (mInstallLock) {
13940                    succeeded = clearApplicationUserDataLI(packageName, userId);
13941                }
13942                clearExternalStorageDataSync(packageName, userId, true);
13943                if (succeeded) {
13944                    // invoke DeviceStorageMonitor's update method to clear any notifications
13945                    DeviceStorageMonitorInternal
13946                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13947                    if (dsm != null) {
13948                        dsm.checkMemory();
13949                    }
13950                }
13951                if(observer != null) {
13952                    try {
13953                        observer.onRemoveCompleted(packageName, succeeded);
13954                    } catch (RemoteException e) {
13955                        Log.i(TAG, "Observer no longer exists.");
13956                    }
13957                } //end if observer
13958            } //end run
13959        });
13960    }
13961
13962    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13963        if (packageName == null) {
13964            Slog.w(TAG, "Attempt to delete null packageName.");
13965            return false;
13966        }
13967
13968        // Try finding details about the requested package
13969        PackageParser.Package pkg;
13970        synchronized (mPackages) {
13971            pkg = mPackages.get(packageName);
13972            if (pkg == null) {
13973                final PackageSetting ps = mSettings.mPackages.get(packageName);
13974                if (ps != null) {
13975                    pkg = ps.pkg;
13976                }
13977            }
13978
13979            if (pkg == null) {
13980                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13981                return false;
13982            }
13983
13984            PackageSetting ps = (PackageSetting) pkg.mExtras;
13985            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13986        }
13987
13988        // Always delete data directories for package, even if we found no other
13989        // record of app. This helps users recover from UID mismatches without
13990        // resorting to a full data wipe.
13991        // TODO: triage flags as part of 26466827
13992        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13993        try {
13994            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
13995        } catch (InstallerException e) {
13996            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
13997            return false;
13998        }
13999
14000        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14001        removeKeystoreDataIfNeeded(userId, appId);
14002
14003        // Create a native library symlink only if we have native libraries
14004        // and if the native libraries are 32 bit libraries. We do not provide
14005        // this symlink for 64 bit libraries.
14006        if (pkg.applicationInfo.primaryCpuAbi != null &&
14007                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14008            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14009            try {
14010                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14011                        nativeLibPath, userId);
14012            } catch (InstallerException e) {
14013                Slog.w(TAG, "Failed linking native library dir", e);
14014                return false;
14015            }
14016        }
14017
14018        return true;
14019    }
14020
14021    /**
14022     * Reverts user permission state changes (permissions and flags) in
14023     * all packages for a given user.
14024     *
14025     * @param userId The device user for which to do a reset.
14026     */
14027    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14028        final int packageCount = mPackages.size();
14029        for (int i = 0; i < packageCount; i++) {
14030            PackageParser.Package pkg = mPackages.valueAt(i);
14031            PackageSetting ps = (PackageSetting) pkg.mExtras;
14032            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14033        }
14034    }
14035
14036    /**
14037     * Reverts user permission state changes (permissions and flags).
14038     *
14039     * @param ps The package for which to reset.
14040     * @param userId The device user for which to do a reset.
14041     */
14042    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14043            final PackageSetting ps, final int userId) {
14044        if (ps.pkg == null) {
14045            return;
14046        }
14047
14048        // These are flags that can change base on user actions.
14049        final int userSettableMask = FLAG_PERMISSION_USER_SET
14050                | FLAG_PERMISSION_USER_FIXED
14051                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14052                | FLAG_PERMISSION_REVIEW_REQUIRED;
14053
14054        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14055                | FLAG_PERMISSION_POLICY_FIXED;
14056
14057        boolean writeInstallPermissions = false;
14058        boolean writeRuntimePermissions = false;
14059
14060        final int permissionCount = ps.pkg.requestedPermissions.size();
14061        for (int i = 0; i < permissionCount; i++) {
14062            String permission = ps.pkg.requestedPermissions.get(i);
14063
14064            BasePermission bp = mSettings.mPermissions.get(permission);
14065            if (bp == null) {
14066                continue;
14067            }
14068
14069            // If shared user we just reset the state to which only this app contributed.
14070            if (ps.sharedUser != null) {
14071                boolean used = false;
14072                final int packageCount = ps.sharedUser.packages.size();
14073                for (int j = 0; j < packageCount; j++) {
14074                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14075                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14076                            && pkg.pkg.requestedPermissions.contains(permission)) {
14077                        used = true;
14078                        break;
14079                    }
14080                }
14081                if (used) {
14082                    continue;
14083                }
14084            }
14085
14086            PermissionsState permissionsState = ps.getPermissionsState();
14087
14088            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14089
14090            // Always clear the user settable flags.
14091            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14092                    bp.name) != null;
14093            // If permission review is enabled and this is a legacy app, mark the
14094            // permission as requiring a review as this is the initial state.
14095            int flags = 0;
14096            if (Build.PERMISSIONS_REVIEW_REQUIRED
14097                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14098                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14099            }
14100            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14101                if (hasInstallState) {
14102                    writeInstallPermissions = true;
14103                } else {
14104                    writeRuntimePermissions = true;
14105                }
14106            }
14107
14108            // Below is only runtime permission handling.
14109            if (!bp.isRuntime()) {
14110                continue;
14111            }
14112
14113            // Never clobber system or policy.
14114            if ((oldFlags & policyOrSystemFlags) != 0) {
14115                continue;
14116            }
14117
14118            // If this permission was granted by default, make sure it is.
14119            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14120                if (permissionsState.grantRuntimePermission(bp, userId)
14121                        != PERMISSION_OPERATION_FAILURE) {
14122                    writeRuntimePermissions = true;
14123                }
14124            // If permission review is enabled the permissions for a legacy apps
14125            // are represented as constantly granted runtime ones, so don't revoke.
14126            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14127                // Otherwise, reset the permission.
14128                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14129                switch (revokeResult) {
14130                    case PERMISSION_OPERATION_SUCCESS: {
14131                        writeRuntimePermissions = true;
14132                    } break;
14133
14134                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14135                        writeRuntimePermissions = true;
14136                        final int appId = ps.appId;
14137                        mHandler.post(new Runnable() {
14138                            @Override
14139                            public void run() {
14140                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14141                            }
14142                        });
14143                    } break;
14144                }
14145            }
14146        }
14147
14148        // Synchronously write as we are taking permissions away.
14149        if (writeRuntimePermissions) {
14150            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14151        }
14152
14153        // Synchronously write as we are taking permissions away.
14154        if (writeInstallPermissions) {
14155            mSettings.writeLPr();
14156        }
14157    }
14158
14159    /**
14160     * Remove entries from the keystore daemon. Will only remove it if the
14161     * {@code appId} is valid.
14162     */
14163    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14164        if (appId < 0) {
14165            return;
14166        }
14167
14168        final KeyStore keyStore = KeyStore.getInstance();
14169        if (keyStore != null) {
14170            if (userId == UserHandle.USER_ALL) {
14171                for (final int individual : sUserManager.getUserIds()) {
14172                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14173                }
14174            } else {
14175                keyStore.clearUid(UserHandle.getUid(userId, appId));
14176            }
14177        } else {
14178            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14179        }
14180    }
14181
14182    @Override
14183    public void deleteApplicationCacheFiles(final String packageName,
14184            final IPackageDataObserver observer) {
14185        mContext.enforceCallingOrSelfPermission(
14186                android.Manifest.permission.DELETE_CACHE_FILES, null);
14187        // Queue up an async operation since the package deletion may take a little while.
14188        final int userId = UserHandle.getCallingUserId();
14189        mHandler.post(new Runnable() {
14190            public void run() {
14191                mHandler.removeCallbacks(this);
14192                final boolean succeded;
14193                synchronized (mInstallLock) {
14194                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14195                }
14196                clearExternalStorageDataSync(packageName, userId, false);
14197                if (observer != null) {
14198                    try {
14199                        observer.onRemoveCompleted(packageName, succeded);
14200                    } catch (RemoteException e) {
14201                        Log.i(TAG, "Observer no longer exists.");
14202                    }
14203                } //end if observer
14204            } //end run
14205        });
14206    }
14207
14208    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14209        if (packageName == null) {
14210            Slog.w(TAG, "Attempt to delete null packageName.");
14211            return false;
14212        }
14213        PackageParser.Package p;
14214        synchronized (mPackages) {
14215            p = mPackages.get(packageName);
14216        }
14217        if (p == null) {
14218            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14219            return false;
14220        }
14221        final ApplicationInfo applicationInfo = p.applicationInfo;
14222        if (applicationInfo == null) {
14223            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14224            return false;
14225        }
14226        // TODO: triage flags as part of 26466827
14227        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14228        try {
14229            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14230                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14231        } catch (InstallerException e) {
14232            Slog.w(TAG, "Couldn't remove cache files for package "
14233                    + packageName + " u" + userId, e);
14234            return false;
14235        }
14236        return true;
14237    }
14238
14239    @Override
14240    public void getPackageSizeInfo(final String packageName, int userHandle,
14241            final IPackageStatsObserver observer) {
14242        mContext.enforceCallingOrSelfPermission(
14243                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14244        if (packageName == null) {
14245            throw new IllegalArgumentException("Attempt to get size of null packageName");
14246        }
14247
14248        PackageStats stats = new PackageStats(packageName, userHandle);
14249
14250        /*
14251         * Queue up an async operation since the package measurement may take a
14252         * little while.
14253         */
14254        Message msg = mHandler.obtainMessage(INIT_COPY);
14255        msg.obj = new MeasureParams(stats, observer);
14256        mHandler.sendMessage(msg);
14257    }
14258
14259    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14260            PackageStats pStats) {
14261        if (packageName == null) {
14262            Slog.w(TAG, "Attempt to get size of null packageName.");
14263            return false;
14264        }
14265        PackageParser.Package p;
14266        boolean dataOnly = false;
14267        String libDirRoot = null;
14268        String asecPath = null;
14269        PackageSetting ps = null;
14270        synchronized (mPackages) {
14271            p = mPackages.get(packageName);
14272            ps = mSettings.mPackages.get(packageName);
14273            if(p == null) {
14274                dataOnly = true;
14275                if((ps == null) || (ps.pkg == null)) {
14276                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14277                    return false;
14278                }
14279                p = ps.pkg;
14280            }
14281            if (ps != null) {
14282                libDirRoot = ps.legacyNativeLibraryPathString;
14283            }
14284            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14285                final long token = Binder.clearCallingIdentity();
14286                try {
14287                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14288                    if (secureContainerId != null) {
14289                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14290                    }
14291                } finally {
14292                    Binder.restoreCallingIdentity(token);
14293                }
14294            }
14295        }
14296        String publicSrcDir = null;
14297        if(!dataOnly) {
14298            final ApplicationInfo applicationInfo = p.applicationInfo;
14299            if (applicationInfo == null) {
14300                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14301                return false;
14302            }
14303            if (p.isForwardLocked()) {
14304                publicSrcDir = applicationInfo.getBaseResourcePath();
14305            }
14306        }
14307        // TODO: extend to measure size of split APKs
14308        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14309        // not just the first level.
14310        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14311        // just the primary.
14312        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14313
14314        String apkPath;
14315        File packageDir = new File(p.codePath);
14316
14317        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14318            apkPath = packageDir.getAbsolutePath();
14319            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14320            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14321                libDirRoot = null;
14322            }
14323        } else {
14324            apkPath = p.baseCodePath;
14325        }
14326
14327        // TODO: triage flags as part of 26466827
14328        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14329        try {
14330            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14331                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14332        } catch (InstallerException e) {
14333            return false;
14334        }
14335
14336        // Fix-up for forward-locked applications in ASEC containers.
14337        if (!isExternal(p)) {
14338            pStats.codeSize += pStats.externalCodeSize;
14339            pStats.externalCodeSize = 0L;
14340        }
14341
14342        return true;
14343    }
14344
14345
14346    @Override
14347    public void addPackageToPreferred(String packageName) {
14348        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14349    }
14350
14351    @Override
14352    public void removePackageFromPreferred(String packageName) {
14353        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14354    }
14355
14356    @Override
14357    public List<PackageInfo> getPreferredPackages(int flags) {
14358        return new ArrayList<PackageInfo>();
14359    }
14360
14361    private int getUidTargetSdkVersionLockedLPr(int uid) {
14362        Object obj = mSettings.getUserIdLPr(uid);
14363        if (obj instanceof SharedUserSetting) {
14364            final SharedUserSetting sus = (SharedUserSetting) obj;
14365            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14366            final Iterator<PackageSetting> it = sus.packages.iterator();
14367            while (it.hasNext()) {
14368                final PackageSetting ps = it.next();
14369                if (ps.pkg != null) {
14370                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14371                    if (v < vers) vers = v;
14372                }
14373            }
14374            return vers;
14375        } else if (obj instanceof PackageSetting) {
14376            final PackageSetting ps = (PackageSetting) obj;
14377            if (ps.pkg != null) {
14378                return ps.pkg.applicationInfo.targetSdkVersion;
14379            }
14380        }
14381        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14382    }
14383
14384    @Override
14385    public void addPreferredActivity(IntentFilter filter, int match,
14386            ComponentName[] set, ComponentName activity, int userId) {
14387        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14388                "Adding preferred");
14389    }
14390
14391    private void addPreferredActivityInternal(IntentFilter filter, int match,
14392            ComponentName[] set, ComponentName activity, boolean always, int userId,
14393            String opname) {
14394        // writer
14395        int callingUid = Binder.getCallingUid();
14396        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14397        if (filter.countActions() == 0) {
14398            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14399            return;
14400        }
14401        synchronized (mPackages) {
14402            if (mContext.checkCallingOrSelfPermission(
14403                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14404                    != PackageManager.PERMISSION_GRANTED) {
14405                if (getUidTargetSdkVersionLockedLPr(callingUid)
14406                        < Build.VERSION_CODES.FROYO) {
14407                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14408                            + callingUid);
14409                    return;
14410                }
14411                mContext.enforceCallingOrSelfPermission(
14412                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14413            }
14414
14415            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14416            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14417                    + userId + ":");
14418            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14419            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14420            scheduleWritePackageRestrictionsLocked(userId);
14421        }
14422    }
14423
14424    @Override
14425    public void replacePreferredActivity(IntentFilter filter, int match,
14426            ComponentName[] set, ComponentName activity, int userId) {
14427        if (filter.countActions() != 1) {
14428            throw new IllegalArgumentException(
14429                    "replacePreferredActivity expects filter to have only 1 action.");
14430        }
14431        if (filter.countDataAuthorities() != 0
14432                || filter.countDataPaths() != 0
14433                || filter.countDataSchemes() > 1
14434                || filter.countDataTypes() != 0) {
14435            throw new IllegalArgumentException(
14436                    "replacePreferredActivity expects filter to have no data authorities, " +
14437                    "paths, or types; and at most one scheme.");
14438        }
14439
14440        final int callingUid = Binder.getCallingUid();
14441        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14442        synchronized (mPackages) {
14443            if (mContext.checkCallingOrSelfPermission(
14444                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14445                    != PackageManager.PERMISSION_GRANTED) {
14446                if (getUidTargetSdkVersionLockedLPr(callingUid)
14447                        < Build.VERSION_CODES.FROYO) {
14448                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14449                            + Binder.getCallingUid());
14450                    return;
14451                }
14452                mContext.enforceCallingOrSelfPermission(
14453                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14454            }
14455
14456            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14457            if (pir != null) {
14458                // Get all of the existing entries that exactly match this filter.
14459                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14460                if (existing != null && existing.size() == 1) {
14461                    PreferredActivity cur = existing.get(0);
14462                    if (DEBUG_PREFERRED) {
14463                        Slog.i(TAG, "Checking replace of preferred:");
14464                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14465                        if (!cur.mPref.mAlways) {
14466                            Slog.i(TAG, "  -- CUR; not mAlways!");
14467                        } else {
14468                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14469                            Slog.i(TAG, "  -- CUR: mSet="
14470                                    + Arrays.toString(cur.mPref.mSetComponents));
14471                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14472                            Slog.i(TAG, "  -- NEW: mMatch="
14473                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14474                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14475                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14476                        }
14477                    }
14478                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14479                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14480                            && cur.mPref.sameSet(set)) {
14481                        // Setting the preferred activity to what it happens to be already
14482                        if (DEBUG_PREFERRED) {
14483                            Slog.i(TAG, "Replacing with same preferred activity "
14484                                    + cur.mPref.mShortComponent + " for user "
14485                                    + userId + ":");
14486                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14487                        }
14488                        return;
14489                    }
14490                }
14491
14492                if (existing != null) {
14493                    if (DEBUG_PREFERRED) {
14494                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14495                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14496                    }
14497                    for (int i = 0; i < existing.size(); i++) {
14498                        PreferredActivity pa = existing.get(i);
14499                        if (DEBUG_PREFERRED) {
14500                            Slog.i(TAG, "Removing existing preferred activity "
14501                                    + pa.mPref.mComponent + ":");
14502                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14503                        }
14504                        pir.removeFilter(pa);
14505                    }
14506                }
14507            }
14508            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14509                    "Replacing preferred");
14510        }
14511    }
14512
14513    @Override
14514    public void clearPackagePreferredActivities(String packageName) {
14515        final int uid = Binder.getCallingUid();
14516        // writer
14517        synchronized (mPackages) {
14518            PackageParser.Package pkg = mPackages.get(packageName);
14519            if (pkg == null || pkg.applicationInfo.uid != uid) {
14520                if (mContext.checkCallingOrSelfPermission(
14521                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14522                        != PackageManager.PERMISSION_GRANTED) {
14523                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14524                            < Build.VERSION_CODES.FROYO) {
14525                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14526                                + Binder.getCallingUid());
14527                        return;
14528                    }
14529                    mContext.enforceCallingOrSelfPermission(
14530                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14531                }
14532            }
14533
14534            int user = UserHandle.getCallingUserId();
14535            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14536                scheduleWritePackageRestrictionsLocked(user);
14537            }
14538        }
14539    }
14540
14541    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14542    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14543        ArrayList<PreferredActivity> removed = null;
14544        boolean changed = false;
14545        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14546            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14547            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14548            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14549                continue;
14550            }
14551            Iterator<PreferredActivity> it = pir.filterIterator();
14552            while (it.hasNext()) {
14553                PreferredActivity pa = it.next();
14554                // Mark entry for removal only if it matches the package name
14555                // and the entry is of type "always".
14556                if (packageName == null ||
14557                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14558                                && pa.mPref.mAlways)) {
14559                    if (removed == null) {
14560                        removed = new ArrayList<PreferredActivity>();
14561                    }
14562                    removed.add(pa);
14563                }
14564            }
14565            if (removed != null) {
14566                for (int j=0; j<removed.size(); j++) {
14567                    PreferredActivity pa = removed.get(j);
14568                    pir.removeFilter(pa);
14569                }
14570                changed = true;
14571            }
14572        }
14573        return changed;
14574    }
14575
14576    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14577    private void clearIntentFilterVerificationsLPw(int userId) {
14578        final int packageCount = mPackages.size();
14579        for (int i = 0; i < packageCount; i++) {
14580            PackageParser.Package pkg = mPackages.valueAt(i);
14581            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14582        }
14583    }
14584
14585    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14586    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14587        if (userId == UserHandle.USER_ALL) {
14588            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14589                    sUserManager.getUserIds())) {
14590                for (int oneUserId : sUserManager.getUserIds()) {
14591                    scheduleWritePackageRestrictionsLocked(oneUserId);
14592                }
14593            }
14594        } else {
14595            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14596                scheduleWritePackageRestrictionsLocked(userId);
14597            }
14598        }
14599    }
14600
14601    void clearDefaultBrowserIfNeeded(String packageName) {
14602        for (int oneUserId : sUserManager.getUserIds()) {
14603            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14604            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14605            if (packageName.equals(defaultBrowserPackageName)) {
14606                setDefaultBrowserPackageName(null, oneUserId);
14607            }
14608        }
14609    }
14610
14611    @Override
14612    public void resetApplicationPreferences(int userId) {
14613        mContext.enforceCallingOrSelfPermission(
14614                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14615        // writer
14616        synchronized (mPackages) {
14617            final long identity = Binder.clearCallingIdentity();
14618            try {
14619                clearPackagePreferredActivitiesLPw(null, userId);
14620                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14621                // TODO: We have to reset the default SMS and Phone. This requires
14622                // significant refactoring to keep all default apps in the package
14623                // manager (cleaner but more work) or have the services provide
14624                // callbacks to the package manager to request a default app reset.
14625                applyFactoryDefaultBrowserLPw(userId);
14626                clearIntentFilterVerificationsLPw(userId);
14627                primeDomainVerificationsLPw(userId);
14628                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14629                scheduleWritePackageRestrictionsLocked(userId);
14630            } finally {
14631                Binder.restoreCallingIdentity(identity);
14632            }
14633        }
14634    }
14635
14636    @Override
14637    public int getPreferredActivities(List<IntentFilter> outFilters,
14638            List<ComponentName> outActivities, String packageName) {
14639
14640        int num = 0;
14641        final int userId = UserHandle.getCallingUserId();
14642        // reader
14643        synchronized (mPackages) {
14644            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14645            if (pir != null) {
14646                final Iterator<PreferredActivity> it = pir.filterIterator();
14647                while (it.hasNext()) {
14648                    final PreferredActivity pa = it.next();
14649                    if (packageName == null
14650                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14651                                    && pa.mPref.mAlways)) {
14652                        if (outFilters != null) {
14653                            outFilters.add(new IntentFilter(pa));
14654                        }
14655                        if (outActivities != null) {
14656                            outActivities.add(pa.mPref.mComponent);
14657                        }
14658                    }
14659                }
14660            }
14661        }
14662
14663        return num;
14664    }
14665
14666    @Override
14667    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14668            int userId) {
14669        int callingUid = Binder.getCallingUid();
14670        if (callingUid != Process.SYSTEM_UID) {
14671            throw new SecurityException(
14672                    "addPersistentPreferredActivity can only be run by the system");
14673        }
14674        if (filter.countActions() == 0) {
14675            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14676            return;
14677        }
14678        synchronized (mPackages) {
14679            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14680                    ":");
14681            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14682            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14683                    new PersistentPreferredActivity(filter, activity));
14684            scheduleWritePackageRestrictionsLocked(userId);
14685        }
14686    }
14687
14688    @Override
14689    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14690        int callingUid = Binder.getCallingUid();
14691        if (callingUid != Process.SYSTEM_UID) {
14692            throw new SecurityException(
14693                    "clearPackagePersistentPreferredActivities can only be run by the system");
14694        }
14695        ArrayList<PersistentPreferredActivity> removed = null;
14696        boolean changed = false;
14697        synchronized (mPackages) {
14698            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14699                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14700                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14701                        .valueAt(i);
14702                if (userId != thisUserId) {
14703                    continue;
14704                }
14705                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14706                while (it.hasNext()) {
14707                    PersistentPreferredActivity ppa = it.next();
14708                    // Mark entry for removal only if it matches the package name.
14709                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14710                        if (removed == null) {
14711                            removed = new ArrayList<PersistentPreferredActivity>();
14712                        }
14713                        removed.add(ppa);
14714                    }
14715                }
14716                if (removed != null) {
14717                    for (int j=0; j<removed.size(); j++) {
14718                        PersistentPreferredActivity ppa = removed.get(j);
14719                        ppir.removeFilter(ppa);
14720                    }
14721                    changed = true;
14722                }
14723            }
14724
14725            if (changed) {
14726                scheduleWritePackageRestrictionsLocked(userId);
14727            }
14728        }
14729    }
14730
14731    /**
14732     * Common machinery for picking apart a restored XML blob and passing
14733     * it to a caller-supplied functor to be applied to the running system.
14734     */
14735    private void restoreFromXml(XmlPullParser parser, int userId,
14736            String expectedStartTag, BlobXmlRestorer functor)
14737            throws IOException, XmlPullParserException {
14738        int type;
14739        while ((type = parser.next()) != XmlPullParser.START_TAG
14740                && type != XmlPullParser.END_DOCUMENT) {
14741        }
14742        if (type != XmlPullParser.START_TAG) {
14743            // oops didn't find a start tag?!
14744            if (DEBUG_BACKUP) {
14745                Slog.e(TAG, "Didn't find start tag during restore");
14746            }
14747            return;
14748        }
14749Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14750        // this is supposed to be TAG_PREFERRED_BACKUP
14751        if (!expectedStartTag.equals(parser.getName())) {
14752            if (DEBUG_BACKUP) {
14753                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14754            }
14755            return;
14756        }
14757
14758        // skip interfering stuff, then we're aligned with the backing implementation
14759        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14760Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14761        functor.apply(parser, userId);
14762    }
14763
14764    private interface BlobXmlRestorer {
14765        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14766    }
14767
14768    /**
14769     * Non-Binder method, support for the backup/restore mechanism: write the
14770     * full set of preferred activities in its canonical XML format.  Returns the
14771     * XML output as a byte array, or null if there is none.
14772     */
14773    @Override
14774    public byte[] getPreferredActivityBackup(int userId) {
14775        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14776            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14777        }
14778
14779        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14780        try {
14781            final XmlSerializer serializer = new FastXmlSerializer();
14782            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14783            serializer.startDocument(null, true);
14784            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14785
14786            synchronized (mPackages) {
14787                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14788            }
14789
14790            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14791            serializer.endDocument();
14792            serializer.flush();
14793        } catch (Exception e) {
14794            if (DEBUG_BACKUP) {
14795                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14796            }
14797            return null;
14798        }
14799
14800        return dataStream.toByteArray();
14801    }
14802
14803    @Override
14804    public void restorePreferredActivities(byte[] backup, int userId) {
14805        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14806            throw new SecurityException("Only the system may call restorePreferredActivities()");
14807        }
14808
14809        try {
14810            final XmlPullParser parser = Xml.newPullParser();
14811            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14812            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14813                    new BlobXmlRestorer() {
14814                        @Override
14815                        public void apply(XmlPullParser parser, int userId)
14816                                throws XmlPullParserException, IOException {
14817                            synchronized (mPackages) {
14818                                mSettings.readPreferredActivitiesLPw(parser, userId);
14819                            }
14820                        }
14821                    } );
14822        } catch (Exception e) {
14823            if (DEBUG_BACKUP) {
14824                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14825            }
14826        }
14827    }
14828
14829    /**
14830     * Non-Binder method, support for the backup/restore mechanism: write the
14831     * default browser (etc) settings in its canonical XML format.  Returns the default
14832     * browser XML representation as a byte array, or null if there is none.
14833     */
14834    @Override
14835    public byte[] getDefaultAppsBackup(int userId) {
14836        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14837            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14838        }
14839
14840        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14841        try {
14842            final XmlSerializer serializer = new FastXmlSerializer();
14843            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14844            serializer.startDocument(null, true);
14845            serializer.startTag(null, TAG_DEFAULT_APPS);
14846
14847            synchronized (mPackages) {
14848                mSettings.writeDefaultAppsLPr(serializer, userId);
14849            }
14850
14851            serializer.endTag(null, TAG_DEFAULT_APPS);
14852            serializer.endDocument();
14853            serializer.flush();
14854        } catch (Exception e) {
14855            if (DEBUG_BACKUP) {
14856                Slog.e(TAG, "Unable to write default apps for backup", e);
14857            }
14858            return null;
14859        }
14860
14861        return dataStream.toByteArray();
14862    }
14863
14864    @Override
14865    public void restoreDefaultApps(byte[] backup, int userId) {
14866        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14867            throw new SecurityException("Only the system may call restoreDefaultApps()");
14868        }
14869
14870        try {
14871            final XmlPullParser parser = Xml.newPullParser();
14872            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14873            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14874                    new BlobXmlRestorer() {
14875                        @Override
14876                        public void apply(XmlPullParser parser, int userId)
14877                                throws XmlPullParserException, IOException {
14878                            synchronized (mPackages) {
14879                                mSettings.readDefaultAppsLPw(parser, userId);
14880                            }
14881                        }
14882                    } );
14883        } catch (Exception e) {
14884            if (DEBUG_BACKUP) {
14885                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14886            }
14887        }
14888    }
14889
14890    @Override
14891    public byte[] getIntentFilterVerificationBackup(int userId) {
14892        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14893            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14894        }
14895
14896        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14897        try {
14898            final XmlSerializer serializer = new FastXmlSerializer();
14899            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14900            serializer.startDocument(null, true);
14901            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14902
14903            synchronized (mPackages) {
14904                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14905            }
14906
14907            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14908            serializer.endDocument();
14909            serializer.flush();
14910        } catch (Exception e) {
14911            if (DEBUG_BACKUP) {
14912                Slog.e(TAG, "Unable to write default apps for backup", e);
14913            }
14914            return null;
14915        }
14916
14917        return dataStream.toByteArray();
14918    }
14919
14920    @Override
14921    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14922        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14923            throw new SecurityException("Only the system may call restorePreferredActivities()");
14924        }
14925
14926        try {
14927            final XmlPullParser parser = Xml.newPullParser();
14928            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14929            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14930                    new BlobXmlRestorer() {
14931                        @Override
14932                        public void apply(XmlPullParser parser, int userId)
14933                                throws XmlPullParserException, IOException {
14934                            synchronized (mPackages) {
14935                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14936                                mSettings.writeLPr();
14937                            }
14938                        }
14939                    } );
14940        } catch (Exception e) {
14941            if (DEBUG_BACKUP) {
14942                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14943            }
14944        }
14945    }
14946
14947    @Override
14948    public byte[] getPermissionGrantBackup(int userId) {
14949        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14950            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
14951        }
14952
14953        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14954        try {
14955            final XmlSerializer serializer = new FastXmlSerializer();
14956            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14957            serializer.startDocument(null, true);
14958            serializer.startTag(null, TAG_PERMISSION_BACKUP);
14959
14960            synchronized (mPackages) {
14961                serializeRuntimePermissionGrantsLPr(serializer, userId);
14962            }
14963
14964            serializer.endTag(null, TAG_PERMISSION_BACKUP);
14965            serializer.endDocument();
14966            serializer.flush();
14967        } catch (Exception e) {
14968            if (DEBUG_BACKUP) {
14969                Slog.e(TAG, "Unable to write default apps for backup", e);
14970            }
14971            return null;
14972        }
14973
14974        return dataStream.toByteArray();
14975    }
14976
14977    @Override
14978    public void restorePermissionGrants(byte[] backup, int userId) {
14979        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14980            throw new SecurityException("Only the system may call restorePermissionGrants()");
14981        }
14982
14983        try {
14984            final XmlPullParser parser = Xml.newPullParser();
14985            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14986            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
14987                    new BlobXmlRestorer() {
14988                        @Override
14989                        public void apply(XmlPullParser parser, int userId)
14990                                throws XmlPullParserException, IOException {
14991                            synchronized (mPackages) {
14992                                processRestoredPermissionGrantsLPr(parser, userId);
14993                            }
14994                        }
14995                    } );
14996        } catch (Exception e) {
14997            if (DEBUG_BACKUP) {
14998                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14999            }
15000        }
15001    }
15002
15003    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15004            throws IOException {
15005        serializer.startTag(null, TAG_ALL_GRANTS);
15006
15007        final int N = mSettings.mPackages.size();
15008        for (int i = 0; i < N; i++) {
15009            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15010            boolean pkgGrantsKnown = false;
15011
15012            PermissionsState packagePerms = ps.getPermissionsState();
15013
15014            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15015                final int grantFlags = state.getFlags();
15016                // only look at grants that are not system/policy fixed
15017                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15018                    final boolean isGranted = state.isGranted();
15019                    // And only back up the user-twiddled state bits
15020                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15021                        final String packageName = mSettings.mPackages.keyAt(i);
15022                        if (!pkgGrantsKnown) {
15023                            serializer.startTag(null, TAG_GRANT);
15024                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15025                            pkgGrantsKnown = true;
15026                        }
15027
15028                        final boolean userSet =
15029                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15030                        final boolean userFixed =
15031                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15032                        final boolean revoke =
15033                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15034
15035                        serializer.startTag(null, TAG_PERMISSION);
15036                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15037                        if (isGranted) {
15038                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15039                        }
15040                        if (userSet) {
15041                            serializer.attribute(null, ATTR_USER_SET, "true");
15042                        }
15043                        if (userFixed) {
15044                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15045                        }
15046                        if (revoke) {
15047                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15048                        }
15049                        serializer.endTag(null, TAG_PERMISSION);
15050                    }
15051                }
15052            }
15053
15054            if (pkgGrantsKnown) {
15055                serializer.endTag(null, TAG_GRANT);
15056            }
15057        }
15058
15059        serializer.endTag(null, TAG_ALL_GRANTS);
15060    }
15061
15062    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15063            throws XmlPullParserException, IOException {
15064        String pkgName = null;
15065        int outerDepth = parser.getDepth();
15066        int type;
15067        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15068                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15069            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15070                continue;
15071            }
15072
15073            final String tagName = parser.getName();
15074            if (tagName.equals(TAG_GRANT)) {
15075                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15076                if (DEBUG_BACKUP) {
15077                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15078                }
15079            } else if (tagName.equals(TAG_PERMISSION)) {
15080
15081                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15082                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15083
15084                int newFlagSet = 0;
15085                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15086                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15087                }
15088                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15089                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15090                }
15091                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15092                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15093                }
15094                if (DEBUG_BACKUP) {
15095                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15096                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15097                }
15098                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15099                if (ps != null) {
15100                    // Already installed so we apply the grant immediately
15101                    if (DEBUG_BACKUP) {
15102                        Slog.v(TAG, "        + already installed; applying");
15103                    }
15104                    PermissionsState perms = ps.getPermissionsState();
15105                    BasePermission bp = mSettings.mPermissions.get(permName);
15106                    if (bp != null) {
15107                        if (isGranted) {
15108                            perms.grantRuntimePermission(bp, userId);
15109                        }
15110                        if (newFlagSet != 0) {
15111                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15112                        }
15113                    }
15114                } else {
15115                    // Need to wait for post-restore install to apply the grant
15116                    if (DEBUG_BACKUP) {
15117                        Slog.v(TAG, "        - not yet installed; saving for later");
15118                    }
15119                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15120                            isGranted, newFlagSet, userId);
15121                }
15122            } else {
15123                PackageManagerService.reportSettingsProblem(Log.WARN,
15124                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15125                XmlUtils.skipCurrentTag(parser);
15126            }
15127        }
15128
15129        scheduleWriteSettingsLocked();
15130        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15131    }
15132
15133    @Override
15134    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15135            int sourceUserId, int targetUserId, int flags) {
15136        mContext.enforceCallingOrSelfPermission(
15137                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15138        int callingUid = Binder.getCallingUid();
15139        enforceOwnerRights(ownerPackage, callingUid);
15140        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15141        if (intentFilter.countActions() == 0) {
15142            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15143            return;
15144        }
15145        synchronized (mPackages) {
15146            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15147                    ownerPackage, targetUserId, flags);
15148            CrossProfileIntentResolver resolver =
15149                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15150            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15151            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15152            if (existing != null) {
15153                int size = existing.size();
15154                for (int i = 0; i < size; i++) {
15155                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15156                        return;
15157                    }
15158                }
15159            }
15160            resolver.addFilter(newFilter);
15161            scheduleWritePackageRestrictionsLocked(sourceUserId);
15162        }
15163    }
15164
15165    @Override
15166    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15167        mContext.enforceCallingOrSelfPermission(
15168                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15169        int callingUid = Binder.getCallingUid();
15170        enforceOwnerRights(ownerPackage, callingUid);
15171        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15172        synchronized (mPackages) {
15173            CrossProfileIntentResolver resolver =
15174                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15175            ArraySet<CrossProfileIntentFilter> set =
15176                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15177            for (CrossProfileIntentFilter filter : set) {
15178                if (filter.getOwnerPackage().equals(ownerPackage)) {
15179                    resolver.removeFilter(filter);
15180                }
15181            }
15182            scheduleWritePackageRestrictionsLocked(sourceUserId);
15183        }
15184    }
15185
15186    // Enforcing that callingUid is owning pkg on userId
15187    private void enforceOwnerRights(String pkg, int callingUid) {
15188        // The system owns everything.
15189        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15190            return;
15191        }
15192        int callingUserId = UserHandle.getUserId(callingUid);
15193        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15194        if (pi == null) {
15195            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15196                    + callingUserId);
15197        }
15198        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15199            throw new SecurityException("Calling uid " + callingUid
15200                    + " does not own package " + pkg);
15201        }
15202    }
15203
15204    @Override
15205    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15206        Intent intent = new Intent(Intent.ACTION_MAIN);
15207        intent.addCategory(Intent.CATEGORY_HOME);
15208
15209        final int callingUserId = UserHandle.getCallingUserId();
15210        List<ResolveInfo> list = queryIntentActivities(intent, null,
15211                PackageManager.GET_META_DATA, callingUserId);
15212        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15213                true, false, false, callingUserId);
15214
15215        allHomeCandidates.clear();
15216        if (list != null) {
15217            for (ResolveInfo ri : list) {
15218                allHomeCandidates.add(ri);
15219            }
15220        }
15221        return (preferred == null || preferred.activityInfo == null)
15222                ? null
15223                : new ComponentName(preferred.activityInfo.packageName,
15224                        preferred.activityInfo.name);
15225    }
15226
15227    @Override
15228    public void setApplicationEnabledSetting(String appPackageName,
15229            int newState, int flags, int userId, String callingPackage) {
15230        if (!sUserManager.exists(userId)) return;
15231        if (callingPackage == null) {
15232            callingPackage = Integer.toString(Binder.getCallingUid());
15233        }
15234        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15235    }
15236
15237    @Override
15238    public void setComponentEnabledSetting(ComponentName componentName,
15239            int newState, int flags, int userId) {
15240        if (!sUserManager.exists(userId)) return;
15241        setEnabledSetting(componentName.getPackageName(),
15242                componentName.getClassName(), newState, flags, userId, null);
15243    }
15244
15245    private void setEnabledSetting(final String packageName, String className, int newState,
15246            final int flags, int userId, String callingPackage) {
15247        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15248              || newState == COMPONENT_ENABLED_STATE_ENABLED
15249              || newState == COMPONENT_ENABLED_STATE_DISABLED
15250              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15251              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15252            throw new IllegalArgumentException("Invalid new component state: "
15253                    + newState);
15254        }
15255        PackageSetting pkgSetting;
15256        final int uid = Binder.getCallingUid();
15257        final int permission = mContext.checkCallingOrSelfPermission(
15258                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15259        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15260        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15261        boolean sendNow = false;
15262        boolean isApp = (className == null);
15263        String componentName = isApp ? packageName : className;
15264        int packageUid = -1;
15265        ArrayList<String> components;
15266
15267        // writer
15268        synchronized (mPackages) {
15269            pkgSetting = mSettings.mPackages.get(packageName);
15270            if (pkgSetting == null) {
15271                if (className == null) {
15272                    throw new IllegalArgumentException("Unknown package: " + packageName);
15273                }
15274                throw new IllegalArgumentException(
15275                        "Unknown component: " + packageName + "/" + className);
15276            }
15277            // Allow root and verify that userId is not being specified by a different user
15278            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15279                throw new SecurityException(
15280                        "Permission Denial: attempt to change component state from pid="
15281                        + Binder.getCallingPid()
15282                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15283            }
15284            if (className == null) {
15285                // We're dealing with an application/package level state change
15286                if (pkgSetting.getEnabled(userId) == newState) {
15287                    // Nothing to do
15288                    return;
15289                }
15290                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15291                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15292                    // Don't care about who enables an app.
15293                    callingPackage = null;
15294                }
15295                pkgSetting.setEnabled(newState, userId, callingPackage);
15296                // pkgSetting.pkg.mSetEnabled = newState;
15297            } else {
15298                // We're dealing with a component level state change
15299                // First, verify that this is a valid class name.
15300                PackageParser.Package pkg = pkgSetting.pkg;
15301                if (pkg == null || !pkg.hasComponentClassName(className)) {
15302                    if (pkg != null &&
15303                            pkg.applicationInfo.targetSdkVersion >=
15304                                    Build.VERSION_CODES.JELLY_BEAN) {
15305                        throw new IllegalArgumentException("Component class " + className
15306                                + " does not exist in " + packageName);
15307                    } else {
15308                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15309                                + className + " does not exist in " + packageName);
15310                    }
15311                }
15312                switch (newState) {
15313                case COMPONENT_ENABLED_STATE_ENABLED:
15314                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15315                        return;
15316                    }
15317                    break;
15318                case COMPONENT_ENABLED_STATE_DISABLED:
15319                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15320                        return;
15321                    }
15322                    break;
15323                case COMPONENT_ENABLED_STATE_DEFAULT:
15324                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15325                        return;
15326                    }
15327                    break;
15328                default:
15329                    Slog.e(TAG, "Invalid new component state: " + newState);
15330                    return;
15331                }
15332            }
15333            scheduleWritePackageRestrictionsLocked(userId);
15334            components = mPendingBroadcasts.get(userId, packageName);
15335            final boolean newPackage = components == null;
15336            if (newPackage) {
15337                components = new ArrayList<String>();
15338            }
15339            if (!components.contains(componentName)) {
15340                components.add(componentName);
15341            }
15342            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15343                sendNow = true;
15344                // Purge entry from pending broadcast list if another one exists already
15345                // since we are sending one right away.
15346                mPendingBroadcasts.remove(userId, packageName);
15347            } else {
15348                if (newPackage) {
15349                    mPendingBroadcasts.put(userId, packageName, components);
15350                }
15351                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15352                    // Schedule a message
15353                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15354                }
15355            }
15356        }
15357
15358        long callingId = Binder.clearCallingIdentity();
15359        try {
15360            if (sendNow) {
15361                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15362                sendPackageChangedBroadcast(packageName,
15363                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15364            }
15365        } finally {
15366            Binder.restoreCallingIdentity(callingId);
15367        }
15368    }
15369
15370    private void sendPackageChangedBroadcast(String packageName,
15371            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15372        if (DEBUG_INSTALL)
15373            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15374                    + componentNames);
15375        Bundle extras = new Bundle(4);
15376        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15377        String nameList[] = new String[componentNames.size()];
15378        componentNames.toArray(nameList);
15379        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15380        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15381        extras.putInt(Intent.EXTRA_UID, packageUid);
15382        // If this is not reporting a change of the overall package, then only send it
15383        // to registered receivers.  We don't want to launch a swath of apps for every
15384        // little component state change.
15385        final int flags = !componentNames.contains(packageName)
15386                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15387        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15388                new int[] {UserHandle.getUserId(packageUid)});
15389    }
15390
15391    @Override
15392    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15393        if (!sUserManager.exists(userId)) return;
15394        final int uid = Binder.getCallingUid();
15395        final int permission = mContext.checkCallingOrSelfPermission(
15396                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15397        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15398        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15399        // writer
15400        synchronized (mPackages) {
15401            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15402                    allowedByPermission, uid, userId)) {
15403                scheduleWritePackageRestrictionsLocked(userId);
15404            }
15405        }
15406    }
15407
15408    @Override
15409    public String getInstallerPackageName(String packageName) {
15410        // reader
15411        synchronized (mPackages) {
15412            return mSettings.getInstallerPackageNameLPr(packageName);
15413        }
15414    }
15415
15416    @Override
15417    public int getApplicationEnabledSetting(String packageName, int userId) {
15418        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15419        int uid = Binder.getCallingUid();
15420        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15421        // reader
15422        synchronized (mPackages) {
15423            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15424        }
15425    }
15426
15427    @Override
15428    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15429        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15430        int uid = Binder.getCallingUid();
15431        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15432        // reader
15433        synchronized (mPackages) {
15434            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15435        }
15436    }
15437
15438    @Override
15439    public void enterSafeMode() {
15440        enforceSystemOrRoot("Only the system can request entering safe mode");
15441
15442        if (!mSystemReady) {
15443            mSafeMode = true;
15444        }
15445    }
15446
15447    @Override
15448    public void systemReady() {
15449        mSystemReady = true;
15450
15451        // Read the compatibilty setting when the system is ready.
15452        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15453                mContext.getContentResolver(),
15454                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15455        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15456        if (DEBUG_SETTINGS) {
15457            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15458        }
15459
15460        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15461
15462        synchronized (mPackages) {
15463            // Verify that all of the preferred activity components actually
15464            // exist.  It is possible for applications to be updated and at
15465            // that point remove a previously declared activity component that
15466            // had been set as a preferred activity.  We try to clean this up
15467            // the next time we encounter that preferred activity, but it is
15468            // possible for the user flow to never be able to return to that
15469            // situation so here we do a sanity check to make sure we haven't
15470            // left any junk around.
15471            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15472            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15473                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15474                removed.clear();
15475                for (PreferredActivity pa : pir.filterSet()) {
15476                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15477                        removed.add(pa);
15478                    }
15479                }
15480                if (removed.size() > 0) {
15481                    for (int r=0; r<removed.size(); r++) {
15482                        PreferredActivity pa = removed.get(r);
15483                        Slog.w(TAG, "Removing dangling preferred activity: "
15484                                + pa.mPref.mComponent);
15485                        pir.removeFilter(pa);
15486                    }
15487                    mSettings.writePackageRestrictionsLPr(
15488                            mSettings.mPreferredActivities.keyAt(i));
15489                }
15490            }
15491
15492            for (int userId : UserManagerService.getInstance().getUserIds()) {
15493                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15494                    grantPermissionsUserIds = ArrayUtils.appendInt(
15495                            grantPermissionsUserIds, userId);
15496                }
15497            }
15498        }
15499        sUserManager.systemReady();
15500
15501        // If we upgraded grant all default permissions before kicking off.
15502        for (int userId : grantPermissionsUserIds) {
15503            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15504        }
15505
15506        // Kick off any messages waiting for system ready
15507        if (mPostSystemReadyMessages != null) {
15508            for (Message msg : mPostSystemReadyMessages) {
15509                msg.sendToTarget();
15510            }
15511            mPostSystemReadyMessages = null;
15512        }
15513
15514        // Watch for external volumes that come and go over time
15515        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15516        storage.registerListener(mStorageListener);
15517
15518        mInstallerService.systemReady();
15519        mPackageDexOptimizer.systemReady();
15520
15521        MountServiceInternal mountServiceInternal = LocalServices.getService(
15522                MountServiceInternal.class);
15523        mountServiceInternal.addExternalStoragePolicy(
15524                new MountServiceInternal.ExternalStorageMountPolicy() {
15525            @Override
15526            public int getMountMode(int uid, String packageName) {
15527                if (Process.isIsolated(uid)) {
15528                    return Zygote.MOUNT_EXTERNAL_NONE;
15529                }
15530                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15531                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15532                }
15533                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15534                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15535                }
15536                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15537                    return Zygote.MOUNT_EXTERNAL_READ;
15538                }
15539                return Zygote.MOUNT_EXTERNAL_WRITE;
15540            }
15541
15542            @Override
15543            public boolean hasExternalStorage(int uid, String packageName) {
15544                return true;
15545            }
15546        });
15547    }
15548
15549    @Override
15550    public boolean isSafeMode() {
15551        return mSafeMode;
15552    }
15553
15554    @Override
15555    public boolean hasSystemUidErrors() {
15556        return mHasSystemUidErrors;
15557    }
15558
15559    static String arrayToString(int[] array) {
15560        StringBuffer buf = new StringBuffer(128);
15561        buf.append('[');
15562        if (array != null) {
15563            for (int i=0; i<array.length; i++) {
15564                if (i > 0) buf.append(", ");
15565                buf.append(array[i]);
15566            }
15567        }
15568        buf.append(']');
15569        return buf.toString();
15570    }
15571
15572    static class DumpState {
15573        public static final int DUMP_LIBS = 1 << 0;
15574        public static final int DUMP_FEATURES = 1 << 1;
15575        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15576        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15577        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15578        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15579        public static final int DUMP_PERMISSIONS = 1 << 6;
15580        public static final int DUMP_PACKAGES = 1 << 7;
15581        public static final int DUMP_SHARED_USERS = 1 << 8;
15582        public static final int DUMP_MESSAGES = 1 << 9;
15583        public static final int DUMP_PROVIDERS = 1 << 10;
15584        public static final int DUMP_VERIFIERS = 1 << 11;
15585        public static final int DUMP_PREFERRED = 1 << 12;
15586        public static final int DUMP_PREFERRED_XML = 1 << 13;
15587        public static final int DUMP_KEYSETS = 1 << 14;
15588        public static final int DUMP_VERSION = 1 << 15;
15589        public static final int DUMP_INSTALLS = 1 << 16;
15590        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15591        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15592
15593        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15594
15595        private int mTypes;
15596
15597        private int mOptions;
15598
15599        private boolean mTitlePrinted;
15600
15601        private SharedUserSetting mSharedUser;
15602
15603        public boolean isDumping(int type) {
15604            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15605                return true;
15606            }
15607
15608            return (mTypes & type) != 0;
15609        }
15610
15611        public void setDump(int type) {
15612            mTypes |= type;
15613        }
15614
15615        public boolean isOptionEnabled(int option) {
15616            return (mOptions & option) != 0;
15617        }
15618
15619        public void setOptionEnabled(int option) {
15620            mOptions |= option;
15621        }
15622
15623        public boolean onTitlePrinted() {
15624            final boolean printed = mTitlePrinted;
15625            mTitlePrinted = true;
15626            return printed;
15627        }
15628
15629        public boolean getTitlePrinted() {
15630            return mTitlePrinted;
15631        }
15632
15633        public void setTitlePrinted(boolean enabled) {
15634            mTitlePrinted = enabled;
15635        }
15636
15637        public SharedUserSetting getSharedUser() {
15638            return mSharedUser;
15639        }
15640
15641        public void setSharedUser(SharedUserSetting user) {
15642            mSharedUser = user;
15643        }
15644    }
15645
15646    @Override
15647    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15648            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15649        (new PackageManagerShellCommand(this)).exec(
15650                this, in, out, err, args, resultReceiver);
15651    }
15652
15653    @Override
15654    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15655        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15656                != PackageManager.PERMISSION_GRANTED) {
15657            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15658                    + Binder.getCallingPid()
15659                    + ", uid=" + Binder.getCallingUid()
15660                    + " without permission "
15661                    + android.Manifest.permission.DUMP);
15662            return;
15663        }
15664
15665        DumpState dumpState = new DumpState();
15666        boolean fullPreferred = false;
15667        boolean checkin = false;
15668
15669        String packageName = null;
15670        ArraySet<String> permissionNames = null;
15671
15672        int opti = 0;
15673        while (opti < args.length) {
15674            String opt = args[opti];
15675            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15676                break;
15677            }
15678            opti++;
15679
15680            if ("-a".equals(opt)) {
15681                // Right now we only know how to print all.
15682            } else if ("-h".equals(opt)) {
15683                pw.println("Package manager dump options:");
15684                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15685                pw.println("    --checkin: dump for a checkin");
15686                pw.println("    -f: print details of intent filters");
15687                pw.println("    -h: print this help");
15688                pw.println("  cmd may be one of:");
15689                pw.println("    l[ibraries]: list known shared libraries");
15690                pw.println("    f[eatures]: list device features");
15691                pw.println("    k[eysets]: print known keysets");
15692                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15693                pw.println("    perm[issions]: dump permissions");
15694                pw.println("    permission [name ...]: dump declaration and use of given permission");
15695                pw.println("    pref[erred]: print preferred package settings");
15696                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15697                pw.println("    prov[iders]: dump content providers");
15698                pw.println("    p[ackages]: dump installed packages");
15699                pw.println("    s[hared-users]: dump shared user IDs");
15700                pw.println("    m[essages]: print collected runtime messages");
15701                pw.println("    v[erifiers]: print package verifier info");
15702                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15703                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15704                pw.println("    version: print database version info");
15705                pw.println("    write: write current settings now");
15706                pw.println("    installs: details about install sessions");
15707                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15708                pw.println("    <package.name>: info about given package");
15709                return;
15710            } else if ("--checkin".equals(opt)) {
15711                checkin = true;
15712            } else if ("-f".equals(opt)) {
15713                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15714            } else {
15715                pw.println("Unknown argument: " + opt + "; use -h for help");
15716            }
15717        }
15718
15719        // Is the caller requesting to dump a particular piece of data?
15720        if (opti < args.length) {
15721            String cmd = args[opti];
15722            opti++;
15723            // Is this a package name?
15724            if ("android".equals(cmd) || cmd.contains(".")) {
15725                packageName = cmd;
15726                // When dumping a single package, we always dump all of its
15727                // filter information since the amount of data will be reasonable.
15728                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15729            } else if ("check-permission".equals(cmd)) {
15730                if (opti >= args.length) {
15731                    pw.println("Error: check-permission missing permission argument");
15732                    return;
15733                }
15734                String perm = args[opti];
15735                opti++;
15736                if (opti >= args.length) {
15737                    pw.println("Error: check-permission missing package argument");
15738                    return;
15739                }
15740                String pkg = args[opti];
15741                opti++;
15742                int user = UserHandle.getUserId(Binder.getCallingUid());
15743                if (opti < args.length) {
15744                    try {
15745                        user = Integer.parseInt(args[opti]);
15746                    } catch (NumberFormatException e) {
15747                        pw.println("Error: check-permission user argument is not a number: "
15748                                + args[opti]);
15749                        return;
15750                    }
15751                }
15752                pw.println(checkPermission(perm, pkg, user));
15753                return;
15754            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15755                dumpState.setDump(DumpState.DUMP_LIBS);
15756            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15757                dumpState.setDump(DumpState.DUMP_FEATURES);
15758            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15759                if (opti >= args.length) {
15760                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15761                            | DumpState.DUMP_SERVICE_RESOLVERS
15762                            | DumpState.DUMP_RECEIVER_RESOLVERS
15763                            | DumpState.DUMP_CONTENT_RESOLVERS);
15764                } else {
15765                    while (opti < args.length) {
15766                        String name = args[opti];
15767                        if ("a".equals(name) || "activity".equals(name)) {
15768                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15769                        } else if ("s".equals(name) || "service".equals(name)) {
15770                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15771                        } else if ("r".equals(name) || "receiver".equals(name)) {
15772                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15773                        } else if ("c".equals(name) || "content".equals(name)) {
15774                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15775                        } else {
15776                            pw.println("Error: unknown resolver table type: " + name);
15777                            return;
15778                        }
15779                        opti++;
15780                    }
15781                }
15782            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15783                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15784            } else if ("permission".equals(cmd)) {
15785                if (opti >= args.length) {
15786                    pw.println("Error: permission requires permission name");
15787                    return;
15788                }
15789                permissionNames = new ArraySet<>();
15790                while (opti < args.length) {
15791                    permissionNames.add(args[opti]);
15792                    opti++;
15793                }
15794                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15795                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15796            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15797                dumpState.setDump(DumpState.DUMP_PREFERRED);
15798            } else if ("preferred-xml".equals(cmd)) {
15799                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15800                if (opti < args.length && "--full".equals(args[opti])) {
15801                    fullPreferred = true;
15802                    opti++;
15803                }
15804            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15805                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15806            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15807                dumpState.setDump(DumpState.DUMP_PACKAGES);
15808            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15809                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15810            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15811                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15812            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15813                dumpState.setDump(DumpState.DUMP_MESSAGES);
15814            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15815                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15816            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15817                    || "intent-filter-verifiers".equals(cmd)) {
15818                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15819            } else if ("version".equals(cmd)) {
15820                dumpState.setDump(DumpState.DUMP_VERSION);
15821            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15822                dumpState.setDump(DumpState.DUMP_KEYSETS);
15823            } else if ("installs".equals(cmd)) {
15824                dumpState.setDump(DumpState.DUMP_INSTALLS);
15825            } else if ("write".equals(cmd)) {
15826                synchronized (mPackages) {
15827                    mSettings.writeLPr();
15828                    pw.println("Settings written.");
15829                    return;
15830                }
15831            }
15832        }
15833
15834        if (checkin) {
15835            pw.println("vers,1");
15836        }
15837
15838        // reader
15839        synchronized (mPackages) {
15840            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15841                if (!checkin) {
15842                    if (dumpState.onTitlePrinted())
15843                        pw.println();
15844                    pw.println("Database versions:");
15845                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15846                }
15847            }
15848
15849            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15850                if (!checkin) {
15851                    if (dumpState.onTitlePrinted())
15852                        pw.println();
15853                    pw.println("Verifiers:");
15854                    pw.print("  Required: ");
15855                    pw.print(mRequiredVerifierPackage);
15856                    pw.print(" (uid=");
15857                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15858                            UserHandle.USER_SYSTEM));
15859                    pw.println(")");
15860                } else if (mRequiredVerifierPackage != null) {
15861                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15862                    pw.print(",");
15863                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15864                            UserHandle.USER_SYSTEM));
15865                }
15866            }
15867
15868            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15869                    packageName == null) {
15870                if (mIntentFilterVerifierComponent != null) {
15871                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15872                    if (!checkin) {
15873                        if (dumpState.onTitlePrinted())
15874                            pw.println();
15875                        pw.println("Intent Filter Verifier:");
15876                        pw.print("  Using: ");
15877                        pw.print(verifierPackageName);
15878                        pw.print(" (uid=");
15879                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15880                                UserHandle.USER_SYSTEM));
15881                        pw.println(")");
15882                    } else if (verifierPackageName != null) {
15883                        pw.print("ifv,"); pw.print(verifierPackageName);
15884                        pw.print(",");
15885                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15886                                UserHandle.USER_SYSTEM));
15887                    }
15888                } else {
15889                    pw.println();
15890                    pw.println("No Intent Filter Verifier available!");
15891                }
15892            }
15893
15894            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15895                boolean printedHeader = false;
15896                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15897                while (it.hasNext()) {
15898                    String name = it.next();
15899                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15900                    if (!checkin) {
15901                        if (!printedHeader) {
15902                            if (dumpState.onTitlePrinted())
15903                                pw.println();
15904                            pw.println("Libraries:");
15905                            printedHeader = true;
15906                        }
15907                        pw.print("  ");
15908                    } else {
15909                        pw.print("lib,");
15910                    }
15911                    pw.print(name);
15912                    if (!checkin) {
15913                        pw.print(" -> ");
15914                    }
15915                    if (ent.path != null) {
15916                        if (!checkin) {
15917                            pw.print("(jar) ");
15918                            pw.print(ent.path);
15919                        } else {
15920                            pw.print(",jar,");
15921                            pw.print(ent.path);
15922                        }
15923                    } else {
15924                        if (!checkin) {
15925                            pw.print("(apk) ");
15926                            pw.print(ent.apk);
15927                        } else {
15928                            pw.print(",apk,");
15929                            pw.print(ent.apk);
15930                        }
15931                    }
15932                    pw.println();
15933                }
15934            }
15935
15936            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15937                if (dumpState.onTitlePrinted())
15938                    pw.println();
15939                if (!checkin) {
15940                    pw.println("Features:");
15941                }
15942                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15943                while (it.hasNext()) {
15944                    String name = it.next();
15945                    if (!checkin) {
15946                        pw.print("  ");
15947                    } else {
15948                        pw.print("feat,");
15949                    }
15950                    pw.println(name);
15951                }
15952            }
15953
15954            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15955                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15956                        : "Activity Resolver Table:", "  ", packageName,
15957                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15958                    dumpState.setTitlePrinted(true);
15959                }
15960            }
15961            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15962                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15963                        : "Receiver Resolver Table:", "  ", packageName,
15964                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15965                    dumpState.setTitlePrinted(true);
15966                }
15967            }
15968            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15969                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15970                        : "Service Resolver Table:", "  ", packageName,
15971                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15972                    dumpState.setTitlePrinted(true);
15973                }
15974            }
15975            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15976                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15977                        : "Provider Resolver Table:", "  ", packageName,
15978                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15979                    dumpState.setTitlePrinted(true);
15980                }
15981            }
15982
15983            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15984                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15985                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15986                    int user = mSettings.mPreferredActivities.keyAt(i);
15987                    if (pir.dump(pw,
15988                            dumpState.getTitlePrinted()
15989                                ? "\nPreferred Activities User " + user + ":"
15990                                : "Preferred Activities User " + user + ":", "  ",
15991                            packageName, true, false)) {
15992                        dumpState.setTitlePrinted(true);
15993                    }
15994                }
15995            }
15996
15997            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15998                pw.flush();
15999                FileOutputStream fout = new FileOutputStream(fd);
16000                BufferedOutputStream str = new BufferedOutputStream(fout);
16001                XmlSerializer serializer = new FastXmlSerializer();
16002                try {
16003                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16004                    serializer.startDocument(null, true);
16005                    serializer.setFeature(
16006                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16007                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16008                    serializer.endDocument();
16009                    serializer.flush();
16010                } catch (IllegalArgumentException e) {
16011                    pw.println("Failed writing: " + e);
16012                } catch (IllegalStateException e) {
16013                    pw.println("Failed writing: " + e);
16014                } catch (IOException e) {
16015                    pw.println("Failed writing: " + e);
16016                }
16017            }
16018
16019            if (!checkin
16020                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16021                    && packageName == null) {
16022                pw.println();
16023                int count = mSettings.mPackages.size();
16024                if (count == 0) {
16025                    pw.println("No applications!");
16026                    pw.println();
16027                } else {
16028                    final String prefix = "  ";
16029                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16030                    if (allPackageSettings.size() == 0) {
16031                        pw.println("No domain preferred apps!");
16032                        pw.println();
16033                    } else {
16034                        pw.println("App verification status:");
16035                        pw.println();
16036                        count = 0;
16037                        for (PackageSetting ps : allPackageSettings) {
16038                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16039                            if (ivi == null || ivi.getPackageName() == null) continue;
16040                            pw.println(prefix + "Package: " + ivi.getPackageName());
16041                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16042                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16043                            pw.println();
16044                            count++;
16045                        }
16046                        if (count == 0) {
16047                            pw.println(prefix + "No app verification established.");
16048                            pw.println();
16049                        }
16050                        for (int userId : sUserManager.getUserIds()) {
16051                            pw.println("App linkages for user " + userId + ":");
16052                            pw.println();
16053                            count = 0;
16054                            for (PackageSetting ps : allPackageSettings) {
16055                                final long status = ps.getDomainVerificationStatusForUser(userId);
16056                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16057                                    continue;
16058                                }
16059                                pw.println(prefix + "Package: " + ps.name);
16060                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16061                                String statusStr = IntentFilterVerificationInfo.
16062                                        getStatusStringFromValue(status);
16063                                pw.println(prefix + "Status:  " + statusStr);
16064                                pw.println();
16065                                count++;
16066                            }
16067                            if (count == 0) {
16068                                pw.println(prefix + "No configured app linkages.");
16069                                pw.println();
16070                            }
16071                        }
16072                    }
16073                }
16074            }
16075
16076            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16077                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16078                if (packageName == null && permissionNames == null) {
16079                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16080                        if (iperm == 0) {
16081                            if (dumpState.onTitlePrinted())
16082                                pw.println();
16083                            pw.println("AppOp Permissions:");
16084                        }
16085                        pw.print("  AppOp Permission ");
16086                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16087                        pw.println(":");
16088                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16089                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16090                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16091                        }
16092                    }
16093                }
16094            }
16095
16096            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16097                boolean printedSomething = false;
16098                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16099                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16100                        continue;
16101                    }
16102                    if (!printedSomething) {
16103                        if (dumpState.onTitlePrinted())
16104                            pw.println();
16105                        pw.println("Registered ContentProviders:");
16106                        printedSomething = true;
16107                    }
16108                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16109                    pw.print("    "); pw.println(p.toString());
16110                }
16111                printedSomething = false;
16112                for (Map.Entry<String, PackageParser.Provider> entry :
16113                        mProvidersByAuthority.entrySet()) {
16114                    PackageParser.Provider p = entry.getValue();
16115                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16116                        continue;
16117                    }
16118                    if (!printedSomething) {
16119                        if (dumpState.onTitlePrinted())
16120                            pw.println();
16121                        pw.println("ContentProvider Authorities:");
16122                        printedSomething = true;
16123                    }
16124                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16125                    pw.print("    "); pw.println(p.toString());
16126                    if (p.info != null && p.info.applicationInfo != null) {
16127                        final String appInfo = p.info.applicationInfo.toString();
16128                        pw.print("      applicationInfo="); pw.println(appInfo);
16129                    }
16130                }
16131            }
16132
16133            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16134                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16135            }
16136
16137            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16138                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16139            }
16140
16141            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16142                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16143            }
16144
16145            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16146                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16147            }
16148
16149            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16150                // XXX should handle packageName != null by dumping only install data that
16151                // the given package is involved with.
16152                if (dumpState.onTitlePrinted()) pw.println();
16153                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16154            }
16155
16156            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16157                if (dumpState.onTitlePrinted()) pw.println();
16158                mSettings.dumpReadMessagesLPr(pw, dumpState);
16159
16160                pw.println();
16161                pw.println("Package warning messages:");
16162                BufferedReader in = null;
16163                String line = null;
16164                try {
16165                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16166                    while ((line = in.readLine()) != null) {
16167                        if (line.contains("ignored: updated version")) continue;
16168                        pw.println(line);
16169                    }
16170                } catch (IOException ignored) {
16171                } finally {
16172                    IoUtils.closeQuietly(in);
16173                }
16174            }
16175
16176            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16177                BufferedReader in = null;
16178                String line = null;
16179                try {
16180                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16181                    while ((line = in.readLine()) != null) {
16182                        if (line.contains("ignored: updated version")) continue;
16183                        pw.print("msg,");
16184                        pw.println(line);
16185                    }
16186                } catch (IOException ignored) {
16187                } finally {
16188                    IoUtils.closeQuietly(in);
16189                }
16190            }
16191        }
16192    }
16193
16194    private String dumpDomainString(String packageName) {
16195        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16196        List<IntentFilter> filters = getAllIntentFilters(packageName);
16197
16198        ArraySet<String> result = new ArraySet<>();
16199        if (iviList.size() > 0) {
16200            for (IntentFilterVerificationInfo ivi : iviList) {
16201                for (String host : ivi.getDomains()) {
16202                    result.add(host);
16203                }
16204            }
16205        }
16206        if (filters != null && filters.size() > 0) {
16207            for (IntentFilter filter : filters) {
16208                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16209                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16210                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16211                    result.addAll(filter.getHostsList());
16212                }
16213            }
16214        }
16215
16216        StringBuilder sb = new StringBuilder(result.size() * 16);
16217        for (String domain : result) {
16218            if (sb.length() > 0) sb.append(" ");
16219            sb.append(domain);
16220        }
16221        return sb.toString();
16222    }
16223
16224    // ------- apps on sdcard specific code -------
16225    static final boolean DEBUG_SD_INSTALL = false;
16226
16227    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16228
16229    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16230
16231    private boolean mMediaMounted = false;
16232
16233    static String getEncryptKey() {
16234        try {
16235            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16236                    SD_ENCRYPTION_KEYSTORE_NAME);
16237            if (sdEncKey == null) {
16238                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16239                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16240                if (sdEncKey == null) {
16241                    Slog.e(TAG, "Failed to create encryption keys");
16242                    return null;
16243                }
16244            }
16245            return sdEncKey;
16246        } catch (NoSuchAlgorithmException nsae) {
16247            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16248            return null;
16249        } catch (IOException ioe) {
16250            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16251            return null;
16252        }
16253    }
16254
16255    /*
16256     * Update media status on PackageManager.
16257     */
16258    @Override
16259    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16260        int callingUid = Binder.getCallingUid();
16261        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16262            throw new SecurityException("Media status can only be updated by the system");
16263        }
16264        // reader; this apparently protects mMediaMounted, but should probably
16265        // be a different lock in that case.
16266        synchronized (mPackages) {
16267            Log.i(TAG, "Updating external media status from "
16268                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16269                    + (mediaStatus ? "mounted" : "unmounted"));
16270            if (DEBUG_SD_INSTALL)
16271                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16272                        + ", mMediaMounted=" + mMediaMounted);
16273            if (mediaStatus == mMediaMounted) {
16274                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16275                        : 0, -1);
16276                mHandler.sendMessage(msg);
16277                return;
16278            }
16279            mMediaMounted = mediaStatus;
16280        }
16281        // Queue up an async operation since the package installation may take a
16282        // little while.
16283        mHandler.post(new Runnable() {
16284            public void run() {
16285                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16286            }
16287        });
16288    }
16289
16290    /**
16291     * Called by MountService when the initial ASECs to scan are available.
16292     * Should block until all the ASEC containers are finished being scanned.
16293     */
16294    public void scanAvailableAsecs() {
16295        updateExternalMediaStatusInner(true, false, false);
16296    }
16297
16298    /*
16299     * Collect information of applications on external media, map them against
16300     * existing containers and update information based on current mount status.
16301     * Please note that we always have to report status if reportStatus has been
16302     * set to true especially when unloading packages.
16303     */
16304    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16305            boolean externalStorage) {
16306        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16307        int[] uidArr = EmptyArray.INT;
16308
16309        final String[] list = PackageHelper.getSecureContainerList();
16310        if (ArrayUtils.isEmpty(list)) {
16311            Log.i(TAG, "No secure containers found");
16312        } else {
16313            // Process list of secure containers and categorize them
16314            // as active or stale based on their package internal state.
16315
16316            // reader
16317            synchronized (mPackages) {
16318                for (String cid : list) {
16319                    // Leave stages untouched for now; installer service owns them
16320                    if (PackageInstallerService.isStageName(cid)) continue;
16321
16322                    if (DEBUG_SD_INSTALL)
16323                        Log.i(TAG, "Processing container " + cid);
16324                    String pkgName = getAsecPackageName(cid);
16325                    if (pkgName == null) {
16326                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16327                        continue;
16328                    }
16329                    if (DEBUG_SD_INSTALL)
16330                        Log.i(TAG, "Looking for pkg : " + pkgName);
16331
16332                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16333                    if (ps == null) {
16334                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16335                        continue;
16336                    }
16337
16338                    /*
16339                     * Skip packages that are not external if we're unmounting
16340                     * external storage.
16341                     */
16342                    if (externalStorage && !isMounted && !isExternal(ps)) {
16343                        continue;
16344                    }
16345
16346                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16347                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16348                    // The package status is changed only if the code path
16349                    // matches between settings and the container id.
16350                    if (ps.codePathString != null
16351                            && ps.codePathString.startsWith(args.getCodePath())) {
16352                        if (DEBUG_SD_INSTALL) {
16353                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16354                                    + " at code path: " + ps.codePathString);
16355                        }
16356
16357                        // We do have a valid package installed on sdcard
16358                        processCids.put(args, ps.codePathString);
16359                        final int uid = ps.appId;
16360                        if (uid != -1) {
16361                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16362                        }
16363                    } else {
16364                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16365                                + ps.codePathString);
16366                    }
16367                }
16368            }
16369
16370            Arrays.sort(uidArr);
16371        }
16372
16373        // Process packages with valid entries.
16374        if (isMounted) {
16375            if (DEBUG_SD_INSTALL)
16376                Log.i(TAG, "Loading packages");
16377            loadMediaPackages(processCids, uidArr, externalStorage);
16378            startCleaningPackages();
16379            mInstallerService.onSecureContainersAvailable();
16380        } else {
16381            if (DEBUG_SD_INSTALL)
16382                Log.i(TAG, "Unloading packages");
16383            unloadMediaPackages(processCids, uidArr, reportStatus);
16384        }
16385    }
16386
16387    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16388            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16389        final int size = infos.size();
16390        final String[] packageNames = new String[size];
16391        final int[] packageUids = new int[size];
16392        for (int i = 0; i < size; i++) {
16393            final ApplicationInfo info = infos.get(i);
16394            packageNames[i] = info.packageName;
16395            packageUids[i] = info.uid;
16396        }
16397        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16398                finishedReceiver);
16399    }
16400
16401    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16402            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16403        sendResourcesChangedBroadcast(mediaStatus, replacing,
16404                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16405    }
16406
16407    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16408            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16409        int size = pkgList.length;
16410        if (size > 0) {
16411            // Send broadcasts here
16412            Bundle extras = new Bundle();
16413            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16414            if (uidArr != null) {
16415                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16416            }
16417            if (replacing) {
16418                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16419            }
16420            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16421                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16422            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16423        }
16424    }
16425
16426   /*
16427     * Look at potentially valid container ids from processCids If package
16428     * information doesn't match the one on record or package scanning fails,
16429     * the cid is added to list of removeCids. We currently don't delete stale
16430     * containers.
16431     */
16432    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16433            boolean externalStorage) {
16434        ArrayList<String> pkgList = new ArrayList<String>();
16435        Set<AsecInstallArgs> keys = processCids.keySet();
16436
16437        for (AsecInstallArgs args : keys) {
16438            String codePath = processCids.get(args);
16439            if (DEBUG_SD_INSTALL)
16440                Log.i(TAG, "Loading container : " + args.cid);
16441            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16442            try {
16443                // Make sure there are no container errors first.
16444                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16445                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16446                            + " when installing from sdcard");
16447                    continue;
16448                }
16449                // Check code path here.
16450                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16451                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16452                            + " does not match one in settings " + codePath);
16453                    continue;
16454                }
16455                // Parse package
16456                int parseFlags = mDefParseFlags;
16457                if (args.isExternalAsec()) {
16458                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16459                }
16460                if (args.isFwdLocked()) {
16461                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16462                }
16463
16464                synchronized (mInstallLock) {
16465                    PackageParser.Package pkg = null;
16466                    try {
16467                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16468                    } catch (PackageManagerException e) {
16469                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16470                    }
16471                    // Scan the package
16472                    if (pkg != null) {
16473                        /*
16474                         * TODO why is the lock being held? doPostInstall is
16475                         * called in other places without the lock. This needs
16476                         * to be straightened out.
16477                         */
16478                        // writer
16479                        synchronized (mPackages) {
16480                            retCode = PackageManager.INSTALL_SUCCEEDED;
16481                            pkgList.add(pkg.packageName);
16482                            // Post process args
16483                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16484                                    pkg.applicationInfo.uid);
16485                        }
16486                    } else {
16487                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16488                    }
16489                }
16490
16491            } finally {
16492                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16493                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16494                }
16495            }
16496        }
16497        // writer
16498        synchronized (mPackages) {
16499            // If the platform SDK has changed since the last time we booted,
16500            // we need to re-grant app permission to catch any new ones that
16501            // appear. This is really a hack, and means that apps can in some
16502            // cases get permissions that the user didn't initially explicitly
16503            // allow... it would be nice to have some better way to handle
16504            // this situation.
16505            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16506                    : mSettings.getInternalVersion();
16507            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16508                    : StorageManager.UUID_PRIVATE_INTERNAL;
16509
16510            int updateFlags = UPDATE_PERMISSIONS_ALL;
16511            if (ver.sdkVersion != mSdkVersion) {
16512                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16513                        + mSdkVersion + "; regranting permissions for external");
16514                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16515            }
16516            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16517
16518            // Yay, everything is now upgraded
16519            ver.forceCurrent();
16520
16521            // can downgrade to reader
16522            // Persist settings
16523            mSettings.writeLPr();
16524        }
16525        // Send a broadcast to let everyone know we are done processing
16526        if (pkgList.size() > 0) {
16527            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16528        }
16529    }
16530
16531   /*
16532     * Utility method to unload a list of specified containers
16533     */
16534    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16535        // Just unmount all valid containers.
16536        for (AsecInstallArgs arg : cidArgs) {
16537            synchronized (mInstallLock) {
16538                arg.doPostDeleteLI(false);
16539           }
16540       }
16541   }
16542
16543    /*
16544     * Unload packages mounted on external media. This involves deleting package
16545     * data from internal structures, sending broadcasts about diabled packages,
16546     * gc'ing to free up references, unmounting all secure containers
16547     * corresponding to packages on external media, and posting a
16548     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16549     * that we always have to post this message if status has been requested no
16550     * matter what.
16551     */
16552    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16553            final boolean reportStatus) {
16554        if (DEBUG_SD_INSTALL)
16555            Log.i(TAG, "unloading media packages");
16556        ArrayList<String> pkgList = new ArrayList<String>();
16557        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16558        final Set<AsecInstallArgs> keys = processCids.keySet();
16559        for (AsecInstallArgs args : keys) {
16560            String pkgName = args.getPackageName();
16561            if (DEBUG_SD_INSTALL)
16562                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16563            // Delete package internally
16564            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16565            synchronized (mInstallLock) {
16566                boolean res = deletePackageLI(pkgName, null, false, null, null,
16567                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16568                if (res) {
16569                    pkgList.add(pkgName);
16570                } else {
16571                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16572                    failedList.add(args);
16573                }
16574            }
16575        }
16576
16577        // reader
16578        synchronized (mPackages) {
16579            // We didn't update the settings after removing each package;
16580            // write them now for all packages.
16581            mSettings.writeLPr();
16582        }
16583
16584        // We have to absolutely send UPDATED_MEDIA_STATUS only
16585        // after confirming that all the receivers processed the ordered
16586        // broadcast when packages get disabled, force a gc to clean things up.
16587        // and unload all the containers.
16588        if (pkgList.size() > 0) {
16589            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16590                    new IIntentReceiver.Stub() {
16591                public void performReceive(Intent intent, int resultCode, String data,
16592                        Bundle extras, boolean ordered, boolean sticky,
16593                        int sendingUser) throws RemoteException {
16594                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16595                            reportStatus ? 1 : 0, 1, keys);
16596                    mHandler.sendMessage(msg);
16597                }
16598            });
16599        } else {
16600            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16601                    keys);
16602            mHandler.sendMessage(msg);
16603        }
16604    }
16605
16606    private void loadPrivatePackages(final VolumeInfo vol) {
16607        mHandler.post(new Runnable() {
16608            @Override
16609            public void run() {
16610                loadPrivatePackagesInner(vol);
16611            }
16612        });
16613    }
16614
16615    private void loadPrivatePackagesInner(VolumeInfo vol) {
16616        final String volumeUuid = vol.fsUuid;
16617        if (TextUtils.isEmpty(volumeUuid)) {
16618            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16619            return;
16620        }
16621
16622        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16623        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16624
16625        final VersionInfo ver;
16626        final List<PackageSetting> packages;
16627        synchronized (mPackages) {
16628            ver = mSettings.findOrCreateVersion(volumeUuid);
16629            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16630        }
16631
16632        // TODO: introduce a new concept similar to "frozen" to prevent these
16633        // apps from being launched until after data has been fully reconciled
16634        for (PackageSetting ps : packages) {
16635            synchronized (mInstallLock) {
16636                final PackageParser.Package pkg;
16637                try {
16638                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16639                    loaded.add(pkg.applicationInfo);
16640
16641                } catch (PackageManagerException e) {
16642                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16643                }
16644
16645                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16646                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16647                }
16648            }
16649        }
16650
16651        // Reconcile app data for all started/unlocked users
16652        final UserManager um = mContext.getSystemService(UserManager.class);
16653        for (UserInfo user : um.getUsers()) {
16654            if (um.isUserUnlocked(user.id)) {
16655                reconcileAppsData(volumeUuid, user.id,
16656                        Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE);
16657            } else if (um.isUserRunning(user.id)) {
16658                reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE);
16659            } else {
16660                continue;
16661            }
16662        }
16663
16664        synchronized (mPackages) {
16665            int updateFlags = UPDATE_PERMISSIONS_ALL;
16666            if (ver.sdkVersion != mSdkVersion) {
16667                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16668                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16669                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16670            }
16671            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16672
16673            // Yay, everything is now upgraded
16674            ver.forceCurrent();
16675
16676            mSettings.writeLPr();
16677        }
16678
16679        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16680        sendResourcesChangedBroadcast(true, false, loaded, null);
16681    }
16682
16683    private void unloadPrivatePackages(final VolumeInfo vol) {
16684        mHandler.post(new Runnable() {
16685            @Override
16686            public void run() {
16687                unloadPrivatePackagesInner(vol);
16688            }
16689        });
16690    }
16691
16692    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16693        final String volumeUuid = vol.fsUuid;
16694        if (TextUtils.isEmpty(volumeUuid)) {
16695            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16696            return;
16697        }
16698
16699        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16700        synchronized (mInstallLock) {
16701        synchronized (mPackages) {
16702            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16703            for (PackageSetting ps : packages) {
16704                if (ps.pkg == null) continue;
16705
16706                final ApplicationInfo info = ps.pkg.applicationInfo;
16707                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16708                if (deletePackageLI(ps.name, null, false, null, null,
16709                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16710                    unloaded.add(info);
16711                } else {
16712                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16713                }
16714            }
16715
16716            mSettings.writeLPr();
16717        }
16718        }
16719
16720        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16721        sendResourcesChangedBroadcast(false, false, unloaded, null);
16722    }
16723
16724    /**
16725     * Examine all users present on given mounted volume, and destroy data
16726     * belonging to users that are no longer valid, or whose user ID has been
16727     * recycled.
16728     */
16729    private void reconcileUsers(String volumeUuid) {
16730        final File[] files = FileUtils
16731                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16732        for (File file : files) {
16733            if (!file.isDirectory()) continue;
16734
16735            final int userId;
16736            final UserInfo info;
16737            try {
16738                userId = Integer.parseInt(file.getName());
16739                info = sUserManager.getUserInfo(userId);
16740            } catch (NumberFormatException e) {
16741                Slog.w(TAG, "Invalid user directory " + file);
16742                continue;
16743            }
16744
16745            boolean destroyUser = false;
16746            if (info == null) {
16747                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16748                        + " because no matching user was found");
16749                destroyUser = true;
16750            } else {
16751                try {
16752                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16753                } catch (IOException e) {
16754                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16755                            + " because we failed to enforce serial number: " + e);
16756                    destroyUser = true;
16757                }
16758            }
16759
16760            if (destroyUser) {
16761                synchronized (mInstallLock) {
16762                    try {
16763                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16764                    } catch (InstallerException e) {
16765                        Slog.w(TAG, "Failed to clean up user dirs", e);
16766                    }
16767                }
16768            }
16769        }
16770
16771        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16772        final UserManager um = mContext.getSystemService(UserManager.class);
16773        for (UserInfo user : um.getUsers()) {
16774            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16775            if (userDir.exists()) continue;
16776
16777            try {
16778                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16779                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16780            } catch (IOException e) {
16781                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16782            }
16783        }
16784    }
16785
16786    private void assertPackageKnown(String volumeUuid, String packageName)
16787            throws PackageManagerException {
16788        synchronized (mPackages) {
16789            final PackageSetting ps = mSettings.mPackages.get(packageName);
16790            if (ps == null) {
16791                throw new PackageManagerException("Package " + packageName + " is unknown");
16792            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16793                throw new PackageManagerException(
16794                        "Package " + packageName + " found on unknown volume " + volumeUuid
16795                                + "; expected volume " + ps.volumeUuid);
16796            }
16797        }
16798    }
16799
16800    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16801            throws PackageManagerException {
16802        synchronized (mPackages) {
16803            final PackageSetting ps = mSettings.mPackages.get(packageName);
16804            if (ps == null) {
16805                throw new PackageManagerException("Package " + packageName + " is unknown");
16806            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16807                throw new PackageManagerException(
16808                        "Package " + packageName + " found on unknown volume " + volumeUuid
16809                                + "; expected volume " + ps.volumeUuid);
16810            } else if (!ps.getInstalled(userId)) {
16811                throw new PackageManagerException(
16812                        "Package " + packageName + " not installed for user " + userId);
16813            }
16814        }
16815    }
16816
16817    /**
16818     * Examine all apps present on given mounted volume, and destroy apps that
16819     * aren't expected, either due to uninstallation or reinstallation on
16820     * another volume.
16821     */
16822    private void reconcileApps(String volumeUuid) {
16823        final File[] files = FileUtils
16824                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16825        for (File file : files) {
16826            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16827                    && !PackageInstallerService.isStageName(file.getName());
16828            if (!isPackage) {
16829                // Ignore entries which are not packages
16830                continue;
16831            }
16832
16833            try {
16834                final PackageLite pkg = PackageParser.parsePackageLite(file,
16835                        PackageParser.PARSE_MUST_BE_APK);
16836                assertPackageKnown(volumeUuid, pkg.packageName);
16837
16838            } catch (PackageParserException | PackageManagerException e) {
16839                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16840                synchronized (mInstallLock) {
16841                    removeCodePathLI(file);
16842                }
16843            }
16844        }
16845    }
16846
16847    /**
16848     * Reconcile all app data for the given user.
16849     * <p>
16850     * Verifies that directories exist and that ownership and labeling is
16851     * correct for all installed apps on all mounted volumes.
16852     */
16853    void reconcileAppsData(int userId, @StorageFlags int flags) {
16854        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16855        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16856            final String volumeUuid = vol.getFsUuid();
16857            reconcileAppsData(volumeUuid, userId, flags);
16858        }
16859    }
16860
16861    /**
16862     * Reconcile all app data on given mounted volume.
16863     * <p>
16864     * Destroys app data that isn't expected, either due to uninstallation or
16865     * reinstallation on another volume.
16866     * <p>
16867     * Verifies that directories exist and that ownership and labeling is
16868     * correct for all installed apps.
16869     */
16870    private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) {
16871        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
16872                + Integer.toHexString(flags));
16873
16874        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
16875        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
16876
16877        boolean restoreconNeeded = false;
16878
16879        // First look for stale data that doesn't belong, and check if things
16880        // have changed since we did our last restorecon
16881        if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16882            if (!isUserKeyUnlocked(userId)) {
16883                throw new RuntimeException(
16884                        "Yikes, someone asked us to reconcile CE storage while " + userId
16885                                + " was still locked; this would have caused massive data loss!");
16886            }
16887
16888            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
16889
16890            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
16891            for (File file : files) {
16892                final String packageName = file.getName();
16893                try {
16894                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16895                } catch (PackageManagerException e) {
16896                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16897                    synchronized (mInstallLock) {
16898                        destroyAppDataLI(volumeUuid, packageName, userId,
16899                                Installer.FLAG_CE_STORAGE);
16900                    }
16901                }
16902            }
16903        }
16904        if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16905            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
16906
16907            final File[] files = FileUtils.listFilesOrEmpty(deDir);
16908            for (File file : files) {
16909                final String packageName = file.getName();
16910                try {
16911                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16912                } catch (PackageManagerException e) {
16913                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16914                    synchronized (mInstallLock) {
16915                        destroyAppDataLI(volumeUuid, packageName, userId,
16916                                Installer.FLAG_DE_STORAGE);
16917                    }
16918                }
16919            }
16920        }
16921
16922        // Ensure that data directories are ready to roll for all packages
16923        // installed for this volume and user
16924        final List<PackageSetting> packages;
16925        synchronized (mPackages) {
16926            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16927        }
16928        int preparedCount = 0;
16929        for (PackageSetting ps : packages) {
16930            final String packageName = ps.name;
16931            if (ps.pkg == null) {
16932                Slog.w(TAG, "Odd, missing scanned package " + packageName);
16933                // TODO: might be due to legacy ASEC apps; we should circle back
16934                // and reconcile again once they're scanned
16935                continue;
16936            }
16937
16938            if (ps.getInstalled(userId)) {
16939                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
16940                preparedCount++;
16941            }
16942        }
16943
16944        if (restoreconNeeded) {
16945            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16946                SELinuxMMAC.setRestoreconDone(ceDir);
16947            }
16948            if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16949                SELinuxMMAC.setRestoreconDone(deDir);
16950            }
16951        }
16952
16953        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
16954                + " packages; restoreconNeeded was " + restoreconNeeded);
16955    }
16956
16957    /**
16958     * Prepare app data for the given app just after it was installed or
16959     * upgraded. This method carefully only touches users that it's installed
16960     * for, and it forces a restorecon to handle any seinfo changes.
16961     * <p>
16962     * Verifies that directories exist and that ownership and labeling is
16963     * correct for all installed apps. If there is an ownership mismatch, it
16964     * will try recovering system apps by wiping data; third-party app data is
16965     * left intact.
16966     */
16967    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
16968        final PackageSetting ps;
16969        synchronized (mPackages) {
16970            ps = mSettings.mPackages.get(pkg.packageName);
16971        }
16972
16973        final UserManager um = mContext.getSystemService(UserManager.class);
16974        for (UserInfo user : um.getUsers()) {
16975            final int flags;
16976            if (um.isUserUnlocked(user.id)) {
16977                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
16978            } else if (um.isUserRunning(user.id)) {
16979                flags = Installer.FLAG_DE_STORAGE;
16980            } else {
16981                continue;
16982            }
16983
16984            if (ps.getInstalled(user.id)) {
16985                // Whenever an app changes, force a restorecon of its data
16986                // TODO: when user data is locked, mark that we're still dirty
16987                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
16988            }
16989        }
16990    }
16991
16992    /**
16993     * Prepare app data for the given app.
16994     * <p>
16995     * Verifies that directories exist and that ownership and labeling is
16996     * correct for all installed apps. If there is an ownership mismatch, this
16997     * will try recovering system apps by wiping data; third-party app data is
16998     * left intact.
16999     */
17000    private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags,
17001            PackageParser.Package pkg, boolean restoreconNeeded) {
17002        if (DEBUG_APP_DATA) {
17003            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17004                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17005        }
17006
17007        final String packageName = pkg.packageName;
17008        final ApplicationInfo app = pkg.applicationInfo;
17009        final int appId = UserHandle.getAppId(app.uid);
17010
17011        Preconditions.checkNotNull(app.seinfo);
17012
17013        synchronized (mInstallLock) {
17014            try {
17015                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17016                        appId, app.seinfo, app.targetSdkVersion);
17017            } catch (InstallerException e) {
17018                if (app.isSystemApp()) {
17019                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17020                            + ", but trying to recover: " + e);
17021                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17022                    try {
17023                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17024                                appId, app.seinfo, app.targetSdkVersion);
17025                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17026                    } catch (InstallerException e2) {
17027                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17028                    }
17029                } else {
17030                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17031                }
17032            }
17033
17034            if (restoreconNeeded) {
17035                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17036            }
17037
17038            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17039                // Create a native library symlink only if we have native libraries
17040                // and if the native libraries are 32 bit libraries. We do not provide
17041                // this symlink for 64 bit libraries.
17042                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17043                    final String nativeLibPath = app.nativeLibraryDir;
17044                    try {
17045                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17046                                nativeLibPath, userId);
17047                    } catch (InstallerException e) {
17048                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17049                    }
17050                }
17051            }
17052        }
17053    }
17054
17055    private void unfreezePackage(String packageName) {
17056        synchronized (mPackages) {
17057            final PackageSetting ps = mSettings.mPackages.get(packageName);
17058            if (ps != null) {
17059                ps.frozen = false;
17060            }
17061        }
17062    }
17063
17064    @Override
17065    public int movePackage(final String packageName, final String volumeUuid) {
17066        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17067
17068        final int moveId = mNextMoveId.getAndIncrement();
17069        mHandler.post(new Runnable() {
17070            @Override
17071            public void run() {
17072                try {
17073                    movePackageInternal(packageName, volumeUuid, moveId);
17074                } catch (PackageManagerException e) {
17075                    Slog.w(TAG, "Failed to move " + packageName, e);
17076                    mMoveCallbacks.notifyStatusChanged(moveId,
17077                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17078                }
17079            }
17080        });
17081        return moveId;
17082    }
17083
17084    private void movePackageInternal(final String packageName, final String volumeUuid,
17085            final int moveId) throws PackageManagerException {
17086        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17087        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17088        final PackageManager pm = mContext.getPackageManager();
17089
17090        final boolean currentAsec;
17091        final String currentVolumeUuid;
17092        final File codeFile;
17093        final String installerPackageName;
17094        final String packageAbiOverride;
17095        final int appId;
17096        final String seinfo;
17097        final String label;
17098        final int targetSdkVersion;
17099
17100        // reader
17101        synchronized (mPackages) {
17102            final PackageParser.Package pkg = mPackages.get(packageName);
17103            final PackageSetting ps = mSettings.mPackages.get(packageName);
17104            if (pkg == null || ps == null) {
17105                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17106            }
17107
17108            if (pkg.applicationInfo.isSystemApp()) {
17109                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17110                        "Cannot move system application");
17111            }
17112
17113            if (pkg.applicationInfo.isExternalAsec()) {
17114                currentAsec = true;
17115                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17116            } else if (pkg.applicationInfo.isForwardLocked()) {
17117                currentAsec = true;
17118                currentVolumeUuid = "forward_locked";
17119            } else {
17120                currentAsec = false;
17121                currentVolumeUuid = ps.volumeUuid;
17122
17123                final File probe = new File(pkg.codePath);
17124                final File probeOat = new File(probe, "oat");
17125                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17126                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17127                            "Move only supported for modern cluster style installs");
17128                }
17129            }
17130
17131            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17132                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17133                        "Package already moved to " + volumeUuid);
17134            }
17135
17136            if (ps.frozen) {
17137                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17138                        "Failed to move already frozen package");
17139            }
17140            ps.frozen = true;
17141
17142            codeFile = new File(pkg.codePath);
17143            installerPackageName = ps.installerPackageName;
17144            packageAbiOverride = ps.cpuAbiOverrideString;
17145            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17146            seinfo = pkg.applicationInfo.seinfo;
17147            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17148            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17149        }
17150
17151        // Now that we're guarded by frozen state, kill app during move
17152        final long token = Binder.clearCallingIdentity();
17153        try {
17154            killApplication(packageName, appId, "move pkg");
17155        } finally {
17156            Binder.restoreCallingIdentity(token);
17157        }
17158
17159        final Bundle extras = new Bundle();
17160        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17161        extras.putString(Intent.EXTRA_TITLE, label);
17162        mMoveCallbacks.notifyCreated(moveId, extras);
17163
17164        int installFlags;
17165        final boolean moveCompleteApp;
17166        final File measurePath;
17167
17168        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17169            installFlags = INSTALL_INTERNAL;
17170            moveCompleteApp = !currentAsec;
17171            measurePath = Environment.getDataAppDirectory(volumeUuid);
17172        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17173            installFlags = INSTALL_EXTERNAL;
17174            moveCompleteApp = false;
17175            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17176        } else {
17177            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17178            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17179                    || !volume.isMountedWritable()) {
17180                unfreezePackage(packageName);
17181                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17182                        "Move location not mounted private volume");
17183            }
17184
17185            Preconditions.checkState(!currentAsec);
17186
17187            installFlags = INSTALL_INTERNAL;
17188            moveCompleteApp = true;
17189            measurePath = Environment.getDataAppDirectory(volumeUuid);
17190        }
17191
17192        final PackageStats stats = new PackageStats(null, -1);
17193        synchronized (mInstaller) {
17194            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17195                unfreezePackage(packageName);
17196                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17197                        "Failed to measure package size");
17198            }
17199        }
17200
17201        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17202                + stats.dataSize);
17203
17204        final long startFreeBytes = measurePath.getFreeSpace();
17205        final long sizeBytes;
17206        if (moveCompleteApp) {
17207            sizeBytes = stats.codeSize + stats.dataSize;
17208        } else {
17209            sizeBytes = stats.codeSize;
17210        }
17211
17212        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17213            unfreezePackage(packageName);
17214            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17215                    "Not enough free space to move");
17216        }
17217
17218        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17219
17220        final CountDownLatch installedLatch = new CountDownLatch(1);
17221        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17222            @Override
17223            public void onUserActionRequired(Intent intent) throws RemoteException {
17224                throw new IllegalStateException();
17225            }
17226
17227            @Override
17228            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17229                    Bundle extras) throws RemoteException {
17230                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17231                        + PackageManager.installStatusToString(returnCode, msg));
17232
17233                installedLatch.countDown();
17234
17235                // Regardless of success or failure of the move operation,
17236                // always unfreeze the package
17237                unfreezePackage(packageName);
17238
17239                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17240                switch (status) {
17241                    case PackageInstaller.STATUS_SUCCESS:
17242                        mMoveCallbacks.notifyStatusChanged(moveId,
17243                                PackageManager.MOVE_SUCCEEDED);
17244                        break;
17245                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17246                        mMoveCallbacks.notifyStatusChanged(moveId,
17247                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17248                        break;
17249                    default:
17250                        mMoveCallbacks.notifyStatusChanged(moveId,
17251                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17252                        break;
17253                }
17254            }
17255        };
17256
17257        final MoveInfo move;
17258        if (moveCompleteApp) {
17259            // Kick off a thread to report progress estimates
17260            new Thread() {
17261                @Override
17262                public void run() {
17263                    while (true) {
17264                        try {
17265                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17266                                break;
17267                            }
17268                        } catch (InterruptedException ignored) {
17269                        }
17270
17271                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17272                        final int progress = 10 + (int) MathUtils.constrain(
17273                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17274                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17275                    }
17276                }
17277            }.start();
17278
17279            final String dataAppName = codeFile.getName();
17280            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17281                    dataAppName, appId, seinfo, targetSdkVersion);
17282        } else {
17283            move = null;
17284        }
17285
17286        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17287
17288        final Message msg = mHandler.obtainMessage(INIT_COPY);
17289        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17290        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17291                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17292        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17293        msg.obj = params;
17294
17295        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17296                System.identityHashCode(msg.obj));
17297        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17298                System.identityHashCode(msg.obj));
17299
17300        mHandler.sendMessage(msg);
17301    }
17302
17303    @Override
17304    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17305        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17306
17307        final int realMoveId = mNextMoveId.getAndIncrement();
17308        final Bundle extras = new Bundle();
17309        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17310        mMoveCallbacks.notifyCreated(realMoveId, extras);
17311
17312        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17313            @Override
17314            public void onCreated(int moveId, Bundle extras) {
17315                // Ignored
17316            }
17317
17318            @Override
17319            public void onStatusChanged(int moveId, int status, long estMillis) {
17320                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17321            }
17322        };
17323
17324        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17325        storage.setPrimaryStorageUuid(volumeUuid, callback);
17326        return realMoveId;
17327    }
17328
17329    @Override
17330    public int getMoveStatus(int moveId) {
17331        mContext.enforceCallingOrSelfPermission(
17332                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17333        return mMoveCallbacks.mLastStatus.get(moveId);
17334    }
17335
17336    @Override
17337    public void registerMoveCallback(IPackageMoveObserver callback) {
17338        mContext.enforceCallingOrSelfPermission(
17339                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17340        mMoveCallbacks.register(callback);
17341    }
17342
17343    @Override
17344    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17345        mContext.enforceCallingOrSelfPermission(
17346                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17347        mMoveCallbacks.unregister(callback);
17348    }
17349
17350    @Override
17351    public boolean setInstallLocation(int loc) {
17352        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17353                null);
17354        if (getInstallLocation() == loc) {
17355            return true;
17356        }
17357        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17358                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17359            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17360                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17361            return true;
17362        }
17363        return false;
17364   }
17365
17366    @Override
17367    public int getInstallLocation() {
17368        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17369                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17370                PackageHelper.APP_INSTALL_AUTO);
17371    }
17372
17373    /** Called by UserManagerService */
17374    void cleanUpUser(UserManagerService userManager, int userHandle) {
17375        synchronized (mPackages) {
17376            mDirtyUsers.remove(userHandle);
17377            mUserNeedsBadging.delete(userHandle);
17378            mSettings.removeUserLPw(userHandle);
17379            mPendingBroadcasts.remove(userHandle);
17380            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17381        }
17382        synchronized (mInstallLock) {
17383            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17384            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17385                final String volumeUuid = vol.getFsUuid();
17386                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17387                try {
17388                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17389                } catch (InstallerException e) {
17390                    Slog.w(TAG, "Failed to remove user data", e);
17391                }
17392            }
17393            synchronized (mPackages) {
17394                removeUnusedPackagesLILPw(userManager, userHandle);
17395            }
17396        }
17397    }
17398
17399    /**
17400     * We're removing userHandle and would like to remove any downloaded packages
17401     * that are no longer in use by any other user.
17402     * @param userHandle the user being removed
17403     */
17404    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17405        final boolean DEBUG_CLEAN_APKS = false;
17406        int [] users = userManager.getUserIds();
17407        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17408        while (psit.hasNext()) {
17409            PackageSetting ps = psit.next();
17410            if (ps.pkg == null) {
17411                continue;
17412            }
17413            final String packageName = ps.pkg.packageName;
17414            // Skip over if system app
17415            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17416                continue;
17417            }
17418            if (DEBUG_CLEAN_APKS) {
17419                Slog.i(TAG, "Checking package " + packageName);
17420            }
17421            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17422            if (keep) {
17423                if (DEBUG_CLEAN_APKS) {
17424                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17425                }
17426            } else {
17427                for (int i = 0; i < users.length; i++) {
17428                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17429                        keep = true;
17430                        if (DEBUG_CLEAN_APKS) {
17431                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17432                                    + users[i]);
17433                        }
17434                        break;
17435                    }
17436                }
17437            }
17438            if (!keep) {
17439                if (DEBUG_CLEAN_APKS) {
17440                    Slog.i(TAG, "  Removing package " + packageName);
17441                }
17442                mHandler.post(new Runnable() {
17443                    public void run() {
17444                        deletePackageX(packageName, userHandle, 0);
17445                    } //end run
17446                });
17447            }
17448        }
17449    }
17450
17451    /** Called by UserManagerService */
17452    void createNewUser(int userHandle) {
17453        synchronized (mInstallLock) {
17454            try {
17455                mInstaller.createUserConfig(userHandle);
17456            } catch (InstallerException e) {
17457                Slog.w(TAG, "Failed to create user config", e);
17458            }
17459            mSettings.createNewUserLI(this, mInstaller, userHandle);
17460        }
17461        synchronized (mPackages) {
17462            applyFactoryDefaultBrowserLPw(userHandle);
17463            primeDomainVerificationsLPw(userHandle);
17464        }
17465    }
17466
17467    void newUserCreated(final int userHandle) {
17468        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17469        // If permission review for legacy apps is required, we represent
17470        // dagerous permissions for such apps as always granted runtime
17471        // permissions to keep per user flag state whether review is needed.
17472        // Hence, if a new user is added we have to propagate dangerous
17473        // permission grants for these legacy apps.
17474        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17475            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17476                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17477        }
17478    }
17479
17480    @Override
17481    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17482        mContext.enforceCallingOrSelfPermission(
17483                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17484                "Only package verification agents can read the verifier device identity");
17485
17486        synchronized (mPackages) {
17487            return mSettings.getVerifierDeviceIdentityLPw();
17488        }
17489    }
17490
17491    @Override
17492    public void setPermissionEnforced(String permission, boolean enforced) {
17493        // TODO: Now that we no longer change GID for storage, this should to away.
17494        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17495                "setPermissionEnforced");
17496        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17497            synchronized (mPackages) {
17498                if (mSettings.mReadExternalStorageEnforced == null
17499                        || mSettings.mReadExternalStorageEnforced != enforced) {
17500                    mSettings.mReadExternalStorageEnforced = enforced;
17501                    mSettings.writeLPr();
17502                }
17503            }
17504            // kill any non-foreground processes so we restart them and
17505            // grant/revoke the GID.
17506            final IActivityManager am = ActivityManagerNative.getDefault();
17507            if (am != null) {
17508                final long token = Binder.clearCallingIdentity();
17509                try {
17510                    am.killProcessesBelowForeground("setPermissionEnforcement");
17511                } catch (RemoteException e) {
17512                } finally {
17513                    Binder.restoreCallingIdentity(token);
17514                }
17515            }
17516        } else {
17517            throw new IllegalArgumentException("No selective enforcement for " + permission);
17518        }
17519    }
17520
17521    @Override
17522    @Deprecated
17523    public boolean isPermissionEnforced(String permission) {
17524        return true;
17525    }
17526
17527    @Override
17528    public boolean isStorageLow() {
17529        final long token = Binder.clearCallingIdentity();
17530        try {
17531            final DeviceStorageMonitorInternal
17532                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17533            if (dsm != null) {
17534                return dsm.isMemoryLow();
17535            } else {
17536                return false;
17537            }
17538        } finally {
17539            Binder.restoreCallingIdentity(token);
17540        }
17541    }
17542
17543    @Override
17544    public IPackageInstaller getPackageInstaller() {
17545        return mInstallerService;
17546    }
17547
17548    private boolean userNeedsBadging(int userId) {
17549        int index = mUserNeedsBadging.indexOfKey(userId);
17550        if (index < 0) {
17551            final UserInfo userInfo;
17552            final long token = Binder.clearCallingIdentity();
17553            try {
17554                userInfo = sUserManager.getUserInfo(userId);
17555            } finally {
17556                Binder.restoreCallingIdentity(token);
17557            }
17558            final boolean b;
17559            if (userInfo != null && userInfo.isManagedProfile()) {
17560                b = true;
17561            } else {
17562                b = false;
17563            }
17564            mUserNeedsBadging.put(userId, b);
17565            return b;
17566        }
17567        return mUserNeedsBadging.valueAt(index);
17568    }
17569
17570    @Override
17571    public KeySet getKeySetByAlias(String packageName, String alias) {
17572        if (packageName == null || alias == null) {
17573            return null;
17574        }
17575        synchronized(mPackages) {
17576            final PackageParser.Package pkg = mPackages.get(packageName);
17577            if (pkg == null) {
17578                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17579                throw new IllegalArgumentException("Unknown package: " + packageName);
17580            }
17581            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17582            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17583        }
17584    }
17585
17586    @Override
17587    public KeySet getSigningKeySet(String packageName) {
17588        if (packageName == null) {
17589            return null;
17590        }
17591        synchronized(mPackages) {
17592            final PackageParser.Package pkg = mPackages.get(packageName);
17593            if (pkg == null) {
17594                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17595                throw new IllegalArgumentException("Unknown package: " + packageName);
17596            }
17597            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17598                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17599                throw new SecurityException("May not access signing KeySet of other apps.");
17600            }
17601            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17602            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17603        }
17604    }
17605
17606    @Override
17607    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17608        if (packageName == null || ks == null) {
17609            return false;
17610        }
17611        synchronized(mPackages) {
17612            final PackageParser.Package pkg = mPackages.get(packageName);
17613            if (pkg == null) {
17614                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17615                throw new IllegalArgumentException("Unknown package: " + packageName);
17616            }
17617            IBinder ksh = ks.getToken();
17618            if (ksh instanceof KeySetHandle) {
17619                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17620                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17621            }
17622            return false;
17623        }
17624    }
17625
17626    @Override
17627    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17628        if (packageName == null || ks == null) {
17629            return false;
17630        }
17631        synchronized(mPackages) {
17632            final PackageParser.Package pkg = mPackages.get(packageName);
17633            if (pkg == null) {
17634                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17635                throw new IllegalArgumentException("Unknown package: " + packageName);
17636            }
17637            IBinder ksh = ks.getToken();
17638            if (ksh instanceof KeySetHandle) {
17639                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17640                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17641            }
17642            return false;
17643        }
17644    }
17645
17646    private void deletePackageIfUnusedLPr(final String packageName) {
17647        PackageSetting ps = mSettings.mPackages.get(packageName);
17648        if (ps == null) {
17649            return;
17650        }
17651        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17652            // TODO Implement atomic delete if package is unused
17653            // It is currently possible that the package will be deleted even if it is installed
17654            // after this method returns.
17655            mHandler.post(new Runnable() {
17656                public void run() {
17657                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17658                }
17659            });
17660        }
17661    }
17662
17663    /**
17664     * Check and throw if the given before/after packages would be considered a
17665     * downgrade.
17666     */
17667    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17668            throws PackageManagerException {
17669        if (after.versionCode < before.mVersionCode) {
17670            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17671                    "Update version code " + after.versionCode + " is older than current "
17672                    + before.mVersionCode);
17673        } else if (after.versionCode == before.mVersionCode) {
17674            if (after.baseRevisionCode < before.baseRevisionCode) {
17675                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17676                        "Update base revision code " + after.baseRevisionCode
17677                        + " is older than current " + before.baseRevisionCode);
17678            }
17679
17680            if (!ArrayUtils.isEmpty(after.splitNames)) {
17681                for (int i = 0; i < after.splitNames.length; i++) {
17682                    final String splitName = after.splitNames[i];
17683                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17684                    if (j != -1) {
17685                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17686                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17687                                    "Update split " + splitName + " revision code "
17688                                    + after.splitRevisionCodes[i] + " is older than current "
17689                                    + before.splitRevisionCodes[j]);
17690                        }
17691                    }
17692                }
17693            }
17694        }
17695    }
17696
17697    private static class MoveCallbacks extends Handler {
17698        private static final int MSG_CREATED = 1;
17699        private static final int MSG_STATUS_CHANGED = 2;
17700
17701        private final RemoteCallbackList<IPackageMoveObserver>
17702                mCallbacks = new RemoteCallbackList<>();
17703
17704        private final SparseIntArray mLastStatus = new SparseIntArray();
17705
17706        public MoveCallbacks(Looper looper) {
17707            super(looper);
17708        }
17709
17710        public void register(IPackageMoveObserver callback) {
17711            mCallbacks.register(callback);
17712        }
17713
17714        public void unregister(IPackageMoveObserver callback) {
17715            mCallbacks.unregister(callback);
17716        }
17717
17718        @Override
17719        public void handleMessage(Message msg) {
17720            final SomeArgs args = (SomeArgs) msg.obj;
17721            final int n = mCallbacks.beginBroadcast();
17722            for (int i = 0; i < n; i++) {
17723                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17724                try {
17725                    invokeCallback(callback, msg.what, args);
17726                } catch (RemoteException ignored) {
17727                }
17728            }
17729            mCallbacks.finishBroadcast();
17730            args.recycle();
17731        }
17732
17733        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17734                throws RemoteException {
17735            switch (what) {
17736                case MSG_CREATED: {
17737                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17738                    break;
17739                }
17740                case MSG_STATUS_CHANGED: {
17741                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17742                    break;
17743                }
17744            }
17745        }
17746
17747        private void notifyCreated(int moveId, Bundle extras) {
17748            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17749
17750            final SomeArgs args = SomeArgs.obtain();
17751            args.argi1 = moveId;
17752            args.arg2 = extras;
17753            obtainMessage(MSG_CREATED, args).sendToTarget();
17754        }
17755
17756        private void notifyStatusChanged(int moveId, int status) {
17757            notifyStatusChanged(moveId, status, -1);
17758        }
17759
17760        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17761            Slog.v(TAG, "Move " + moveId + " status " + status);
17762
17763            final SomeArgs args = SomeArgs.obtain();
17764            args.argi1 = moveId;
17765            args.argi2 = status;
17766            args.arg3 = estMillis;
17767            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17768
17769            synchronized (mLastStatus) {
17770                mLastStatus.put(moveId, status);
17771            }
17772        }
17773    }
17774
17775    private final static class OnPermissionChangeListeners extends Handler {
17776        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17777
17778        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17779                new RemoteCallbackList<>();
17780
17781        public OnPermissionChangeListeners(Looper looper) {
17782            super(looper);
17783        }
17784
17785        @Override
17786        public void handleMessage(Message msg) {
17787            switch (msg.what) {
17788                case MSG_ON_PERMISSIONS_CHANGED: {
17789                    final int uid = msg.arg1;
17790                    handleOnPermissionsChanged(uid);
17791                } break;
17792            }
17793        }
17794
17795        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17796            mPermissionListeners.register(listener);
17797
17798        }
17799
17800        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17801            mPermissionListeners.unregister(listener);
17802        }
17803
17804        public void onPermissionsChanged(int uid) {
17805            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17806                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17807            }
17808        }
17809
17810        private void handleOnPermissionsChanged(int uid) {
17811            final int count = mPermissionListeners.beginBroadcast();
17812            try {
17813                for (int i = 0; i < count; i++) {
17814                    IOnPermissionsChangeListener callback = mPermissionListeners
17815                            .getBroadcastItem(i);
17816                    try {
17817                        callback.onPermissionsChanged(uid);
17818                    } catch (RemoteException e) {
17819                        Log.e(TAG, "Permission listener is dead", e);
17820                    }
17821                }
17822            } finally {
17823                mPermissionListeners.finishBroadcast();
17824            }
17825        }
17826    }
17827
17828    private class PackageManagerInternalImpl extends PackageManagerInternal {
17829        @Override
17830        public void setLocationPackagesProvider(PackagesProvider provider) {
17831            synchronized (mPackages) {
17832                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17833            }
17834        }
17835
17836        @Override
17837        public void setImePackagesProvider(PackagesProvider provider) {
17838            synchronized (mPackages) {
17839                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17840            }
17841        }
17842
17843        @Override
17844        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17845            synchronized (mPackages) {
17846                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17847            }
17848        }
17849
17850        @Override
17851        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17852            synchronized (mPackages) {
17853                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17854            }
17855        }
17856
17857        @Override
17858        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17859            synchronized (mPackages) {
17860                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17861            }
17862        }
17863
17864        @Override
17865        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17866            synchronized (mPackages) {
17867                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17868            }
17869        }
17870
17871        @Override
17872        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17873            synchronized (mPackages) {
17874                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17875            }
17876        }
17877
17878        @Override
17879        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17880            synchronized (mPackages) {
17881                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17882                        packageName, userId);
17883            }
17884        }
17885
17886        @Override
17887        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17888            synchronized (mPackages) {
17889                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17890                        packageName, userId);
17891            }
17892        }
17893
17894        @Override
17895        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17896            synchronized (mPackages) {
17897                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17898                        packageName, userId);
17899            }
17900        }
17901
17902        @Override
17903        public void setKeepUninstalledPackages(final List<String> packageList) {
17904            Preconditions.checkNotNull(packageList);
17905            List<String> removedFromList = null;
17906            synchronized (mPackages) {
17907                if (mKeepUninstalledPackages != null) {
17908                    final int packagesCount = mKeepUninstalledPackages.size();
17909                    for (int i = 0; i < packagesCount; i++) {
17910                        String oldPackage = mKeepUninstalledPackages.get(i);
17911                        if (packageList != null && packageList.contains(oldPackage)) {
17912                            continue;
17913                        }
17914                        if (removedFromList == null) {
17915                            removedFromList = new ArrayList<>();
17916                        }
17917                        removedFromList.add(oldPackage);
17918                    }
17919                }
17920                mKeepUninstalledPackages = new ArrayList<>(packageList);
17921                if (removedFromList != null) {
17922                    final int removedCount = removedFromList.size();
17923                    for (int i = 0; i < removedCount; i++) {
17924                        deletePackageIfUnusedLPr(removedFromList.get(i));
17925                    }
17926                }
17927            }
17928        }
17929
17930        @Override
17931        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17932            synchronized (mPackages) {
17933                // If we do not support permission review, done.
17934                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17935                    return false;
17936                }
17937
17938                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17939                if (packageSetting == null) {
17940                    return false;
17941                }
17942
17943                // Permission review applies only to apps not supporting the new permission model.
17944                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17945                    return false;
17946                }
17947
17948                // Legacy apps have the permission and get user consent on launch.
17949                PermissionsState permissionsState = packageSetting.getPermissionsState();
17950                return permissionsState.isPermissionReviewRequired(userId);
17951            }
17952        }
17953    }
17954
17955    @Override
17956    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17957        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17958        synchronized (mPackages) {
17959            final long identity = Binder.clearCallingIdentity();
17960            try {
17961                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17962                        packageNames, userId);
17963            } finally {
17964                Binder.restoreCallingIdentity(identity);
17965            }
17966        }
17967    }
17968
17969    private static void enforceSystemOrPhoneCaller(String tag) {
17970        int callingUid = Binder.getCallingUid();
17971        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17972            throw new SecurityException(
17973                    "Cannot call " + tag + " from UID " + callingUid);
17974        }
17975    }
17976}
17977