PackageManagerService.java revision 5cbeb5902633646fbc0a1be252081e77aaaee7b4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
72import static android.content.pm.PackageManager.PERMISSION_DENIED;
73import static android.content.pm.PackageManager.PERMISSION_GRANTED;
74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
75import static android.content.pm.PackageParser.isApkFile;
76import static android.os.Process.PACKAGE_INFO_GID;
77import static android.os.Process.SYSTEM_UID;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
96
97import android.Manifest;
98import android.annotation.NonNull;
99import android.annotation.Nullable;
100import android.app.ActivityManager;
101import android.app.ActivityManagerNative;
102import android.app.AppGlobals;
103import android.app.IActivityManager;
104import android.app.admin.IDevicePolicyManager;
105import android.app.backup.IBackupManager;
106import android.content.BroadcastReceiver;
107import android.content.ComponentName;
108import android.content.Context;
109import android.content.IIntentReceiver;
110import android.content.Intent;
111import android.content.IntentFilter;
112import android.content.IntentSender;
113import android.content.IntentSender.SendIntentException;
114import android.content.ServiceConnection;
115import android.content.pm.ActivityInfo;
116import android.content.pm.ApplicationInfo;
117import android.content.pm.AppsQueryHelper;
118import android.content.pm.ComponentInfo;
119import android.content.pm.EphemeralApplicationInfo;
120import android.content.pm.EphemeralResolveInfo;
121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
122import android.content.pm.FeatureInfo;
123import android.content.pm.IOnPermissionsChangeListener;
124import android.content.pm.IPackageDataObserver;
125import android.content.pm.IPackageDeleteObserver;
126import android.content.pm.IPackageDeleteObserver2;
127import android.content.pm.IPackageInstallObserver2;
128import android.content.pm.IPackageInstaller;
129import android.content.pm.IPackageManager;
130import android.content.pm.IPackageMoveObserver;
131import android.content.pm.IPackageStatsObserver;
132import android.content.pm.InstrumentationInfo;
133import android.content.pm.IntentFilterVerificationInfo;
134import android.content.pm.KeySet;
135import android.content.pm.PackageCleanItem;
136import android.content.pm.PackageInfo;
137import android.content.pm.PackageInfoLite;
138import android.content.pm.PackageInstaller;
139import android.content.pm.PackageManager;
140import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
141import android.content.pm.PackageManagerInternal;
142import android.content.pm.PackageParser;
143import android.content.pm.PackageParser.ActivityIntentInfo;
144import android.content.pm.PackageParser.Package;
145import android.content.pm.PackageParser.PackageLite;
146import android.content.pm.PackageParser.PackageParserException;
147import android.content.pm.PackageStats;
148import android.content.pm.PackageUserState;
149import android.content.pm.ParceledListSlice;
150import android.content.pm.PermissionGroupInfo;
151import android.content.pm.PermissionInfo;
152import android.content.pm.ProviderInfo;
153import android.content.pm.ResolveInfo;
154import android.content.pm.ServiceInfo;
155import android.content.pm.Signature;
156import android.content.pm.UserInfo;
157import android.content.pm.VerificationParams;
158import android.content.pm.VerifierDeviceIdentity;
159import android.content.pm.VerifierInfo;
160import android.content.res.Resources;
161import android.graphics.Bitmap;
162import android.hardware.display.DisplayManager;
163import android.net.Uri;
164import android.os.Binder;
165import android.os.Build;
166import android.os.Bundle;
167import android.os.Debug;
168import android.os.Environment;
169import android.os.Environment.UserEnvironment;
170import android.os.FileUtils;
171import android.os.Handler;
172import android.os.IBinder;
173import android.os.Looper;
174import android.os.Message;
175import android.os.Parcel;
176import android.os.ParcelFileDescriptor;
177import android.os.Process;
178import android.os.RemoteCallbackList;
179import android.os.RemoteException;
180import android.os.ResultReceiver;
181import android.os.SELinux;
182import android.os.ServiceManager;
183import android.os.SystemClock;
184import android.os.SystemProperties;
185import android.os.Trace;
186import android.os.UserHandle;
187import android.os.UserManager;
188import android.os.storage.IMountService;
189import android.os.storage.MountServiceInternal;
190import android.os.storage.StorageEventListener;
191import android.os.storage.StorageManager;
192import android.os.storage.VolumeInfo;
193import android.os.storage.VolumeRecord;
194import android.security.KeyStore;
195import android.security.SystemKeyStore;
196import android.system.ErrnoException;
197import android.system.Os;
198import android.text.TextUtils;
199import android.text.format.DateUtils;
200import android.util.ArrayMap;
201import android.util.ArraySet;
202import android.util.AtomicFile;
203import android.util.DisplayMetrics;
204import android.util.EventLog;
205import android.util.ExceptionUtils;
206import android.util.Log;
207import android.util.LogPrinter;
208import android.util.MathUtils;
209import android.util.PrintStreamPrinter;
210import android.util.Slog;
211import android.util.SparseArray;
212import android.util.SparseBooleanArray;
213import android.util.SparseIntArray;
214import android.util.Xml;
215import android.view.Display;
216
217import com.android.internal.R;
218import com.android.internal.annotations.GuardedBy;
219import com.android.internal.app.IMediaContainerService;
220import com.android.internal.app.ResolverActivity;
221import com.android.internal.content.NativeLibraryHelper;
222import com.android.internal.content.PackageHelper;
223import com.android.internal.os.IParcelFileDescriptorFactory;
224import com.android.internal.os.InstallerConnection.InstallerException;
225import com.android.internal.os.SomeArgs;
226import com.android.internal.os.Zygote;
227import com.android.internal.util.ArrayUtils;
228import com.android.internal.util.FastPrintWriter;
229import com.android.internal.util.FastXmlSerializer;
230import com.android.internal.util.IndentingPrintWriter;
231import com.android.internal.util.Preconditions;
232import com.android.internal.util.XmlUtils;
233import com.android.server.EventLogTags;
234import com.android.server.FgThread;
235import com.android.server.IntentResolver;
236import com.android.server.LocalServices;
237import com.android.server.ServiceThread;
238import com.android.server.SystemConfig;
239import com.android.server.Watchdog;
240import com.android.server.pm.PermissionsState.PermissionState;
241import com.android.server.pm.Settings.DatabaseVersion;
242import com.android.server.pm.Settings.VersionInfo;
243import com.android.server.storage.DeviceStorageMonitorInternal;
244
245import dalvik.system.DexFile;
246import dalvik.system.VMRuntime;
247
248import libcore.io.IoUtils;
249import libcore.util.EmptyArray;
250
251import org.xmlpull.v1.XmlPullParser;
252import org.xmlpull.v1.XmlPullParserException;
253import org.xmlpull.v1.XmlSerializer;
254
255import java.io.BufferedInputStream;
256import java.io.BufferedOutputStream;
257import java.io.BufferedReader;
258import java.io.ByteArrayInputStream;
259import java.io.ByteArrayOutputStream;
260import java.io.File;
261import java.io.FileDescriptor;
262import java.io.FileNotFoundException;
263import java.io.FileOutputStream;
264import java.io.FileReader;
265import java.io.FilenameFilter;
266import java.io.IOException;
267import java.io.InputStream;
268import java.io.PrintStream;
269import java.io.PrintWriter;
270import java.nio.charset.StandardCharsets;
271import java.security.MessageDigest;
272import java.security.NoSuchAlgorithmException;
273import java.security.PublicKey;
274import java.security.cert.CertificateEncodingException;
275import java.security.cert.CertificateException;
276import java.text.SimpleDateFormat;
277import java.util.ArrayList;
278import java.util.Arrays;
279import java.util.Collection;
280import java.util.Collections;
281import java.util.Comparator;
282import java.util.Date;
283import java.util.HashSet;
284import java.util.Iterator;
285import java.util.List;
286import java.util.Map;
287import java.util.Objects;
288import java.util.Set;
289import java.util.concurrent.CountDownLatch;
290import java.util.concurrent.TimeUnit;
291import java.util.concurrent.atomic.AtomicBoolean;
292import java.util.concurrent.atomic.AtomicInteger;
293import java.util.concurrent.atomic.AtomicLong;
294
295/**
296 * Keep track of all those .apks everywhere.
297 *
298 * This is very central to the platform's security; please run the unit
299 * tests whenever making modifications here:
300 *
301runtest -c android.content.pm.PackageManagerTests frameworks-core
302 *
303 * {@hide}
304 */
305public class PackageManagerService extends IPackageManager.Stub {
306    static final String TAG = "PackageManager";
307    static final boolean DEBUG_SETTINGS = false;
308    static final boolean DEBUG_PREFERRED = false;
309    static final boolean DEBUG_UPGRADE = false;
310    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
311    private static final boolean DEBUG_BACKUP = false;
312    private static final boolean DEBUG_INSTALL = false;
313    private static final boolean DEBUG_REMOVE = false;
314    private static final boolean DEBUG_BROADCASTS = false;
315    private static final boolean DEBUG_SHOW_INFO = false;
316    private static final boolean DEBUG_PACKAGE_INFO = false;
317    private static final boolean DEBUG_INTENT_MATCHING = false;
318    private static final boolean DEBUG_PACKAGE_SCANNING = false;
319    private static final boolean DEBUG_VERIFY = false;
320
321    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
322    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
323    // user, but by default initialize to this.
324    static final boolean DEBUG_DEXOPT = false;
325
326    private static final boolean DEBUG_ABI_SELECTION = false;
327    private static final boolean DEBUG_EPHEMERAL = false;
328    private static final boolean DEBUG_TRIAGED_MISSING = false;
329    private static final boolean DEBUG_APP_DATA = false;
330
331    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
332
333    private static final boolean DISABLE_EPHEMERAL_APPS = true;
334
335    private static final int RADIO_UID = Process.PHONE_UID;
336    private static final int LOG_UID = Process.LOG_UID;
337    private static final int NFC_UID = Process.NFC_UID;
338    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
339    private static final int SHELL_UID = Process.SHELL_UID;
340
341    // Cap the size of permission trees that 3rd party apps can define
342    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
343
344    // Suffix used during package installation when copying/moving
345    // package apks to install directory.
346    private static final String INSTALL_PACKAGE_SUFFIX = "-";
347
348    static final int SCAN_NO_DEX = 1<<1;
349    static final int SCAN_FORCE_DEX = 1<<2;
350    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
351    static final int SCAN_NEW_INSTALL = 1<<4;
352    static final int SCAN_NO_PATHS = 1<<5;
353    static final int SCAN_UPDATE_TIME = 1<<6;
354    static final int SCAN_DEFER_DEX = 1<<7;
355    static final int SCAN_BOOTING = 1<<8;
356    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
357    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
358    static final int SCAN_REPLACING = 1<<11;
359    static final int SCAN_REQUIRE_KNOWN = 1<<12;
360    static final int SCAN_MOVE = 1<<13;
361    static final int SCAN_INITIAL = 1<<14;
362    static final int SCAN_CHECK_ONLY = 1<<15;
363
364    static final int REMOVE_CHATTY = 1<<16;
365
366    private static final int[] EMPTY_INT_ARRAY = new int[0];
367
368    /**
369     * Timeout (in milliseconds) after which the watchdog should declare that
370     * our handler thread is wedged.  The usual default for such things is one
371     * minute but we sometimes do very lengthy I/O operations on this thread,
372     * such as installing multi-gigabyte applications, so ours needs to be longer.
373     */
374    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
375
376    /**
377     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
378     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
379     * settings entry if available, otherwise we use the hardcoded default.  If it's been
380     * more than this long since the last fstrim, we force one during the boot sequence.
381     *
382     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
383     * one gets run at the next available charging+idle time.  This final mandatory
384     * no-fstrim check kicks in only of the other scheduling criteria is never met.
385     */
386    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
387
388    /**
389     * Whether verification is enabled by default.
390     */
391    private static final boolean DEFAULT_VERIFY_ENABLE = true;
392
393    /**
394     * The default maximum time to wait for the verification agent to return in
395     * milliseconds.
396     */
397    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
398
399    /**
400     * The default response for package verification timeout.
401     *
402     * This can be either PackageManager.VERIFICATION_ALLOW or
403     * PackageManager.VERIFICATION_REJECT.
404     */
405    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
406
407    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
408
409    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
410            DEFAULT_CONTAINER_PACKAGE,
411            "com.android.defcontainer.DefaultContainerService");
412
413    private static final String KILL_APP_REASON_GIDS_CHANGED =
414            "permission grant or revoke changed gids";
415
416    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
417            "permissions revoked";
418
419    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
420
421    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
422
423    /** Permission grant: not grant the permission. */
424    private static final int GRANT_DENIED = 1;
425
426    /** Permission grant: grant the permission as an install permission. */
427    private static final int GRANT_INSTALL = 2;
428
429    /** Permission grant: grant the permission as a runtime one. */
430    private static final int GRANT_RUNTIME = 3;
431
432    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
433    private static final int GRANT_UPGRADE = 4;
434
435    /** Canonical intent used to identify what counts as a "web browser" app */
436    private static final Intent sBrowserIntent;
437    static {
438        sBrowserIntent = new Intent();
439        sBrowserIntent.setAction(Intent.ACTION_VIEW);
440        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
441        sBrowserIntent.setData(Uri.parse("http:"));
442    }
443
444    final ServiceThread mHandlerThread;
445
446    final PackageHandler mHandler;
447
448    /**
449     * Messages for {@link #mHandler} that need to wait for system ready before
450     * being dispatched.
451     */
452    private ArrayList<Message> mPostSystemReadyMessages;
453
454    final int mSdkVersion = Build.VERSION.SDK_INT;
455
456    final Context mContext;
457    final boolean mFactoryTest;
458    final boolean mOnlyCore;
459    final DisplayMetrics mMetrics;
460    final int mDefParseFlags;
461    final String[] mSeparateProcesses;
462    final boolean mIsUpgrade;
463
464    /** The location for ASEC container files on internal storage. */
465    final String mAsecInternalPath;
466
467    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
468    // LOCK HELD.  Can be called with mInstallLock held.
469    @GuardedBy("mInstallLock")
470    final Installer mInstaller;
471
472    /** Directory where installed third-party apps stored */
473    final File mAppInstallDir;
474    final File mEphemeralInstallDir;
475
476    /**
477     * Directory to which applications installed internally have their
478     * 32 bit native libraries copied.
479     */
480    private File mAppLib32InstallDir;
481
482    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
483    // apps.
484    final File mDrmAppPrivateInstallDir;
485
486    // ----------------------------------------------------------------
487
488    // Lock for state used when installing and doing other long running
489    // operations.  Methods that must be called with this lock held have
490    // the suffix "LI".
491    final Object mInstallLock = new Object();
492
493    // ----------------------------------------------------------------
494
495    // Keys are String (package name), values are Package.  This also serves
496    // as the lock for the global state.  Methods that must be called with
497    // this lock held have the prefix "LP".
498    @GuardedBy("mPackages")
499    final ArrayMap<String, PackageParser.Package> mPackages =
500            new ArrayMap<String, PackageParser.Package>();
501
502    // Tracks available target package names -> overlay package paths.
503    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
504        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
505
506    /**
507     * Tracks new system packages [received in an OTA] that we expect to
508     * find updated user-installed versions. Keys are package name, values
509     * are package location.
510     */
511    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
512
513    /**
514     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
515     */
516    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
517    /**
518     * Whether or not system app permissions should be promoted from install to runtime.
519     */
520    boolean mPromoteSystemApps;
521
522    final Settings mSettings;
523    boolean mRestoredSettings;
524
525    // System configuration read by SystemConfig.
526    final int[] mGlobalGids;
527    final SparseArray<ArraySet<String>> mSystemPermissions;
528    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
529
530    // If mac_permissions.xml was found for seinfo labeling.
531    boolean mFoundPolicyFile;
532
533    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
534
535    public static final class SharedLibraryEntry {
536        public final String path;
537        public final String apk;
538
539        SharedLibraryEntry(String _path, String _apk) {
540            path = _path;
541            apk = _apk;
542        }
543    }
544
545    // Currently known shared libraries.
546    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
547            new ArrayMap<String, SharedLibraryEntry>();
548
549    // All available activities, for your resolving pleasure.
550    final ActivityIntentResolver mActivities =
551            new ActivityIntentResolver();
552
553    // All available receivers, for your resolving pleasure.
554    final ActivityIntentResolver mReceivers =
555            new ActivityIntentResolver();
556
557    // All available services, for your resolving pleasure.
558    final ServiceIntentResolver mServices = new ServiceIntentResolver();
559
560    // All available providers, for your resolving pleasure.
561    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
562
563    // Mapping from provider base names (first directory in content URI codePath)
564    // to the provider information.
565    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
566            new ArrayMap<String, PackageParser.Provider>();
567
568    // Mapping from instrumentation class names to info about them.
569    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
570            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
571
572    // Mapping from permission names to info about them.
573    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
574            new ArrayMap<String, PackageParser.PermissionGroup>();
575
576    // Packages whose data we have transfered into another package, thus
577    // should no longer exist.
578    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
579
580    // Broadcast actions that are only available to the system.
581    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
582
583    /** List of packages waiting for verification. */
584    final SparseArray<PackageVerificationState> mPendingVerification
585            = new SparseArray<PackageVerificationState>();
586
587    /** Set of packages associated with each app op permission. */
588    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
589
590    final PackageInstallerService mInstallerService;
591
592    private final PackageDexOptimizer mPackageDexOptimizer;
593
594    private AtomicInteger mNextMoveId = new AtomicInteger();
595    private final MoveCallbacks mMoveCallbacks;
596
597    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
598
599    // Cache of users who need badging.
600    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
601
602    /** Token for keys in mPendingVerification. */
603    private int mPendingVerificationToken = 0;
604
605    volatile boolean mSystemReady;
606    volatile boolean mSafeMode;
607    volatile boolean mHasSystemUidErrors;
608
609    ApplicationInfo mAndroidApplication;
610    final ActivityInfo mResolveActivity = new ActivityInfo();
611    final ResolveInfo mResolveInfo = new ResolveInfo();
612    ComponentName mResolveComponentName;
613    PackageParser.Package mPlatformPackage;
614    ComponentName mCustomResolverComponentName;
615
616    boolean mResolverReplaced = false;
617
618    private final @Nullable ComponentName mIntentFilterVerifierComponent;
619    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
620
621    private int mIntentFilterVerificationToken = 0;
622
623    /** Component that knows whether or not an ephemeral application exists */
624    final ComponentName mEphemeralResolverComponent;
625    /** The service connection to the ephemeral resolver */
626    final EphemeralResolverConnection mEphemeralResolverConnection;
627
628    /** Component used to install ephemeral applications */
629    final ComponentName mEphemeralInstallerComponent;
630    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
631    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
632
633    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
634            = new SparseArray<IntentFilterVerificationState>();
635
636    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
637            new DefaultPermissionGrantPolicy(this);
638
639    // List of packages names to keep cached, even if they are uninstalled for all users
640    private List<String> mKeepUninstalledPackages;
641
642    private boolean mUseJitProfiles =
643            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
644
645    private static class IFVerificationParams {
646        PackageParser.Package pkg;
647        boolean replacing;
648        int userId;
649        int verifierUid;
650
651        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
652                int _userId, int _verifierUid) {
653            pkg = _pkg;
654            replacing = _replacing;
655            userId = _userId;
656            replacing = _replacing;
657            verifierUid = _verifierUid;
658        }
659    }
660
661    private interface IntentFilterVerifier<T extends IntentFilter> {
662        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
663                                               T filter, String packageName);
664        void startVerifications(int userId);
665        void receiveVerificationResponse(int verificationId);
666    }
667
668    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
669        private Context mContext;
670        private ComponentName mIntentFilterVerifierComponent;
671        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
672
673        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
674            mContext = context;
675            mIntentFilterVerifierComponent = verifierComponent;
676        }
677
678        private String getDefaultScheme() {
679            return IntentFilter.SCHEME_HTTPS;
680        }
681
682        @Override
683        public void startVerifications(int userId) {
684            // Launch verifications requests
685            int count = mCurrentIntentFilterVerifications.size();
686            for (int n=0; n<count; n++) {
687                int verificationId = mCurrentIntentFilterVerifications.get(n);
688                final IntentFilterVerificationState ivs =
689                        mIntentFilterVerificationStates.get(verificationId);
690
691                String packageName = ivs.getPackageName();
692
693                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
694                final int filterCount = filters.size();
695                ArraySet<String> domainsSet = new ArraySet<>();
696                for (int m=0; m<filterCount; m++) {
697                    PackageParser.ActivityIntentInfo filter = filters.get(m);
698                    domainsSet.addAll(filter.getHostsList());
699                }
700                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
701                synchronized (mPackages) {
702                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
703                            packageName, domainsList) != null) {
704                        scheduleWriteSettingsLocked();
705                    }
706                }
707                sendVerificationRequest(userId, verificationId, ivs);
708            }
709            mCurrentIntentFilterVerifications.clear();
710        }
711
712        private void sendVerificationRequest(int userId, int verificationId,
713                IntentFilterVerificationState ivs) {
714
715            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
716            verificationIntent.putExtra(
717                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
718                    verificationId);
719            verificationIntent.putExtra(
720                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
721                    getDefaultScheme());
722            verificationIntent.putExtra(
723                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
724                    ivs.getHostsString());
725            verificationIntent.putExtra(
726                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
727                    ivs.getPackageName());
728            verificationIntent.setComponent(mIntentFilterVerifierComponent);
729            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
730
731            UserHandle user = new UserHandle(userId);
732            mContext.sendBroadcastAsUser(verificationIntent, user);
733            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
734                    "Sending IntentFilter verification broadcast");
735        }
736
737        public void receiveVerificationResponse(int verificationId) {
738            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
739
740            final boolean verified = ivs.isVerified();
741
742            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
743            final int count = filters.size();
744            if (DEBUG_DOMAIN_VERIFICATION) {
745                Slog.i(TAG, "Received verification response " + verificationId
746                        + " for " + count + " filters, verified=" + verified);
747            }
748            for (int n=0; n<count; n++) {
749                PackageParser.ActivityIntentInfo filter = filters.get(n);
750                filter.setVerified(verified);
751
752                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
753                        + " verified with result:" + verified + " and hosts:"
754                        + ivs.getHostsString());
755            }
756
757            mIntentFilterVerificationStates.remove(verificationId);
758
759            final String packageName = ivs.getPackageName();
760            IntentFilterVerificationInfo ivi = null;
761
762            synchronized (mPackages) {
763                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
764            }
765            if (ivi == null) {
766                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
767                        + verificationId + " packageName:" + packageName);
768                return;
769            }
770            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
771                    "Updating IntentFilterVerificationInfo for package " + packageName
772                            +" verificationId:" + verificationId);
773
774            synchronized (mPackages) {
775                if (verified) {
776                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
777                } else {
778                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
779                }
780                scheduleWriteSettingsLocked();
781
782                final int userId = ivs.getUserId();
783                if (userId != UserHandle.USER_ALL) {
784                    final int userStatus =
785                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
786
787                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
788                    boolean needUpdate = false;
789
790                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
791                    // already been set by the User thru the Disambiguation dialog
792                    switch (userStatus) {
793                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
794                            if (verified) {
795                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
796                            } else {
797                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
798                            }
799                            needUpdate = true;
800                            break;
801
802                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
803                            if (verified) {
804                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
805                                needUpdate = true;
806                            }
807                            break;
808
809                        default:
810                            // Nothing to do
811                    }
812
813                    if (needUpdate) {
814                        mSettings.updateIntentFilterVerificationStatusLPw(
815                                packageName, updatedStatus, userId);
816                        scheduleWritePackageRestrictionsLocked(userId);
817                    }
818                }
819            }
820        }
821
822        @Override
823        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
824                    ActivityIntentInfo filter, String packageName) {
825            if (!hasValidDomains(filter)) {
826                return false;
827            }
828            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
829            if (ivs == null) {
830                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
831                        packageName);
832            }
833            if (DEBUG_DOMAIN_VERIFICATION) {
834                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
835            }
836            ivs.addFilter(filter);
837            return true;
838        }
839
840        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
841                int userId, int verificationId, String packageName) {
842            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
843                    verifierUid, userId, packageName);
844            ivs.setPendingState();
845            synchronized (mPackages) {
846                mIntentFilterVerificationStates.append(verificationId, ivs);
847                mCurrentIntentFilterVerifications.add(verificationId);
848            }
849            return ivs;
850        }
851    }
852
853    private static boolean hasValidDomains(ActivityIntentInfo filter) {
854        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
855                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
856                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
857    }
858
859    // Set of pending broadcasts for aggregating enable/disable of components.
860    static class PendingPackageBroadcasts {
861        // for each user id, a map of <package name -> components within that package>
862        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
863
864        public PendingPackageBroadcasts() {
865            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
866        }
867
868        public ArrayList<String> get(int userId, String packageName) {
869            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
870            return packages.get(packageName);
871        }
872
873        public void put(int userId, String packageName, ArrayList<String> components) {
874            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
875            packages.put(packageName, components);
876        }
877
878        public void remove(int userId, String packageName) {
879            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
880            if (packages != null) {
881                packages.remove(packageName);
882            }
883        }
884
885        public void remove(int userId) {
886            mUidMap.remove(userId);
887        }
888
889        public int userIdCount() {
890            return mUidMap.size();
891        }
892
893        public int userIdAt(int n) {
894            return mUidMap.keyAt(n);
895        }
896
897        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
898            return mUidMap.get(userId);
899        }
900
901        public int size() {
902            // total number of pending broadcast entries across all userIds
903            int num = 0;
904            for (int i = 0; i< mUidMap.size(); i++) {
905                num += mUidMap.valueAt(i).size();
906            }
907            return num;
908        }
909
910        public void clear() {
911            mUidMap.clear();
912        }
913
914        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
915            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
916            if (map == null) {
917                map = new ArrayMap<String, ArrayList<String>>();
918                mUidMap.put(userId, map);
919            }
920            return map;
921        }
922    }
923    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
924
925    // Service Connection to remote media container service to copy
926    // package uri's from external media onto secure containers
927    // or internal storage.
928    private IMediaContainerService mContainerService = null;
929
930    static final int SEND_PENDING_BROADCAST = 1;
931    static final int MCS_BOUND = 3;
932    static final int END_COPY = 4;
933    static final int INIT_COPY = 5;
934    static final int MCS_UNBIND = 6;
935    static final int START_CLEANING_PACKAGE = 7;
936    static final int FIND_INSTALL_LOC = 8;
937    static final int POST_INSTALL = 9;
938    static final int MCS_RECONNECT = 10;
939    static final int MCS_GIVE_UP = 11;
940    static final int UPDATED_MEDIA_STATUS = 12;
941    static final int WRITE_SETTINGS = 13;
942    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
943    static final int PACKAGE_VERIFIED = 15;
944    static final int CHECK_PENDING_VERIFICATION = 16;
945    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
946    static final int INTENT_FILTER_VERIFIED = 18;
947
948    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
949
950    // Delay time in millisecs
951    static final int BROADCAST_DELAY = 10 * 1000;
952
953    static UserManagerService sUserManager;
954
955    // Stores a list of users whose package restrictions file needs to be updated
956    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
957
958    final private DefaultContainerConnection mDefContainerConn =
959            new DefaultContainerConnection();
960    class DefaultContainerConnection implements ServiceConnection {
961        public void onServiceConnected(ComponentName name, IBinder service) {
962            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
963            IMediaContainerService imcs =
964                IMediaContainerService.Stub.asInterface(service);
965            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
966        }
967
968        public void onServiceDisconnected(ComponentName name) {
969            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
970        }
971    }
972
973    // Recordkeeping of restore-after-install operations that are currently in flight
974    // between the Package Manager and the Backup Manager
975    static class PostInstallData {
976        public InstallArgs args;
977        public PackageInstalledInfo res;
978
979        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
980            args = _a;
981            res = _r;
982        }
983    }
984
985    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
986    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
987
988    // XML tags for backup/restore of various bits of state
989    private static final String TAG_PREFERRED_BACKUP = "pa";
990    private static final String TAG_DEFAULT_APPS = "da";
991    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
992
993    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
994    private static final String TAG_ALL_GRANTS = "rt-grants";
995    private static final String TAG_GRANT = "grant";
996    private static final String ATTR_PACKAGE_NAME = "pkg";
997
998    private static final String TAG_PERMISSION = "perm";
999    private static final String ATTR_PERMISSION_NAME = "name";
1000    private static final String ATTR_IS_GRANTED = "g";
1001    private static final String ATTR_USER_SET = "set";
1002    private static final String ATTR_USER_FIXED = "fixed";
1003    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1004
1005    // System/policy permission grants are not backed up
1006    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1007            FLAG_PERMISSION_POLICY_FIXED
1008            | FLAG_PERMISSION_SYSTEM_FIXED
1009            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1010
1011    // And we back up these user-adjusted states
1012    private static final int USER_RUNTIME_GRANT_MASK =
1013            FLAG_PERMISSION_USER_SET
1014            | FLAG_PERMISSION_USER_FIXED
1015            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1016
1017    final @Nullable String mRequiredVerifierPackage;
1018    final @Nullable String mRequiredInstallerPackage;
1019
1020    private final PackageUsage mPackageUsage = new PackageUsage();
1021
1022    private class PackageUsage {
1023        private static final int WRITE_INTERVAL
1024            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1025
1026        private final Object mFileLock = new Object();
1027        private final AtomicLong mLastWritten = new AtomicLong(0);
1028        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1029
1030        private boolean mIsHistoricalPackageUsageAvailable = true;
1031
1032        boolean isHistoricalPackageUsageAvailable() {
1033            return mIsHistoricalPackageUsageAvailable;
1034        }
1035
1036        void write(boolean force) {
1037            if (force) {
1038                writeInternal();
1039                return;
1040            }
1041            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1042                && !DEBUG_DEXOPT) {
1043                return;
1044            }
1045            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1046                new Thread("PackageUsage_DiskWriter") {
1047                    @Override
1048                    public void run() {
1049                        try {
1050                            writeInternal();
1051                        } finally {
1052                            mBackgroundWriteRunning.set(false);
1053                        }
1054                    }
1055                }.start();
1056            }
1057        }
1058
1059        private void writeInternal() {
1060            synchronized (mPackages) {
1061                synchronized (mFileLock) {
1062                    AtomicFile file = getFile();
1063                    FileOutputStream f = null;
1064                    try {
1065                        f = file.startWrite();
1066                        BufferedOutputStream out = new BufferedOutputStream(f);
1067                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1068                        StringBuilder sb = new StringBuilder();
1069                        for (PackageParser.Package pkg : mPackages.values()) {
1070                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1071                                continue;
1072                            }
1073                            sb.setLength(0);
1074                            sb.append(pkg.packageName);
1075                            sb.append(' ');
1076                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1077                            sb.append('\n');
1078                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1079                        }
1080                        out.flush();
1081                        file.finishWrite(f);
1082                    } catch (IOException e) {
1083                        if (f != null) {
1084                            file.failWrite(f);
1085                        }
1086                        Log.e(TAG, "Failed to write package usage times", e);
1087                    }
1088                }
1089            }
1090            mLastWritten.set(SystemClock.elapsedRealtime());
1091        }
1092
1093        void readLP() {
1094            synchronized (mFileLock) {
1095                AtomicFile file = getFile();
1096                BufferedInputStream in = null;
1097                try {
1098                    in = new BufferedInputStream(file.openRead());
1099                    StringBuffer sb = new StringBuffer();
1100                    while (true) {
1101                        String packageName = readToken(in, sb, ' ');
1102                        if (packageName == null) {
1103                            break;
1104                        }
1105                        String timeInMillisString = readToken(in, sb, '\n');
1106                        if (timeInMillisString == null) {
1107                            throw new IOException("Failed to find last usage time for package "
1108                                                  + packageName);
1109                        }
1110                        PackageParser.Package pkg = mPackages.get(packageName);
1111                        if (pkg == null) {
1112                            continue;
1113                        }
1114                        long timeInMillis;
1115                        try {
1116                            timeInMillis = Long.parseLong(timeInMillisString);
1117                        } catch (NumberFormatException e) {
1118                            throw new IOException("Failed to parse " + timeInMillisString
1119                                                  + " as a long.", e);
1120                        }
1121                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1122                    }
1123                } catch (FileNotFoundException expected) {
1124                    mIsHistoricalPackageUsageAvailable = false;
1125                } catch (IOException e) {
1126                    Log.w(TAG, "Failed to read package usage times", e);
1127                } finally {
1128                    IoUtils.closeQuietly(in);
1129                }
1130            }
1131            mLastWritten.set(SystemClock.elapsedRealtime());
1132        }
1133
1134        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1135                throws IOException {
1136            sb.setLength(0);
1137            while (true) {
1138                int ch = in.read();
1139                if (ch == -1) {
1140                    if (sb.length() == 0) {
1141                        return null;
1142                    }
1143                    throw new IOException("Unexpected EOF");
1144                }
1145                if (ch == endOfToken) {
1146                    return sb.toString();
1147                }
1148                sb.append((char)ch);
1149            }
1150        }
1151
1152        private AtomicFile getFile() {
1153            File dataDir = Environment.getDataDirectory();
1154            File systemDir = new File(dataDir, "system");
1155            File fname = new File(systemDir, "package-usage.list");
1156            return new AtomicFile(fname);
1157        }
1158    }
1159
1160    class PackageHandler extends Handler {
1161        private boolean mBound = false;
1162        final ArrayList<HandlerParams> mPendingInstalls =
1163            new ArrayList<HandlerParams>();
1164
1165        private boolean connectToService() {
1166            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1167                    " DefaultContainerService");
1168            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1170            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1171                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1172                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1173                mBound = true;
1174                return true;
1175            }
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1177            return false;
1178        }
1179
1180        private void disconnectService() {
1181            mContainerService = null;
1182            mBound = false;
1183            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1184            mContext.unbindService(mDefContainerConn);
1185            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186        }
1187
1188        PackageHandler(Looper looper) {
1189            super(looper);
1190        }
1191
1192        public void handleMessage(Message msg) {
1193            try {
1194                doHandleMessage(msg);
1195            } finally {
1196                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1197            }
1198        }
1199
1200        void doHandleMessage(Message msg) {
1201            switch (msg.what) {
1202                case INIT_COPY: {
1203                    HandlerParams params = (HandlerParams) msg.obj;
1204                    int idx = mPendingInstalls.size();
1205                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1206                    // If a bind was already initiated we dont really
1207                    // need to do anything. The pending install
1208                    // will be processed later on.
1209                    if (!mBound) {
1210                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                System.identityHashCode(mHandler));
1212                        // If this is the only one pending we might
1213                        // have to bind to the service again.
1214                        if (!connectToService()) {
1215                            Slog.e(TAG, "Failed to bind to media container service");
1216                            params.serviceError();
1217                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1218                                    System.identityHashCode(mHandler));
1219                            if (params.traceMethod != null) {
1220                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1221                                        params.traceCookie);
1222                            }
1223                            return;
1224                        } else {
1225                            // Once we bind to the service, the first
1226                            // pending request will be processed.
1227                            mPendingInstalls.add(idx, params);
1228                        }
1229                    } else {
1230                        mPendingInstalls.add(idx, params);
1231                        // Already bound to the service. Just make
1232                        // sure we trigger off processing the first request.
1233                        if (idx == 0) {
1234                            mHandler.sendEmptyMessage(MCS_BOUND);
1235                        }
1236                    }
1237                    break;
1238                }
1239                case MCS_BOUND: {
1240                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1241                    if (msg.obj != null) {
1242                        mContainerService = (IMediaContainerService) msg.obj;
1243                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1244                                System.identityHashCode(mHandler));
1245                    }
1246                    if (mContainerService == null) {
1247                        if (!mBound) {
1248                            // Something seriously wrong since we are not bound and we are not
1249                            // waiting for connection. Bail out.
1250                            Slog.e(TAG, "Cannot bind to media container service");
1251                            for (HandlerParams params : mPendingInstalls) {
1252                                // Indicate service bind error
1253                                params.serviceError();
1254                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1255                                        System.identityHashCode(params));
1256                                if (params.traceMethod != null) {
1257                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1258                                            params.traceMethod, params.traceCookie);
1259                                }
1260                                return;
1261                            }
1262                            mPendingInstalls.clear();
1263                        } else {
1264                            Slog.w(TAG, "Waiting to connect to media container service");
1265                        }
1266                    } else if (mPendingInstalls.size() > 0) {
1267                        HandlerParams params = mPendingInstalls.get(0);
1268                        if (params != null) {
1269                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1270                                    System.identityHashCode(params));
1271                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1272                            if (params.startCopy()) {
1273                                // We are done...  look for more work or to
1274                                // go idle.
1275                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1276                                        "Checking for more work or unbind...");
1277                                // Delete pending install
1278                                if (mPendingInstalls.size() > 0) {
1279                                    mPendingInstalls.remove(0);
1280                                }
1281                                if (mPendingInstalls.size() == 0) {
1282                                    if (mBound) {
1283                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1284                                                "Posting delayed MCS_UNBIND");
1285                                        removeMessages(MCS_UNBIND);
1286                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1287                                        // Unbind after a little delay, to avoid
1288                                        // continual thrashing.
1289                                        sendMessageDelayed(ubmsg, 10000);
1290                                    }
1291                                } else {
1292                                    // There are more pending requests in queue.
1293                                    // Just post MCS_BOUND message to trigger processing
1294                                    // of next pending install.
1295                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1296                                            "Posting MCS_BOUND for next work");
1297                                    mHandler.sendEmptyMessage(MCS_BOUND);
1298                                }
1299                            }
1300                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1301                        }
1302                    } else {
1303                        // Should never happen ideally.
1304                        Slog.w(TAG, "Empty queue");
1305                    }
1306                    break;
1307                }
1308                case MCS_RECONNECT: {
1309                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1310                    if (mPendingInstalls.size() > 0) {
1311                        if (mBound) {
1312                            disconnectService();
1313                        }
1314                        if (!connectToService()) {
1315                            Slog.e(TAG, "Failed to bind to media container service");
1316                            for (HandlerParams params : mPendingInstalls) {
1317                                // Indicate service bind error
1318                                params.serviceError();
1319                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                                        System.identityHashCode(params));
1321                            }
1322                            mPendingInstalls.clear();
1323                        }
1324                    }
1325                    break;
1326                }
1327                case MCS_UNBIND: {
1328                    // If there is no actual work left, then time to unbind.
1329                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1330
1331                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1332                        if (mBound) {
1333                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1334
1335                            disconnectService();
1336                        }
1337                    } else if (mPendingInstalls.size() > 0) {
1338                        // There are more pending requests in queue.
1339                        // Just post MCS_BOUND message to trigger processing
1340                        // of next pending install.
1341                        mHandler.sendEmptyMessage(MCS_BOUND);
1342                    }
1343
1344                    break;
1345                }
1346                case MCS_GIVE_UP: {
1347                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1348                    HandlerParams params = mPendingInstalls.remove(0);
1349                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1350                            System.identityHashCode(params));
1351                    break;
1352                }
1353                case SEND_PENDING_BROADCAST: {
1354                    String packages[];
1355                    ArrayList<String> components[];
1356                    int size = 0;
1357                    int uids[];
1358                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1359                    synchronized (mPackages) {
1360                        if (mPendingBroadcasts == null) {
1361                            return;
1362                        }
1363                        size = mPendingBroadcasts.size();
1364                        if (size <= 0) {
1365                            // Nothing to be done. Just return
1366                            return;
1367                        }
1368                        packages = new String[size];
1369                        components = new ArrayList[size];
1370                        uids = new int[size];
1371                        int i = 0;  // filling out the above arrays
1372
1373                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1374                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1375                            Iterator<Map.Entry<String, ArrayList<String>>> it
1376                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1377                                            .entrySet().iterator();
1378                            while (it.hasNext() && i < size) {
1379                                Map.Entry<String, ArrayList<String>> ent = it.next();
1380                                packages[i] = ent.getKey();
1381                                components[i] = ent.getValue();
1382                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1383                                uids[i] = (ps != null)
1384                                        ? UserHandle.getUid(packageUserId, ps.appId)
1385                                        : -1;
1386                                i++;
1387                            }
1388                        }
1389                        size = i;
1390                        mPendingBroadcasts.clear();
1391                    }
1392                    // Send broadcasts
1393                    for (int i = 0; i < size; i++) {
1394                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1395                    }
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1397                    break;
1398                }
1399                case START_CLEANING_PACKAGE: {
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401                    final String packageName = (String)msg.obj;
1402                    final int userId = msg.arg1;
1403                    final boolean andCode = msg.arg2 != 0;
1404                    synchronized (mPackages) {
1405                        if (userId == UserHandle.USER_ALL) {
1406                            int[] users = sUserManager.getUserIds();
1407                            for (int user : users) {
1408                                mSettings.addPackageToCleanLPw(
1409                                        new PackageCleanItem(user, packageName, andCode));
1410                            }
1411                        } else {
1412                            mSettings.addPackageToCleanLPw(
1413                                    new PackageCleanItem(userId, packageName, andCode));
1414                        }
1415                    }
1416                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417                    startCleaningPackages();
1418                } break;
1419                case POST_INSTALL: {
1420                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1421
1422                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1423                    mRunningInstalls.delete(msg.arg1);
1424                    boolean deleteOld = false;
1425
1426                    if (data != null) {
1427                        InstallArgs args = data.args;
1428                        PackageInstalledInfo res = data.res;
1429
1430                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1431                            //TODO: Broadcast for child packages too
1432                            final String packageName = res.pkg.applicationInfo.packageName;
1433                            res.removedInfo.sendBroadcast(false, true, false);
1434                            Bundle extras = new Bundle(1);
1435                            extras.putInt(Intent.EXTRA_UID, res.uid);
1436
1437                            // Now that we successfully installed the package, grant runtime
1438                            // permissions if requested before broadcasting the install.
1439                            if ((args.installFlags
1440                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1441                                    && res.pkg.applicationInfo.targetSdkVersion
1442                                            >= Build.VERSION_CODES.M) {
1443                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1444                                        args.installGrantPermissions);
1445                            }
1446
1447                            synchronized (mPackages) {
1448                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1449                            }
1450
1451                            // Determine the set of users who are adding this
1452                            // package for the first time vs. those who are seeing
1453                            // an update.
1454                            int[] firstUsers;
1455                            int[] updateUsers = new int[0];
1456                            if (res.origUsers == null || res.origUsers.length == 0) {
1457                                firstUsers = res.newUsers;
1458                            } else {
1459                                firstUsers = new int[0];
1460                                for (int i=0; i<res.newUsers.length; i++) {
1461                                    int user = res.newUsers[i];
1462                                    boolean isNew = true;
1463                                    for (int j=0; j<res.origUsers.length; j++) {
1464                                        if (res.origUsers[j] == user) {
1465                                            isNew = false;
1466                                            break;
1467                                        }
1468                                    }
1469                                    if (isNew) {
1470                                        int[] newFirst = new int[firstUsers.length+1];
1471                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1472                                                firstUsers.length);
1473                                        newFirst[firstUsers.length] = user;
1474                                        firstUsers = newFirst;
1475                                    } else {
1476                                        int[] newUpdate = new int[updateUsers.length+1];
1477                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1478                                                updateUsers.length);
1479                                        newUpdate[updateUsers.length] = user;
1480                                        updateUsers = newUpdate;
1481                                    }
1482                                }
1483                            }
1484                            // don't broadcast for ephemeral installs/updates
1485                            final boolean isEphemeral = isEphemeral(res.pkg);
1486                            if (!isEphemeral) {
1487                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1488                                        extras, 0 /*flags*/, null /*targetPackage*/,
1489                                        null /*finishedReceiver*/, firstUsers);
1490                            }
1491                            final boolean update = res.removedInfo.removedPackage != null;
1492                            if (update) {
1493                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1494                            }
1495                            if (!isEphemeral) {
1496                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1497                                        extras, 0 /*flags*/, null /*targetPackage*/,
1498                                        null /*finishedReceiver*/, updateUsers);
1499                            }
1500                            if (update) {
1501                                if (!isEphemeral) {
1502                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1503                                            packageName, extras, 0 /*flags*/,
1504                                            null /*targetPackage*/, null /*finishedReceiver*/,
1505                                            updateUsers);
1506                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1507                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1508                                            packageName /*targetPackage*/,
1509                                            null /*finishedReceiver*/, updateUsers);
1510                                }
1511
1512                                // treat asec-hosted packages like removable media on upgrade
1513                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1514                                    if (DEBUG_INSTALL) {
1515                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1516                                                + " is ASEC-hosted -> AVAILABLE");
1517                                    }
1518                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1519                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1520                                    pkgList.add(packageName);
1521                                    sendResourcesChangedBroadcast(true, true,
1522                                            pkgList,uidArray, null);
1523                                }
1524                            }
1525                            if (res.removedInfo.args != null) {
1526                                // Remove the replaced package's older resources safely now
1527                                deleteOld = true;
1528                            }
1529
1530
1531                            // Work that needs to happen on first install within each user
1532                            if (firstUsers.length > 0) {
1533                                for (int userId : firstUsers) {
1534                                    synchronized (mPackages) {
1535                                        // If this app is a browser and it's newly-installed for
1536                                        // some users, clear any default-browser state in those
1537                                        // users.  The app's nature doesn't depend on the user,
1538                                        // so we can just check its browser nature in any user
1539                                        // and generalize.
1540                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1541                                            mSettings.setDefaultBrowserPackageNameLPw(
1542                                                    null, userId);
1543                                        }
1544
1545                                        // We may also need to apply pending (restored) runtime
1546                                        // permission grants within these users.
1547                                        mSettings.applyPendingPermissionGrantsLPw(
1548                                                packageName, userId);
1549                                    }
1550                                }
1551                            }
1552                            // Log current value of "unknown sources" setting
1553                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1554                                getUnknownSourcesSettings());
1555                        }
1556                        // Force a gc to clear up things
1557                        Runtime.getRuntime().gc();
1558                        // We delete after a gc for applications  on sdcard.
1559                        if (deleteOld) {
1560                            synchronized (mInstallLock) {
1561                                res.removedInfo.args.doPostDeleteLI(true);
1562                            }
1563                        }
1564                        if (args.observer != null) {
1565                            try {
1566                                Bundle extras = extrasForInstallResult(res);
1567                                args.observer.onPackageInstalled(res.name, res.returnCode,
1568                                        res.returnMsg, extras);
1569                            } catch (RemoteException e) {
1570                                Slog.i(TAG, "Observer no longer exists.");
1571                            }
1572                        }
1573                        if (args.traceMethod != null) {
1574                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1575                                    args.traceCookie);
1576                        }
1577                        return;
1578                    } else {
1579                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1580                    }
1581
1582                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1583                } break;
1584                case UPDATED_MEDIA_STATUS: {
1585                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1586                    boolean reportStatus = msg.arg1 == 1;
1587                    boolean doGc = msg.arg2 == 1;
1588                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1589                    if (doGc) {
1590                        // Force a gc to clear up stale containers.
1591                        Runtime.getRuntime().gc();
1592                    }
1593                    if (msg.obj != null) {
1594                        @SuppressWarnings("unchecked")
1595                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1596                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1597                        // Unload containers
1598                        unloadAllContainers(args);
1599                    }
1600                    if (reportStatus) {
1601                        try {
1602                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1603                            PackageHelper.getMountService().finishMediaUpdate();
1604                        } catch (RemoteException e) {
1605                            Log.e(TAG, "MountService not running?");
1606                        }
1607                    }
1608                } break;
1609                case WRITE_SETTINGS: {
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    synchronized (mPackages) {
1612                        removeMessages(WRITE_SETTINGS);
1613                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1614                        mSettings.writeLPr();
1615                        mDirtyUsers.clear();
1616                    }
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1618                } break;
1619                case WRITE_PACKAGE_RESTRICTIONS: {
1620                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1621                    synchronized (mPackages) {
1622                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1623                        for (int userId : mDirtyUsers) {
1624                            mSettings.writePackageRestrictionsLPr(userId);
1625                        }
1626                        mDirtyUsers.clear();
1627                    }
1628                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1629                } break;
1630                case CHECK_PENDING_VERIFICATION: {
1631                    final int verificationId = msg.arg1;
1632                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1633
1634                    if ((state != null) && !state.timeoutExtended()) {
1635                        final InstallArgs args = state.getInstallArgs();
1636                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1637
1638                        Slog.i(TAG, "Verification timed out for " + originUri);
1639                        mPendingVerification.remove(verificationId);
1640
1641                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1642
1643                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1644                            Slog.i(TAG, "Continuing with installation of " + originUri);
1645                            state.setVerifierResponse(Binder.getCallingUid(),
1646                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1647                            broadcastPackageVerified(verificationId, originUri,
1648                                    PackageManager.VERIFICATION_ALLOW,
1649                                    state.getInstallArgs().getUser());
1650                            try {
1651                                ret = args.copyApk(mContainerService, true);
1652                            } catch (RemoteException e) {
1653                                Slog.e(TAG, "Could not contact the ContainerService");
1654                            }
1655                        } else {
1656                            broadcastPackageVerified(verificationId, originUri,
1657                                    PackageManager.VERIFICATION_REJECT,
1658                                    state.getInstallArgs().getUser());
1659                        }
1660
1661                        Trace.asyncTraceEnd(
1662                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1663
1664                        processPendingInstall(args, ret);
1665                        mHandler.sendEmptyMessage(MCS_UNBIND);
1666                    }
1667                    break;
1668                }
1669                case PACKAGE_VERIFIED: {
1670                    final int verificationId = msg.arg1;
1671
1672                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1673                    if (state == null) {
1674                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1675                        break;
1676                    }
1677
1678                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1679
1680                    state.setVerifierResponse(response.callerUid, response.code);
1681
1682                    if (state.isVerificationComplete()) {
1683                        mPendingVerification.remove(verificationId);
1684
1685                        final InstallArgs args = state.getInstallArgs();
1686                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1687
1688                        int ret;
1689                        if (state.isInstallAllowed()) {
1690                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1691                            broadcastPackageVerified(verificationId, originUri,
1692                                    response.code, state.getInstallArgs().getUser());
1693                            try {
1694                                ret = args.copyApk(mContainerService, true);
1695                            } catch (RemoteException e) {
1696                                Slog.e(TAG, "Could not contact the ContainerService");
1697                            }
1698                        } else {
1699                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1700                        }
1701
1702                        Trace.asyncTraceEnd(
1703                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1704
1705                        processPendingInstall(args, ret);
1706                        mHandler.sendEmptyMessage(MCS_UNBIND);
1707                    }
1708
1709                    break;
1710                }
1711                case START_INTENT_FILTER_VERIFICATIONS: {
1712                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1713                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1714                            params.replacing, params.pkg);
1715                    break;
1716                }
1717                case INTENT_FILTER_VERIFIED: {
1718                    final int verificationId = msg.arg1;
1719
1720                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1721                            verificationId);
1722                    if (state == null) {
1723                        Slog.w(TAG, "Invalid IntentFilter verification token "
1724                                + verificationId + " received");
1725                        break;
1726                    }
1727
1728                    final int userId = state.getUserId();
1729
1730                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1731                            "Processing IntentFilter verification with token:"
1732                            + verificationId + " and userId:" + userId);
1733
1734                    final IntentFilterVerificationResponse response =
1735                            (IntentFilterVerificationResponse) msg.obj;
1736
1737                    state.setVerifierResponse(response.callerUid, response.code);
1738
1739                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1740                            "IntentFilter verification with token:" + verificationId
1741                            + " and userId:" + userId
1742                            + " is settings verifier response with response code:"
1743                            + response.code);
1744
1745                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1746                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1747                                + response.getFailedDomainsString());
1748                    }
1749
1750                    if (state.isVerificationComplete()) {
1751                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1752                    } else {
1753                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1754                                "IntentFilter verification with token:" + verificationId
1755                                + " was not said to be complete");
1756                    }
1757
1758                    break;
1759                }
1760            }
1761        }
1762    }
1763
1764    private StorageEventListener mStorageListener = new StorageEventListener() {
1765        @Override
1766        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1767            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1768                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1769                    final String volumeUuid = vol.getFsUuid();
1770
1771                    // Clean up any users or apps that were removed or recreated
1772                    // while this volume was missing
1773                    reconcileUsers(volumeUuid);
1774                    reconcileApps(volumeUuid);
1775
1776                    // Clean up any install sessions that expired or were
1777                    // cancelled while this volume was missing
1778                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1779
1780                    loadPrivatePackages(vol);
1781
1782                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1783                    unloadPrivatePackages(vol);
1784                }
1785            }
1786
1787            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1788                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1789                    updateExternalMediaStatus(true, false);
1790                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1791                    updateExternalMediaStatus(false, false);
1792                }
1793            }
1794        }
1795
1796        @Override
1797        public void onVolumeForgotten(String fsUuid) {
1798            if (TextUtils.isEmpty(fsUuid)) {
1799                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1800                return;
1801            }
1802
1803            // Remove any apps installed on the forgotten volume
1804            synchronized (mPackages) {
1805                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1806                for (PackageSetting ps : packages) {
1807                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1808                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1809                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1810                }
1811
1812                mSettings.onVolumeForgotten(fsUuid);
1813                mSettings.writeLPr();
1814            }
1815        }
1816    };
1817
1818    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1819            String[] grantedPermissions) {
1820        if (userId >= UserHandle.USER_SYSTEM) {
1821            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1822        } else if (userId == UserHandle.USER_ALL) {
1823            final int[] userIds;
1824            synchronized (mPackages) {
1825                userIds = UserManagerService.getInstance().getUserIds();
1826            }
1827            for (int someUserId : userIds) {
1828                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1829            }
1830        }
1831
1832        // We could have touched GID membership, so flush out packages.list
1833        synchronized (mPackages) {
1834            mSettings.writePackageListLPr();
1835        }
1836    }
1837
1838    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1839            String[] grantedPermissions) {
1840        SettingBase sb = (SettingBase) pkg.mExtras;
1841        if (sb == null) {
1842            return;
1843        }
1844
1845        PermissionsState permissionsState = sb.getPermissionsState();
1846
1847        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1848                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1849
1850        synchronized (mPackages) {
1851            for (String permission : pkg.requestedPermissions) {
1852                BasePermission bp = mSettings.mPermissions.get(permission);
1853                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1854                        && (grantedPermissions == null
1855                               || ArrayUtils.contains(grantedPermissions, permission))) {
1856                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1857                    // Installer cannot change immutable permissions.
1858                    if ((flags & immutableFlags) == 0) {
1859                        grantRuntimePermission(pkg.packageName, permission, userId);
1860                    }
1861                }
1862            }
1863        }
1864    }
1865
1866    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1867        Bundle extras = null;
1868        switch (res.returnCode) {
1869            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1870                extras = new Bundle();
1871                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1872                        res.origPermission);
1873                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1874                        res.origPackage);
1875                break;
1876            }
1877            case PackageManager.INSTALL_SUCCEEDED: {
1878                extras = new Bundle();
1879                extras.putBoolean(Intent.EXTRA_REPLACING,
1880                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1881                break;
1882            }
1883        }
1884        return extras;
1885    }
1886
1887    void scheduleWriteSettingsLocked() {
1888        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1889            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1890        }
1891    }
1892
1893    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1894        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1895        scheduleWritePackageRestrictionsLocked(userId);
1896    }
1897
1898    void scheduleWritePackageRestrictionsLocked(int userId) {
1899        final int[] userIds = (userId == UserHandle.USER_ALL)
1900                ? sUserManager.getUserIds() : new int[]{userId};
1901        for (int nextUserId : userIds) {
1902            if (!sUserManager.exists(nextUserId)) return;
1903            mDirtyUsers.add(nextUserId);
1904            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1905                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1906            }
1907        }
1908    }
1909
1910    public static PackageManagerService main(Context context, Installer installer,
1911            boolean factoryTest, boolean onlyCore) {
1912        PackageManagerService m = new PackageManagerService(context, installer,
1913                factoryTest, onlyCore);
1914        m.enableSystemUserPackages();
1915        ServiceManager.addService("package", m);
1916        return m;
1917    }
1918
1919    private void enableSystemUserPackages() {
1920        if (!UserManager.isSplitSystemUser()) {
1921            return;
1922        }
1923        // For system user, enable apps based on the following conditions:
1924        // - app is whitelisted or belong to one of these groups:
1925        //   -- system app which has no launcher icons
1926        //   -- system app which has INTERACT_ACROSS_USERS permission
1927        //   -- system IME app
1928        // - app is not in the blacklist
1929        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1930        Set<String> enableApps = new ArraySet<>();
1931        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1932                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1933                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1934        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1935        enableApps.addAll(wlApps);
1936        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1937                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1938        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1939        enableApps.removeAll(blApps);
1940        Log.i(TAG, "Applications installed for system user: " + enableApps);
1941        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1942                UserHandle.SYSTEM);
1943        final int allAppsSize = allAps.size();
1944        synchronized (mPackages) {
1945            for (int i = 0; i < allAppsSize; i++) {
1946                String pName = allAps.get(i);
1947                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1948                // Should not happen, but we shouldn't be failing if it does
1949                if (pkgSetting == null) {
1950                    continue;
1951                }
1952                boolean install = enableApps.contains(pName);
1953                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1954                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1955                            + " for system user");
1956                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1957                }
1958            }
1959        }
1960    }
1961
1962    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1963        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1964                Context.DISPLAY_SERVICE);
1965        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1966    }
1967
1968    public PackageManagerService(Context context, Installer installer,
1969            boolean factoryTest, boolean onlyCore) {
1970        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1971                SystemClock.uptimeMillis());
1972
1973        if (mSdkVersion <= 0) {
1974            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1975        }
1976
1977        mContext = context;
1978        mFactoryTest = factoryTest;
1979        mOnlyCore = onlyCore;
1980        mMetrics = new DisplayMetrics();
1981        mSettings = new Settings(mPackages);
1982        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1983                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1984        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1985                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1986        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1987                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1988        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1989                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1990        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1991                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1992        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1993                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1994
1995        String separateProcesses = SystemProperties.get("debug.separate_processes");
1996        if (separateProcesses != null && separateProcesses.length() > 0) {
1997            if ("*".equals(separateProcesses)) {
1998                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1999                mSeparateProcesses = null;
2000                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2001            } else {
2002                mDefParseFlags = 0;
2003                mSeparateProcesses = separateProcesses.split(",");
2004                Slog.w(TAG, "Running with debug.separate_processes: "
2005                        + separateProcesses);
2006            }
2007        } else {
2008            mDefParseFlags = 0;
2009            mSeparateProcesses = null;
2010        }
2011
2012        mInstaller = installer;
2013        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2014                "*dexopt*");
2015        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2016
2017        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2018                FgThread.get().getLooper());
2019
2020        getDefaultDisplayMetrics(context, mMetrics);
2021
2022        SystemConfig systemConfig = SystemConfig.getInstance();
2023        mGlobalGids = systemConfig.getGlobalGids();
2024        mSystemPermissions = systemConfig.getSystemPermissions();
2025        mAvailableFeatures = systemConfig.getAvailableFeatures();
2026
2027        synchronized (mInstallLock) {
2028        // writer
2029        synchronized (mPackages) {
2030            mHandlerThread = new ServiceThread(TAG,
2031                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2032            mHandlerThread.start();
2033            mHandler = new PackageHandler(mHandlerThread.getLooper());
2034            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2035
2036            File dataDir = Environment.getDataDirectory();
2037            mAppInstallDir = new File(dataDir, "app");
2038            mAppLib32InstallDir = new File(dataDir, "app-lib");
2039            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2040            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2041            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2042
2043            sUserManager = new UserManagerService(context, this, mPackages);
2044
2045            // Propagate permission configuration in to package manager.
2046            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2047                    = systemConfig.getPermissions();
2048            for (int i=0; i<permConfig.size(); i++) {
2049                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2050                BasePermission bp = mSettings.mPermissions.get(perm.name);
2051                if (bp == null) {
2052                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2053                    mSettings.mPermissions.put(perm.name, bp);
2054                }
2055                if (perm.gids != null) {
2056                    bp.setGids(perm.gids, perm.perUser);
2057                }
2058            }
2059
2060            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2061            for (int i=0; i<libConfig.size(); i++) {
2062                mSharedLibraries.put(libConfig.keyAt(i),
2063                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2064            }
2065
2066            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2067
2068            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2069
2070            String customResolverActivity = Resources.getSystem().getString(
2071                    R.string.config_customResolverActivity);
2072            if (TextUtils.isEmpty(customResolverActivity)) {
2073                customResolverActivity = null;
2074            } else {
2075                mCustomResolverComponentName = ComponentName.unflattenFromString(
2076                        customResolverActivity);
2077            }
2078
2079            long startTime = SystemClock.uptimeMillis();
2080
2081            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2082                    startTime);
2083
2084            // Set flag to monitor and not change apk file paths when
2085            // scanning install directories.
2086            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2087
2088            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2089            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2090
2091            if (bootClassPath == null) {
2092                Slog.w(TAG, "No BOOTCLASSPATH found!");
2093            }
2094
2095            if (systemServerClassPath == null) {
2096                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2097            }
2098
2099            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2100            final String[] dexCodeInstructionSets =
2101                    getDexCodeInstructionSets(
2102                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2103
2104            /**
2105             * Ensure all external libraries have had dexopt run on them.
2106             */
2107            if (mSharedLibraries.size() > 0) {
2108                // NOTE: For now, we're compiling these system "shared libraries"
2109                // (and framework jars) into all available architectures. It's possible
2110                // to compile them only when we come across an app that uses them (there's
2111                // already logic for that in scanPackageLI) but that adds some complexity.
2112                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2113                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2114                        final String lib = libEntry.path;
2115                        if (lib == null) {
2116                            continue;
2117                        }
2118
2119                        try {
2120                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2121                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2122                                // Shared libraries do not have profiles so we perform a full
2123                                // AOT compilation.
2124                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2125                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2126                                        StorageManager.UUID_PRIVATE_INTERNAL,
2127                                        false /*useProfiles*/);
2128                            }
2129                        } catch (FileNotFoundException e) {
2130                            Slog.w(TAG, "Library not found: " + lib);
2131                        } catch (IOException | InstallerException e) {
2132                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2133                                    + e.getMessage());
2134                        }
2135                    }
2136                }
2137            }
2138
2139            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2140
2141            final VersionInfo ver = mSettings.getInternalVersion();
2142            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2143            // when upgrading from pre-M, promote system app permissions from install to runtime
2144            mPromoteSystemApps =
2145                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2146
2147            // save off the names of pre-existing system packages prior to scanning; we don't
2148            // want to automatically grant runtime permissions for new system apps
2149            if (mPromoteSystemApps) {
2150                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2151                while (pkgSettingIter.hasNext()) {
2152                    PackageSetting ps = pkgSettingIter.next();
2153                    if (isSystemApp(ps)) {
2154                        mExistingSystemPackages.add(ps.name);
2155                    }
2156                }
2157            }
2158
2159            // Collect vendor overlay packages.
2160            // (Do this before scanning any apps.)
2161            // For security and version matching reason, only consider
2162            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2163            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2164            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2165                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2166
2167            // Find base frameworks (resource packages without code).
2168            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2169                    | PackageParser.PARSE_IS_SYSTEM_DIR
2170                    | PackageParser.PARSE_IS_PRIVILEGED,
2171                    scanFlags | SCAN_NO_DEX, 0);
2172
2173            // Collected privileged system packages.
2174            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2175            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2176                    | PackageParser.PARSE_IS_SYSTEM_DIR
2177                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2178
2179            // Collect ordinary system packages.
2180            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2181            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2182                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2183
2184            // Collect all vendor packages.
2185            File vendorAppDir = new File("/vendor/app");
2186            try {
2187                vendorAppDir = vendorAppDir.getCanonicalFile();
2188            } catch (IOException e) {
2189                // failed to look up canonical path, continue with original one
2190            }
2191            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2192                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2193
2194            // Collect all OEM packages.
2195            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2196            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2197                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2198
2199            // Prune any system packages that no longer exist.
2200            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2201            if (!mOnlyCore) {
2202                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2203                while (psit.hasNext()) {
2204                    PackageSetting ps = psit.next();
2205
2206                    /*
2207                     * If this is not a system app, it can't be a
2208                     * disable system app.
2209                     */
2210                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2211                        continue;
2212                    }
2213
2214                    /*
2215                     * If the package is scanned, it's not erased.
2216                     */
2217                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2218                    if (scannedPkg != null) {
2219                        /*
2220                         * If the system app is both scanned and in the
2221                         * disabled packages list, then it must have been
2222                         * added via OTA. Remove it from the currently
2223                         * scanned package so the previously user-installed
2224                         * application can be scanned.
2225                         */
2226                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2227                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2228                                    + ps.name + "; removing system app.  Last known codePath="
2229                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2230                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2231                                    + scannedPkg.mVersionCode);
2232                            removePackageSettingLI(scannedPkg, true);
2233                            mExpectingBetter.put(ps.name, ps.codePath);
2234                        }
2235
2236                        continue;
2237                    }
2238
2239                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2240                        psit.remove();
2241                        logCriticalInfo(Log.WARN, "System package " + ps.name
2242                                + " no longer exists; wiping its data");
2243                        removeDataDirsLI(null, ps.name);
2244                    } else {
2245                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2246                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2247                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2248                        }
2249                    }
2250                }
2251            }
2252
2253            //look for any incomplete package installations
2254            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2255            //clean up list
2256            for(int i = 0; i < deletePkgsList.size(); i++) {
2257                //clean up here
2258                cleanupInstallFailedPackage(deletePkgsList.get(i));
2259            }
2260            //delete tmp files
2261            deleteTempPackageFiles();
2262
2263            // Remove any shared userIDs that have no associated packages
2264            mSettings.pruneSharedUsersLPw();
2265
2266            if (!mOnlyCore) {
2267                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2268                        SystemClock.uptimeMillis());
2269                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2270
2271                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2272                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2273
2274                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2275                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2276
2277                /**
2278                 * Remove disable package settings for any updated system
2279                 * apps that were removed via an OTA. If they're not a
2280                 * previously-updated app, remove them completely.
2281                 * Otherwise, just revoke their system-level permissions.
2282                 */
2283                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2284                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2285                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2286
2287                    String msg;
2288                    if (deletedPkg == null) {
2289                        msg = "Updated system package " + deletedAppName
2290                                + " no longer exists; wiping its data";
2291                        removeDataDirsLI(null, deletedAppName);
2292                    } else {
2293                        msg = "Updated system app + " + deletedAppName
2294                                + " no longer present; removing system privileges for "
2295                                + deletedAppName;
2296
2297                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2298
2299                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2300                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2301                    }
2302                    logCriticalInfo(Log.WARN, msg);
2303                }
2304
2305                /**
2306                 * Make sure all system apps that we expected to appear on
2307                 * the userdata partition actually showed up. If they never
2308                 * appeared, crawl back and revive the system version.
2309                 */
2310                for (int i = 0; i < mExpectingBetter.size(); i++) {
2311                    final String packageName = mExpectingBetter.keyAt(i);
2312                    if (!mPackages.containsKey(packageName)) {
2313                        final File scanFile = mExpectingBetter.valueAt(i);
2314
2315                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2316                                + " but never showed up; reverting to system");
2317
2318                        final int reparseFlags;
2319                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2320                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2321                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2322                                    | PackageParser.PARSE_IS_PRIVILEGED;
2323                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2324                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2325                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2326                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2327                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2328                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2329                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2330                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2331                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2332                        } else {
2333                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2334                            continue;
2335                        }
2336
2337                        mSettings.enableSystemPackageLPw(packageName);
2338
2339                        try {
2340                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2341                        } catch (PackageManagerException e) {
2342                            Slog.e(TAG, "Failed to parse original system package: "
2343                                    + e.getMessage());
2344                        }
2345                    }
2346                }
2347            }
2348            mExpectingBetter.clear();
2349
2350            // Now that we know all of the shared libraries, update all clients to have
2351            // the correct library paths.
2352            updateAllSharedLibrariesLPw();
2353
2354            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2355                // NOTE: We ignore potential failures here during a system scan (like
2356                // the rest of the commands above) because there's precious little we
2357                // can do about it. A settings error is reported, though.
2358                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2359                        false /* boot complete */);
2360            }
2361
2362            // Now that we know all the packages we are keeping,
2363            // read and update their last usage times.
2364            mPackageUsage.readLP();
2365
2366            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2367                    SystemClock.uptimeMillis());
2368            Slog.i(TAG, "Time to scan packages: "
2369                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2370                    + " seconds");
2371
2372            // If the platform SDK has changed since the last time we booted,
2373            // we need to re-grant app permission to catch any new ones that
2374            // appear.  This is really a hack, and means that apps can in some
2375            // cases get permissions that the user didn't initially explicitly
2376            // allow...  it would be nice to have some better way to handle
2377            // this situation.
2378            int updateFlags = UPDATE_PERMISSIONS_ALL;
2379            if (ver.sdkVersion != mSdkVersion) {
2380                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2381                        + mSdkVersion + "; regranting permissions for internal storage");
2382                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2383            }
2384            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2385            ver.sdkVersion = mSdkVersion;
2386
2387            // If this is the first boot or an update from pre-M, and it is a normal
2388            // boot, then we need to initialize the default preferred apps across
2389            // all defined users.
2390            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2391                for (UserInfo user : sUserManager.getUsers(true)) {
2392                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2393                    applyFactoryDefaultBrowserLPw(user.id);
2394                    primeDomainVerificationsLPw(user.id);
2395                }
2396            }
2397
2398            // Prepare storage for system user really early during boot,
2399            // since core system apps like SettingsProvider and SystemUI
2400            // can't wait for user to start
2401            final int storageFlags;
2402            if (StorageManager.isFileBasedEncryptionEnabled()) {
2403                storageFlags = StorageManager.FLAG_STORAGE_DE;
2404            } else {
2405                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2406            }
2407            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2408                    storageFlags);
2409
2410            if (!StorageManager.isFileBasedEncryptionEnabled()
2411                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2412                // When upgrading a non-FBE device, we might need to shuffle
2413                // around the default storage location of system apps
2414                final List<UserInfo> users = sUserManager.getUsers(true);
2415                for (PackageSetting ps : mSettings.mPackages.values()) {
2416                    if (ps.pkg == null || !ps.isSystem()) continue;
2417                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2418                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2419                    for (UserInfo user : users) {
2420                        if (ps.getInstalled(user.id)) {
2421                            try {
2422                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2423                                        ps.name, user.id, storageTarget);
2424                            } catch (InstallerException e) {
2425                                logCriticalInfo(Log.WARN,
2426                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2427                            }
2428                            // We may have just shuffled around app data
2429                            // directories, so prepare it one more time
2430                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2431                                    storageFlags, ps.pkg, false);
2432                        }
2433                    }
2434                }
2435            }
2436
2437            // If this is first boot after an OTA, and a normal boot, then
2438            // we need to clear code cache directories.
2439            if (mIsUpgrade && !onlyCore) {
2440                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2441                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2442                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2443                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2444                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2445                    }
2446                }
2447                ver.fingerprint = Build.FINGERPRINT;
2448            }
2449
2450            checkDefaultBrowser();
2451
2452            // clear only after permissions and other defaults have been updated
2453            mExistingSystemPackages.clear();
2454            mPromoteSystemApps = false;
2455
2456            // All the changes are done during package scanning.
2457            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2458
2459            // can downgrade to reader
2460            mSettings.writeLPr();
2461
2462            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2463                    SystemClock.uptimeMillis());
2464
2465            if (!mOnlyCore) {
2466                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2467                mRequiredInstallerPackage = getRequiredInstallerLPr();
2468                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2469                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2470                        mIntentFilterVerifierComponent);
2471            } else {
2472                mRequiredVerifierPackage = null;
2473                mRequiredInstallerPackage = null;
2474                mIntentFilterVerifierComponent = null;
2475                mIntentFilterVerifier = null;
2476            }
2477
2478            mInstallerService = new PackageInstallerService(context, this);
2479
2480            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2481            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2482            // both the installer and resolver must be present to enable ephemeral
2483            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2484                if (DEBUG_EPHEMERAL) {
2485                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2486                            + " installer:" + ephemeralInstallerComponent);
2487                }
2488                mEphemeralResolverComponent = ephemeralResolverComponent;
2489                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2490                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2491                mEphemeralResolverConnection =
2492                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2493            } else {
2494                if (DEBUG_EPHEMERAL) {
2495                    final String missingComponent =
2496                            (ephemeralResolverComponent == null)
2497                            ? (ephemeralInstallerComponent == null)
2498                                    ? "resolver and installer"
2499                                    : "resolver"
2500                            : "installer";
2501                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2502                }
2503                mEphemeralResolverComponent = null;
2504                mEphemeralInstallerComponent = null;
2505                mEphemeralResolverConnection = null;
2506            }
2507
2508            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2509        } // synchronized (mPackages)
2510        } // synchronized (mInstallLock)
2511
2512        // Now after opening every single application zip, make sure they
2513        // are all flushed.  Not really needed, but keeps things nice and
2514        // tidy.
2515        Runtime.getRuntime().gc();
2516
2517        // The initial scanning above does many calls into installd while
2518        // holding the mPackages lock, but we're mostly interested in yelling
2519        // once we have a booted system.
2520        mInstaller.setWarnIfHeld(mPackages);
2521
2522        // Expose private service for system components to use.
2523        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2524    }
2525
2526    @Override
2527    public boolean isFirstBoot() {
2528        return !mRestoredSettings;
2529    }
2530
2531    @Override
2532    public boolean isOnlyCoreApps() {
2533        return mOnlyCore;
2534    }
2535
2536    @Override
2537    public boolean isUpgrade() {
2538        return mIsUpgrade;
2539    }
2540
2541    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2542        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2543
2544        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2545                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2546        if (matches.size() == 1) {
2547            return matches.get(0).getComponentInfo().packageName;
2548        } else {
2549            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2550            return null;
2551        }
2552    }
2553
2554    private @NonNull String getRequiredInstallerLPr() {
2555        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2556        intent.addCategory(Intent.CATEGORY_DEFAULT);
2557        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2558
2559        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2560                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2561        if (matches.size() == 1) {
2562            return matches.get(0).getComponentInfo().packageName;
2563        } else {
2564            throw new RuntimeException("There must be exactly one installer; found " + matches);
2565        }
2566    }
2567
2568    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2569        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2570
2571        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2572                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2573        ResolveInfo best = null;
2574        final int N = matches.size();
2575        for (int i = 0; i < N; i++) {
2576            final ResolveInfo cur = matches.get(i);
2577            final String packageName = cur.getComponentInfo().packageName;
2578            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2579                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2580                continue;
2581            }
2582
2583            if (best == null || cur.priority > best.priority) {
2584                best = cur;
2585            }
2586        }
2587
2588        if (best != null) {
2589            return best.getComponentInfo().getComponentName();
2590        } else {
2591            throw new RuntimeException("There must be at least one intent filter verifier");
2592        }
2593    }
2594
2595    private @Nullable ComponentName getEphemeralResolverLPr() {
2596        final String[] packageArray =
2597                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2598        if (packageArray.length == 0) {
2599            if (DEBUG_EPHEMERAL) {
2600                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2601            }
2602            return null;
2603        }
2604
2605        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2606        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2607                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2608
2609        final int N = resolvers.size();
2610        if (N == 0) {
2611            if (DEBUG_EPHEMERAL) {
2612                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2613            }
2614            return null;
2615        }
2616
2617        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2618        for (int i = 0; i < N; i++) {
2619            final ResolveInfo info = resolvers.get(i);
2620
2621            if (info.serviceInfo == null) {
2622                continue;
2623            }
2624
2625            final String packageName = info.serviceInfo.packageName;
2626            if (!possiblePackages.contains(packageName)) {
2627                if (DEBUG_EPHEMERAL) {
2628                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2629                            + " pkg: " + packageName + ", info:" + info);
2630                }
2631                continue;
2632            }
2633
2634            if (DEBUG_EPHEMERAL) {
2635                Slog.v(TAG, "Ephemeral resolver found;"
2636                        + " pkg: " + packageName + ", info:" + info);
2637            }
2638            return new ComponentName(packageName, info.serviceInfo.name);
2639        }
2640        if (DEBUG_EPHEMERAL) {
2641            Slog.v(TAG, "Ephemeral resolver NOT found");
2642        }
2643        return null;
2644    }
2645
2646    private @Nullable ComponentName getEphemeralInstallerLPr() {
2647        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2648        intent.addCategory(Intent.CATEGORY_DEFAULT);
2649        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2650
2651        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2652                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2653        if (matches.size() == 0) {
2654            return null;
2655        } else if (matches.size() == 1) {
2656            return matches.get(0).getComponentInfo().getComponentName();
2657        } else {
2658            throw new RuntimeException(
2659                    "There must be at most one ephemeral installer; found " + matches);
2660        }
2661    }
2662
2663    private void primeDomainVerificationsLPw(int userId) {
2664        if (DEBUG_DOMAIN_VERIFICATION) {
2665            Slog.d(TAG, "Priming domain verifications in user " + userId);
2666        }
2667
2668        SystemConfig systemConfig = SystemConfig.getInstance();
2669        ArraySet<String> packages = systemConfig.getLinkedApps();
2670        ArraySet<String> domains = new ArraySet<String>();
2671
2672        for (String packageName : packages) {
2673            PackageParser.Package pkg = mPackages.get(packageName);
2674            if (pkg != null) {
2675                if (!pkg.isSystemApp()) {
2676                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2677                    continue;
2678                }
2679
2680                domains.clear();
2681                for (PackageParser.Activity a : pkg.activities) {
2682                    for (ActivityIntentInfo filter : a.intents) {
2683                        if (hasValidDomains(filter)) {
2684                            domains.addAll(filter.getHostsList());
2685                        }
2686                    }
2687                }
2688
2689                if (domains.size() > 0) {
2690                    if (DEBUG_DOMAIN_VERIFICATION) {
2691                        Slog.v(TAG, "      + " + packageName);
2692                    }
2693                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2694                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2695                    // and then 'always' in the per-user state actually used for intent resolution.
2696                    final IntentFilterVerificationInfo ivi;
2697                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2698                            new ArrayList<String>(domains));
2699                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2700                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2701                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2702                } else {
2703                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2704                            + "' does not handle web links");
2705                }
2706            } else {
2707                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2708            }
2709        }
2710
2711        scheduleWritePackageRestrictionsLocked(userId);
2712        scheduleWriteSettingsLocked();
2713    }
2714
2715    private void applyFactoryDefaultBrowserLPw(int userId) {
2716        // The default browser app's package name is stored in a string resource,
2717        // with a product-specific overlay used for vendor customization.
2718        String browserPkg = mContext.getResources().getString(
2719                com.android.internal.R.string.default_browser);
2720        if (!TextUtils.isEmpty(browserPkg)) {
2721            // non-empty string => required to be a known package
2722            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2723            if (ps == null) {
2724                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2725                browserPkg = null;
2726            } else {
2727                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2728            }
2729        }
2730
2731        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2732        // default.  If there's more than one, just leave everything alone.
2733        if (browserPkg == null) {
2734            calculateDefaultBrowserLPw(userId);
2735        }
2736    }
2737
2738    private void calculateDefaultBrowserLPw(int userId) {
2739        List<String> allBrowsers = resolveAllBrowserApps(userId);
2740        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2741        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2742    }
2743
2744    private List<String> resolveAllBrowserApps(int userId) {
2745        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2746        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2747                PackageManager.MATCH_ALL, userId);
2748
2749        final int count = list.size();
2750        List<String> result = new ArrayList<String>(count);
2751        for (int i=0; i<count; i++) {
2752            ResolveInfo info = list.get(i);
2753            if (info.activityInfo == null
2754                    || !info.handleAllWebDataURI
2755                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2756                    || result.contains(info.activityInfo.packageName)) {
2757                continue;
2758            }
2759            result.add(info.activityInfo.packageName);
2760        }
2761
2762        return result;
2763    }
2764
2765    private boolean packageIsBrowser(String packageName, int userId) {
2766        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2767                PackageManager.MATCH_ALL, userId);
2768        final int N = list.size();
2769        for (int i = 0; i < N; i++) {
2770            ResolveInfo info = list.get(i);
2771            if (packageName.equals(info.activityInfo.packageName)) {
2772                return true;
2773            }
2774        }
2775        return false;
2776    }
2777
2778    private void checkDefaultBrowser() {
2779        final int myUserId = UserHandle.myUserId();
2780        final String packageName = getDefaultBrowserPackageName(myUserId);
2781        if (packageName != null) {
2782            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2783            if (info == null) {
2784                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2785                synchronized (mPackages) {
2786                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2787                }
2788            }
2789        }
2790    }
2791
2792    @Override
2793    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2794            throws RemoteException {
2795        try {
2796            return super.onTransact(code, data, reply, flags);
2797        } catch (RuntimeException e) {
2798            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2799                Slog.wtf(TAG, "Package Manager Crash", e);
2800            }
2801            throw e;
2802        }
2803    }
2804
2805    void cleanupInstallFailedPackage(PackageSetting ps) {
2806        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2807
2808        removeDataDirsLI(ps.volumeUuid, ps.name);
2809        if (ps.codePath != null) {
2810            removeCodePathLI(ps.codePath);
2811        }
2812        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2813            if (ps.resourcePath.isDirectory()) {
2814                FileUtils.deleteContents(ps.resourcePath);
2815            }
2816            ps.resourcePath.delete();
2817        }
2818        mSettings.removePackageLPw(ps.name);
2819    }
2820
2821    static int[] appendInts(int[] cur, int[] add) {
2822        if (add == null) return cur;
2823        if (cur == null) return add;
2824        final int N = add.length;
2825        for (int i=0; i<N; i++) {
2826            cur = appendInt(cur, add[i]);
2827        }
2828        return cur;
2829    }
2830
2831    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2832        if (!sUserManager.exists(userId)) return null;
2833        final PackageSetting ps = (PackageSetting) p.mExtras;
2834        if (ps == null) {
2835            return null;
2836        }
2837
2838        final PermissionsState permissionsState = ps.getPermissionsState();
2839
2840        final int[] gids = permissionsState.computeGids(userId);
2841        final Set<String> permissions = permissionsState.getPermissions(userId);
2842        final PackageUserState state = ps.readUserState(userId);
2843
2844        return PackageParser.generatePackageInfo(p, gids, flags,
2845                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2846    }
2847
2848    @Override
2849    public void checkPackageStartable(String packageName, int userId) {
2850        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2851
2852        synchronized (mPackages) {
2853            final PackageSetting ps = mSettings.mPackages.get(packageName);
2854            if (ps == null) {
2855                throw new SecurityException("Package " + packageName + " was not found!");
2856            }
2857
2858            if (ps.frozen) {
2859                throw new SecurityException("Package " + packageName + " is currently frozen!");
2860            }
2861
2862            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2863                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2864                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2865            }
2866        }
2867    }
2868
2869    @Override
2870    public boolean isPackageAvailable(String packageName, int userId) {
2871        if (!sUserManager.exists(userId)) return false;
2872        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2873        synchronized (mPackages) {
2874            PackageParser.Package p = mPackages.get(packageName);
2875            if (p != null) {
2876                final PackageSetting ps = (PackageSetting) p.mExtras;
2877                if (ps != null) {
2878                    final PackageUserState state = ps.readUserState(userId);
2879                    if (state != null) {
2880                        return PackageParser.isAvailable(state);
2881                    }
2882                }
2883            }
2884        }
2885        return false;
2886    }
2887
2888    @Override
2889    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        flags = updateFlagsForPackage(flags, userId, packageName);
2892        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2893        // reader
2894        synchronized (mPackages) {
2895            PackageParser.Package p = mPackages.get(packageName);
2896            if (DEBUG_PACKAGE_INFO)
2897                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2898            if (p != null) {
2899                return generatePackageInfo(p, flags, userId);
2900            }
2901            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2902                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2903            }
2904        }
2905        return null;
2906    }
2907
2908    @Override
2909    public String[] currentToCanonicalPackageNames(String[] names) {
2910        String[] out = new String[names.length];
2911        // reader
2912        synchronized (mPackages) {
2913            for (int i=names.length-1; i>=0; i--) {
2914                PackageSetting ps = mSettings.mPackages.get(names[i]);
2915                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2916            }
2917        }
2918        return out;
2919    }
2920
2921    @Override
2922    public String[] canonicalToCurrentPackageNames(String[] names) {
2923        String[] out = new String[names.length];
2924        // reader
2925        synchronized (mPackages) {
2926            for (int i=names.length-1; i>=0; i--) {
2927                String cur = mSettings.mRenamedPackages.get(names[i]);
2928                out[i] = cur != null ? cur : names[i];
2929            }
2930        }
2931        return out;
2932    }
2933
2934    @Override
2935    public int getPackageUid(String packageName, int flags, int userId) {
2936        if (!sUserManager.exists(userId)) return -1;
2937        flags = updateFlagsForPackage(flags, userId, packageName);
2938        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2939
2940        // reader
2941        synchronized (mPackages) {
2942            final PackageParser.Package p = mPackages.get(packageName);
2943            if (p != null && p.isMatch(flags)) {
2944                return UserHandle.getUid(userId, p.applicationInfo.uid);
2945            }
2946            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2947                final PackageSetting ps = mSettings.mPackages.get(packageName);
2948                if (ps != null && ps.isMatch(flags)) {
2949                    return UserHandle.getUid(userId, ps.appId);
2950                }
2951            }
2952        }
2953
2954        return -1;
2955    }
2956
2957    @Override
2958    public int[] getPackageGids(String packageName, int flags, int userId) {
2959        if (!sUserManager.exists(userId)) return null;
2960        flags = updateFlagsForPackage(flags, userId, packageName);
2961        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2962                "getPackageGids");
2963
2964        // reader
2965        synchronized (mPackages) {
2966            final PackageParser.Package p = mPackages.get(packageName);
2967            if (p != null && p.isMatch(flags)) {
2968                PackageSetting ps = (PackageSetting) p.mExtras;
2969                return ps.getPermissionsState().computeGids(userId);
2970            }
2971            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2972                final PackageSetting ps = mSettings.mPackages.get(packageName);
2973                if (ps != null && ps.isMatch(flags)) {
2974                    return ps.getPermissionsState().computeGids(userId);
2975                }
2976            }
2977        }
2978
2979        return null;
2980    }
2981
2982    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2983        if (bp.perm != null) {
2984            return PackageParser.generatePermissionInfo(bp.perm, flags);
2985        }
2986        PermissionInfo pi = new PermissionInfo();
2987        pi.name = bp.name;
2988        pi.packageName = bp.sourcePackage;
2989        pi.nonLocalizedLabel = bp.name;
2990        pi.protectionLevel = bp.protectionLevel;
2991        return pi;
2992    }
2993
2994    @Override
2995    public PermissionInfo getPermissionInfo(String name, int flags) {
2996        // reader
2997        synchronized (mPackages) {
2998            final BasePermission p = mSettings.mPermissions.get(name);
2999            if (p != null) {
3000                return generatePermissionInfo(p, flags);
3001            }
3002            return null;
3003        }
3004    }
3005
3006    @Override
3007    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3008        // reader
3009        synchronized (mPackages) {
3010            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3011            for (BasePermission p : mSettings.mPermissions.values()) {
3012                if (group == null) {
3013                    if (p.perm == null || p.perm.info.group == null) {
3014                        out.add(generatePermissionInfo(p, flags));
3015                    }
3016                } else {
3017                    if (p.perm != null && group.equals(p.perm.info.group)) {
3018                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3019                    }
3020                }
3021            }
3022
3023            if (out.size() > 0) {
3024                return out;
3025            }
3026            return mPermissionGroups.containsKey(group) ? out : null;
3027        }
3028    }
3029
3030    @Override
3031    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3032        // reader
3033        synchronized (mPackages) {
3034            return PackageParser.generatePermissionGroupInfo(
3035                    mPermissionGroups.get(name), flags);
3036        }
3037    }
3038
3039    @Override
3040    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3041        // reader
3042        synchronized (mPackages) {
3043            final int N = mPermissionGroups.size();
3044            ArrayList<PermissionGroupInfo> out
3045                    = new ArrayList<PermissionGroupInfo>(N);
3046            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3047                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3048            }
3049            return out;
3050        }
3051    }
3052
3053    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3054            int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        PackageSetting ps = mSettings.mPackages.get(packageName);
3057        if (ps != null) {
3058            if (ps.pkg == null) {
3059                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3060                        flags, userId);
3061                if (pInfo != null) {
3062                    return pInfo.applicationInfo;
3063                }
3064                return null;
3065            }
3066            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3067                    ps.readUserState(userId), userId);
3068        }
3069        return null;
3070    }
3071
3072    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3073            int userId) {
3074        if (!sUserManager.exists(userId)) return null;
3075        PackageSetting ps = mSettings.mPackages.get(packageName);
3076        if (ps != null) {
3077            PackageParser.Package pkg = ps.pkg;
3078            if (pkg == null) {
3079                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3080                    return null;
3081                }
3082                // Only data remains, so we aren't worried about code paths
3083                pkg = new PackageParser.Package(packageName);
3084                pkg.applicationInfo.packageName = packageName;
3085                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3086                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3087                pkg.applicationInfo.uid = ps.appId;
3088                pkg.applicationInfo.initForUser(userId);
3089                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3090                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3091            }
3092            return generatePackageInfo(pkg, flags, userId);
3093        }
3094        return null;
3095    }
3096
3097    @Override
3098    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3099        if (!sUserManager.exists(userId)) return null;
3100        flags = updateFlagsForApplication(flags, userId, packageName);
3101        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3102        // writer
3103        synchronized (mPackages) {
3104            PackageParser.Package p = mPackages.get(packageName);
3105            if (DEBUG_PACKAGE_INFO) Log.v(
3106                    TAG, "getApplicationInfo " + packageName
3107                    + ": " + p);
3108            if (p != null) {
3109                PackageSetting ps = mSettings.mPackages.get(packageName);
3110                if (ps == null) return null;
3111                // Note: isEnabledLP() does not apply here - always return info
3112                return PackageParser.generateApplicationInfo(
3113                        p, flags, ps.readUserState(userId), userId);
3114            }
3115            if ("android".equals(packageName)||"system".equals(packageName)) {
3116                return mAndroidApplication;
3117            }
3118            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3119                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3120            }
3121        }
3122        return null;
3123    }
3124
3125    @Override
3126    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3127            final IPackageDataObserver observer) {
3128        mContext.enforceCallingOrSelfPermission(
3129                android.Manifest.permission.CLEAR_APP_CACHE, null);
3130        // Queue up an async operation since clearing cache may take a little while.
3131        mHandler.post(new Runnable() {
3132            public void run() {
3133                mHandler.removeCallbacks(this);
3134                boolean success = true;
3135                synchronized (mInstallLock) {
3136                    try {
3137                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3138                    } catch (InstallerException e) {
3139                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3140                        success = false;
3141                    }
3142                }
3143                if (observer != null) {
3144                    try {
3145                        observer.onRemoveCompleted(null, success);
3146                    } catch (RemoteException e) {
3147                        Slog.w(TAG, "RemoveException when invoking call back");
3148                    }
3149                }
3150            }
3151        });
3152    }
3153
3154    @Override
3155    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3156            final IntentSender pi) {
3157        mContext.enforceCallingOrSelfPermission(
3158                android.Manifest.permission.CLEAR_APP_CACHE, null);
3159        // Queue up an async operation since clearing cache may take a little while.
3160        mHandler.post(new Runnable() {
3161            public void run() {
3162                mHandler.removeCallbacks(this);
3163                boolean success = true;
3164                synchronized (mInstallLock) {
3165                    try {
3166                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3167                    } catch (InstallerException e) {
3168                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3169                        success = false;
3170                    }
3171                }
3172                if(pi != null) {
3173                    try {
3174                        // Callback via pending intent
3175                        int code = success ? 1 : 0;
3176                        pi.sendIntent(null, code, null,
3177                                null, null);
3178                    } catch (SendIntentException e1) {
3179                        Slog.i(TAG, "Failed to send pending intent");
3180                    }
3181                }
3182            }
3183        });
3184    }
3185
3186    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3187        synchronized (mInstallLock) {
3188            try {
3189                mInstaller.freeCache(volumeUuid, freeStorageSize);
3190            } catch (InstallerException e) {
3191                throw new IOException("Failed to free enough space", e);
3192            }
3193        }
3194    }
3195
3196    /**
3197     * Return if the user key is currently unlocked.
3198     */
3199    private boolean isUserKeyUnlocked(int userId) {
3200        if (StorageManager.isFileBasedEncryptionEnabled()) {
3201            final IMountService mount = IMountService.Stub
3202                    .asInterface(ServiceManager.getService("mount"));
3203            if (mount == null) {
3204                Slog.w(TAG, "Early during boot, assuming locked");
3205                return false;
3206            }
3207            final long token = Binder.clearCallingIdentity();
3208            try {
3209                return mount.isUserKeyUnlocked(userId);
3210            } catch (RemoteException e) {
3211                throw e.rethrowAsRuntimeException();
3212            } finally {
3213                Binder.restoreCallingIdentity(token);
3214            }
3215        } else {
3216            return true;
3217        }
3218    }
3219
3220    /**
3221     * Update given flags based on encryption status of current user.
3222     */
3223    private int updateFlags(int flags, int userId) {
3224        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3225                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3226            // Caller expressed an explicit opinion about what encryption
3227            // aware/unaware components they want to see, so fall through and
3228            // give them what they want
3229        } else {
3230            // Caller expressed no opinion, so match based on user state
3231            if (isUserKeyUnlocked(userId)) {
3232                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3233            } else {
3234                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3235            }
3236        }
3237
3238        // Safe mode means we should ignore any third-party apps
3239        if (mSafeMode) {
3240            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3241        }
3242
3243        return flags;
3244    }
3245
3246    /**
3247     * Update given flags when being used to request {@link PackageInfo}.
3248     */
3249    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3250        boolean triaged = true;
3251        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3252                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3253            // Caller is asking for component details, so they'd better be
3254            // asking for specific encryption matching behavior, or be triaged
3255            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3256                    | PackageManager.MATCH_ENCRYPTION_AWARE
3257                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3258                triaged = false;
3259            }
3260        }
3261        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3262                | PackageManager.MATCH_SYSTEM_ONLY
3263                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3264            triaged = false;
3265        }
3266        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3267            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3268                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3269        }
3270        return updateFlags(flags, userId);
3271    }
3272
3273    /**
3274     * Update given flags when being used to request {@link ApplicationInfo}.
3275     */
3276    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3277        return updateFlagsForPackage(flags, userId, cookie);
3278    }
3279
3280    /**
3281     * Update given flags when being used to request {@link ComponentInfo}.
3282     */
3283    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3284        if (cookie instanceof Intent) {
3285            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3286                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3287            }
3288        }
3289
3290        boolean triaged = true;
3291        // Caller is asking for component details, so they'd better be
3292        // asking for specific encryption matching behavior, or be triaged
3293        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3294                | PackageManager.MATCH_ENCRYPTION_AWARE
3295                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3296            triaged = false;
3297        }
3298        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3299            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3300                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3301        }
3302        return updateFlags(flags, userId);
3303    }
3304
3305    /**
3306     * Update given flags when being used to request {@link ResolveInfo}.
3307     */
3308    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3309        return updateFlagsForComponent(flags, userId, cookie);
3310    }
3311
3312    @Override
3313    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3314        if (!sUserManager.exists(userId)) return null;
3315        flags = updateFlagsForComponent(flags, userId, component);
3316        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3317        synchronized (mPackages) {
3318            PackageParser.Activity a = mActivities.mActivities.get(component);
3319
3320            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3321            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3322                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3323                if (ps == null) return null;
3324                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3325                        userId);
3326            }
3327            if (mResolveComponentName.equals(component)) {
3328                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3329                        new PackageUserState(), userId);
3330            }
3331        }
3332        return null;
3333    }
3334
3335    @Override
3336    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3337            String resolvedType) {
3338        synchronized (mPackages) {
3339            if (component.equals(mResolveComponentName)) {
3340                // The resolver supports EVERYTHING!
3341                return true;
3342            }
3343            PackageParser.Activity a = mActivities.mActivities.get(component);
3344            if (a == null) {
3345                return false;
3346            }
3347            for (int i=0; i<a.intents.size(); i++) {
3348                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3349                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3350                    return true;
3351                }
3352            }
3353            return false;
3354        }
3355    }
3356
3357    @Override
3358    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3359        if (!sUserManager.exists(userId)) return null;
3360        flags = updateFlagsForComponent(flags, userId, component);
3361        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3362        synchronized (mPackages) {
3363            PackageParser.Activity a = mReceivers.mActivities.get(component);
3364            if (DEBUG_PACKAGE_INFO) Log.v(
3365                TAG, "getReceiverInfo " + component + ": " + a);
3366            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3367                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3368                if (ps == null) return null;
3369                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3370                        userId);
3371            }
3372        }
3373        return null;
3374    }
3375
3376    @Override
3377    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3378        if (!sUserManager.exists(userId)) return null;
3379        flags = updateFlagsForComponent(flags, userId, component);
3380        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3381        synchronized (mPackages) {
3382            PackageParser.Service s = mServices.mServices.get(component);
3383            if (DEBUG_PACKAGE_INFO) Log.v(
3384                TAG, "getServiceInfo " + component + ": " + s);
3385            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3386                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3387                if (ps == null) return null;
3388                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3389                        userId);
3390            }
3391        }
3392        return null;
3393    }
3394
3395    @Override
3396    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3397        if (!sUserManager.exists(userId)) return null;
3398        flags = updateFlagsForComponent(flags, userId, component);
3399        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3400        synchronized (mPackages) {
3401            PackageParser.Provider p = mProviders.mProviders.get(component);
3402            if (DEBUG_PACKAGE_INFO) Log.v(
3403                TAG, "getProviderInfo " + component + ": " + p);
3404            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3405                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3406                if (ps == null) return null;
3407                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3408                        userId);
3409            }
3410        }
3411        return null;
3412    }
3413
3414    @Override
3415    public String[] getSystemSharedLibraryNames() {
3416        Set<String> libSet;
3417        synchronized (mPackages) {
3418            libSet = mSharedLibraries.keySet();
3419            int size = libSet.size();
3420            if (size > 0) {
3421                String[] libs = new String[size];
3422                libSet.toArray(libs);
3423                return libs;
3424            }
3425        }
3426        return null;
3427    }
3428
3429    @Override
3430    public FeatureInfo[] getSystemAvailableFeatures() {
3431        Collection<FeatureInfo> featSet;
3432        synchronized (mPackages) {
3433            featSet = mAvailableFeatures.values();
3434            int size = featSet.size();
3435            if (size > 0) {
3436                FeatureInfo[] features = new FeatureInfo[size+1];
3437                featSet.toArray(features);
3438                FeatureInfo fi = new FeatureInfo();
3439                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3440                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3441                features[size] = fi;
3442                return features;
3443            }
3444        }
3445        return null;
3446    }
3447
3448    @Override
3449    public boolean hasSystemFeature(String name) {
3450        synchronized (mPackages) {
3451            return mAvailableFeatures.containsKey(name);
3452        }
3453    }
3454
3455    @Override
3456    public int checkPermission(String permName, String pkgName, int userId) {
3457        if (!sUserManager.exists(userId)) {
3458            return PackageManager.PERMISSION_DENIED;
3459        }
3460
3461        synchronized (mPackages) {
3462            final PackageParser.Package p = mPackages.get(pkgName);
3463            if (p != null && p.mExtras != null) {
3464                final PackageSetting ps = (PackageSetting) p.mExtras;
3465                final PermissionsState permissionsState = ps.getPermissionsState();
3466                if (permissionsState.hasPermission(permName, userId)) {
3467                    return PackageManager.PERMISSION_GRANTED;
3468                }
3469                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3470                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3471                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3472                    return PackageManager.PERMISSION_GRANTED;
3473                }
3474            }
3475        }
3476
3477        return PackageManager.PERMISSION_DENIED;
3478    }
3479
3480    @Override
3481    public int checkUidPermission(String permName, int uid) {
3482        final int userId = UserHandle.getUserId(uid);
3483
3484        if (!sUserManager.exists(userId)) {
3485            return PackageManager.PERMISSION_DENIED;
3486        }
3487
3488        synchronized (mPackages) {
3489            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3490            if (obj != null) {
3491                final SettingBase ps = (SettingBase) obj;
3492                final PermissionsState permissionsState = ps.getPermissionsState();
3493                if (permissionsState.hasPermission(permName, userId)) {
3494                    return PackageManager.PERMISSION_GRANTED;
3495                }
3496                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3497                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3498                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3499                    return PackageManager.PERMISSION_GRANTED;
3500                }
3501            } else {
3502                ArraySet<String> perms = mSystemPermissions.get(uid);
3503                if (perms != null) {
3504                    if (perms.contains(permName)) {
3505                        return PackageManager.PERMISSION_GRANTED;
3506                    }
3507                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3508                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3509                        return PackageManager.PERMISSION_GRANTED;
3510                    }
3511                }
3512            }
3513        }
3514
3515        return PackageManager.PERMISSION_DENIED;
3516    }
3517
3518    @Override
3519    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3520        if (UserHandle.getCallingUserId() != userId) {
3521            mContext.enforceCallingPermission(
3522                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3523                    "isPermissionRevokedByPolicy for user " + userId);
3524        }
3525
3526        if (checkPermission(permission, packageName, userId)
3527                == PackageManager.PERMISSION_GRANTED) {
3528            return false;
3529        }
3530
3531        final long identity = Binder.clearCallingIdentity();
3532        try {
3533            final int flags = getPermissionFlags(permission, packageName, userId);
3534            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3535        } finally {
3536            Binder.restoreCallingIdentity(identity);
3537        }
3538    }
3539
3540    @Override
3541    public String getPermissionControllerPackageName() {
3542        synchronized (mPackages) {
3543            return mRequiredInstallerPackage;
3544        }
3545    }
3546
3547    /**
3548     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3549     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3550     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3551     * @param message the message to log on security exception
3552     */
3553    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3554            boolean checkShell, String message) {
3555        if (userId < 0) {
3556            throw new IllegalArgumentException("Invalid userId " + userId);
3557        }
3558        if (checkShell) {
3559            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3560        }
3561        if (userId == UserHandle.getUserId(callingUid)) return;
3562        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3563            if (requireFullPermission) {
3564                mContext.enforceCallingOrSelfPermission(
3565                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3566            } else {
3567                try {
3568                    mContext.enforceCallingOrSelfPermission(
3569                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3570                } catch (SecurityException se) {
3571                    mContext.enforceCallingOrSelfPermission(
3572                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3573                }
3574            }
3575        }
3576    }
3577
3578    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3579        if (callingUid == Process.SHELL_UID) {
3580            if (userHandle >= 0
3581                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3582                throw new SecurityException("Shell does not have permission to access user "
3583                        + userHandle);
3584            } else if (userHandle < 0) {
3585                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3586                        + Debug.getCallers(3));
3587            }
3588        }
3589    }
3590
3591    private BasePermission findPermissionTreeLP(String permName) {
3592        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3593            if (permName.startsWith(bp.name) &&
3594                    permName.length() > bp.name.length() &&
3595                    permName.charAt(bp.name.length()) == '.') {
3596                return bp;
3597            }
3598        }
3599        return null;
3600    }
3601
3602    private BasePermission checkPermissionTreeLP(String permName) {
3603        if (permName != null) {
3604            BasePermission bp = findPermissionTreeLP(permName);
3605            if (bp != null) {
3606                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3607                    return bp;
3608                }
3609                throw new SecurityException("Calling uid "
3610                        + Binder.getCallingUid()
3611                        + " is not allowed to add to permission tree "
3612                        + bp.name + " owned by uid " + bp.uid);
3613            }
3614        }
3615        throw new SecurityException("No permission tree found for " + permName);
3616    }
3617
3618    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3619        if (s1 == null) {
3620            return s2 == null;
3621        }
3622        if (s2 == null) {
3623            return false;
3624        }
3625        if (s1.getClass() != s2.getClass()) {
3626            return false;
3627        }
3628        return s1.equals(s2);
3629    }
3630
3631    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3632        if (pi1.icon != pi2.icon) return false;
3633        if (pi1.logo != pi2.logo) return false;
3634        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3635        if (!compareStrings(pi1.name, pi2.name)) return false;
3636        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3637        // We'll take care of setting this one.
3638        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3639        // These are not currently stored in settings.
3640        //if (!compareStrings(pi1.group, pi2.group)) return false;
3641        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3642        //if (pi1.labelRes != pi2.labelRes) return false;
3643        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3644        return true;
3645    }
3646
3647    int permissionInfoFootprint(PermissionInfo info) {
3648        int size = info.name.length();
3649        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3650        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3651        return size;
3652    }
3653
3654    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3655        int size = 0;
3656        for (BasePermission perm : mSettings.mPermissions.values()) {
3657            if (perm.uid == tree.uid) {
3658                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3659            }
3660        }
3661        return size;
3662    }
3663
3664    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3665        // We calculate the max size of permissions defined by this uid and throw
3666        // if that plus the size of 'info' would exceed our stated maximum.
3667        if (tree.uid != Process.SYSTEM_UID) {
3668            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3669            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3670                throw new SecurityException("Permission tree size cap exceeded");
3671            }
3672        }
3673    }
3674
3675    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3676        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3677            throw new SecurityException("Label must be specified in permission");
3678        }
3679        BasePermission tree = checkPermissionTreeLP(info.name);
3680        BasePermission bp = mSettings.mPermissions.get(info.name);
3681        boolean added = bp == null;
3682        boolean changed = true;
3683        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3684        if (added) {
3685            enforcePermissionCapLocked(info, tree);
3686            bp = new BasePermission(info.name, tree.sourcePackage,
3687                    BasePermission.TYPE_DYNAMIC);
3688        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3689            throw new SecurityException(
3690                    "Not allowed to modify non-dynamic permission "
3691                    + info.name);
3692        } else {
3693            if (bp.protectionLevel == fixedLevel
3694                    && bp.perm.owner.equals(tree.perm.owner)
3695                    && bp.uid == tree.uid
3696                    && comparePermissionInfos(bp.perm.info, info)) {
3697                changed = false;
3698            }
3699        }
3700        bp.protectionLevel = fixedLevel;
3701        info = new PermissionInfo(info);
3702        info.protectionLevel = fixedLevel;
3703        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3704        bp.perm.info.packageName = tree.perm.info.packageName;
3705        bp.uid = tree.uid;
3706        if (added) {
3707            mSettings.mPermissions.put(info.name, bp);
3708        }
3709        if (changed) {
3710            if (!async) {
3711                mSettings.writeLPr();
3712            } else {
3713                scheduleWriteSettingsLocked();
3714            }
3715        }
3716        return added;
3717    }
3718
3719    @Override
3720    public boolean addPermission(PermissionInfo info) {
3721        synchronized (mPackages) {
3722            return addPermissionLocked(info, false);
3723        }
3724    }
3725
3726    @Override
3727    public boolean addPermissionAsync(PermissionInfo info) {
3728        synchronized (mPackages) {
3729            return addPermissionLocked(info, true);
3730        }
3731    }
3732
3733    @Override
3734    public void removePermission(String name) {
3735        synchronized (mPackages) {
3736            checkPermissionTreeLP(name);
3737            BasePermission bp = mSettings.mPermissions.get(name);
3738            if (bp != null) {
3739                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3740                    throw new SecurityException(
3741                            "Not allowed to modify non-dynamic permission "
3742                            + name);
3743                }
3744                mSettings.mPermissions.remove(name);
3745                mSettings.writeLPr();
3746            }
3747        }
3748    }
3749
3750    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3751            BasePermission bp) {
3752        int index = pkg.requestedPermissions.indexOf(bp.name);
3753        if (index == -1) {
3754            throw new SecurityException("Package " + pkg.packageName
3755                    + " has not requested permission " + bp.name);
3756        }
3757        if (!bp.isRuntime() && !bp.isDevelopment()) {
3758            throw new SecurityException("Permission " + bp.name
3759                    + " is not a changeable permission type");
3760        }
3761    }
3762
3763    @Override
3764    public void grantRuntimePermission(String packageName, String name, final int userId) {
3765        if (!sUserManager.exists(userId)) {
3766            Log.e(TAG, "No such user:" + userId);
3767            return;
3768        }
3769
3770        mContext.enforceCallingOrSelfPermission(
3771                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3772                "grantRuntimePermission");
3773
3774        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3775                "grantRuntimePermission");
3776
3777        final int uid;
3778        final SettingBase sb;
3779
3780        synchronized (mPackages) {
3781            final PackageParser.Package pkg = mPackages.get(packageName);
3782            if (pkg == null) {
3783                throw new IllegalArgumentException("Unknown package: " + packageName);
3784            }
3785
3786            final BasePermission bp = mSettings.mPermissions.get(name);
3787            if (bp == null) {
3788                throw new IllegalArgumentException("Unknown permission: " + name);
3789            }
3790
3791            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3792
3793            // If a permission review is required for legacy apps we represent
3794            // their permissions as always granted runtime ones since we need
3795            // to keep the review required permission flag per user while an
3796            // install permission's state is shared across all users.
3797            if (Build.PERMISSIONS_REVIEW_REQUIRED
3798                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3799                    && bp.isRuntime()) {
3800                return;
3801            }
3802
3803            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3804            sb = (SettingBase) pkg.mExtras;
3805            if (sb == null) {
3806                throw new IllegalArgumentException("Unknown package: " + packageName);
3807            }
3808
3809            final PermissionsState permissionsState = sb.getPermissionsState();
3810
3811            final int flags = permissionsState.getPermissionFlags(name, userId);
3812            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3813                throw new SecurityException("Cannot grant system fixed permission "
3814                        + name + " for package " + packageName);
3815            }
3816
3817            if (bp.isDevelopment()) {
3818                // Development permissions must be handled specially, since they are not
3819                // normal runtime permissions.  For now they apply to all users.
3820                if (permissionsState.grantInstallPermission(bp) !=
3821                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3822                    scheduleWriteSettingsLocked();
3823                }
3824                return;
3825            }
3826
3827            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3828                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3829                return;
3830            }
3831
3832            final int result = permissionsState.grantRuntimePermission(bp, userId);
3833            switch (result) {
3834                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3835                    return;
3836                }
3837
3838                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3839                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3840                    mHandler.post(new Runnable() {
3841                        @Override
3842                        public void run() {
3843                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3844                        }
3845                    });
3846                }
3847                break;
3848            }
3849
3850            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3851
3852            // Not critical if that is lost - app has to request again.
3853            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3854        }
3855
3856        // Only need to do this if user is initialized. Otherwise it's a new user
3857        // and there are no processes running as the user yet and there's no need
3858        // to make an expensive call to remount processes for the changed permissions.
3859        if (READ_EXTERNAL_STORAGE.equals(name)
3860                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3861            final long token = Binder.clearCallingIdentity();
3862            try {
3863                if (sUserManager.isInitialized(userId)) {
3864                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3865                            MountServiceInternal.class);
3866                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3867                }
3868            } finally {
3869                Binder.restoreCallingIdentity(token);
3870            }
3871        }
3872    }
3873
3874    @Override
3875    public void revokeRuntimePermission(String packageName, String name, int userId) {
3876        if (!sUserManager.exists(userId)) {
3877            Log.e(TAG, "No such user:" + userId);
3878            return;
3879        }
3880
3881        mContext.enforceCallingOrSelfPermission(
3882                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3883                "revokeRuntimePermission");
3884
3885        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3886                "revokeRuntimePermission");
3887
3888        final int appId;
3889
3890        synchronized (mPackages) {
3891            final PackageParser.Package pkg = mPackages.get(packageName);
3892            if (pkg == null) {
3893                throw new IllegalArgumentException("Unknown package: " + packageName);
3894            }
3895
3896            final BasePermission bp = mSettings.mPermissions.get(name);
3897            if (bp == null) {
3898                throw new IllegalArgumentException("Unknown permission: " + name);
3899            }
3900
3901            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3902
3903            // If a permission review is required for legacy apps we represent
3904            // their permissions as always granted runtime ones since we need
3905            // to keep the review required permission flag per user while an
3906            // install permission's state is shared across all users.
3907            if (Build.PERMISSIONS_REVIEW_REQUIRED
3908                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3909                    && bp.isRuntime()) {
3910                return;
3911            }
3912
3913            SettingBase sb = (SettingBase) pkg.mExtras;
3914            if (sb == null) {
3915                throw new IllegalArgumentException("Unknown package: " + packageName);
3916            }
3917
3918            final PermissionsState permissionsState = sb.getPermissionsState();
3919
3920            final int flags = permissionsState.getPermissionFlags(name, userId);
3921            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3922                throw new SecurityException("Cannot revoke system fixed permission "
3923                        + name + " for package " + packageName);
3924            }
3925
3926            if (bp.isDevelopment()) {
3927                // Development permissions must be handled specially, since they are not
3928                // normal runtime permissions.  For now they apply to all users.
3929                if (permissionsState.revokeInstallPermission(bp) !=
3930                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3931                    scheduleWriteSettingsLocked();
3932                }
3933                return;
3934            }
3935
3936            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3937                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3938                return;
3939            }
3940
3941            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3942
3943            // Critical, after this call app should never have the permission.
3944            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3945
3946            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3947        }
3948
3949        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3950    }
3951
3952    @Override
3953    public void resetRuntimePermissions() {
3954        mContext.enforceCallingOrSelfPermission(
3955                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3956                "revokeRuntimePermission");
3957
3958        int callingUid = Binder.getCallingUid();
3959        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3960            mContext.enforceCallingOrSelfPermission(
3961                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3962                    "resetRuntimePermissions");
3963        }
3964
3965        synchronized (mPackages) {
3966            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3967            for (int userId : UserManagerService.getInstance().getUserIds()) {
3968                final int packageCount = mPackages.size();
3969                for (int i = 0; i < packageCount; i++) {
3970                    PackageParser.Package pkg = mPackages.valueAt(i);
3971                    if (!(pkg.mExtras instanceof PackageSetting)) {
3972                        continue;
3973                    }
3974                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3975                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3976                }
3977            }
3978        }
3979    }
3980
3981    @Override
3982    public int getPermissionFlags(String name, String packageName, int userId) {
3983        if (!sUserManager.exists(userId)) {
3984            return 0;
3985        }
3986
3987        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3988
3989        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3990                "getPermissionFlags");
3991
3992        synchronized (mPackages) {
3993            final PackageParser.Package pkg = mPackages.get(packageName);
3994            if (pkg == null) {
3995                throw new IllegalArgumentException("Unknown package: " + packageName);
3996            }
3997
3998            final BasePermission bp = mSettings.mPermissions.get(name);
3999            if (bp == null) {
4000                throw new IllegalArgumentException("Unknown permission: " + name);
4001            }
4002
4003            SettingBase sb = (SettingBase) pkg.mExtras;
4004            if (sb == null) {
4005                throw new IllegalArgumentException("Unknown package: " + packageName);
4006            }
4007
4008            PermissionsState permissionsState = sb.getPermissionsState();
4009            return permissionsState.getPermissionFlags(name, userId);
4010        }
4011    }
4012
4013    @Override
4014    public void updatePermissionFlags(String name, String packageName, int flagMask,
4015            int flagValues, int userId) {
4016        if (!sUserManager.exists(userId)) {
4017            return;
4018        }
4019
4020        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4021
4022        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4023                "updatePermissionFlags");
4024
4025        // Only the system can change these flags and nothing else.
4026        if (getCallingUid() != Process.SYSTEM_UID) {
4027            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4028            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4029            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4030            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4031            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4032        }
4033
4034        synchronized (mPackages) {
4035            final PackageParser.Package pkg = mPackages.get(packageName);
4036            if (pkg == null) {
4037                throw new IllegalArgumentException("Unknown package: " + packageName);
4038            }
4039
4040            final BasePermission bp = mSettings.mPermissions.get(name);
4041            if (bp == null) {
4042                throw new IllegalArgumentException("Unknown permission: " + name);
4043            }
4044
4045            SettingBase sb = (SettingBase) pkg.mExtras;
4046            if (sb == null) {
4047                throw new IllegalArgumentException("Unknown package: " + packageName);
4048            }
4049
4050            PermissionsState permissionsState = sb.getPermissionsState();
4051
4052            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4053
4054            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4055                // Install and runtime permissions are stored in different places,
4056                // so figure out what permission changed and persist the change.
4057                if (permissionsState.getInstallPermissionState(name) != null) {
4058                    scheduleWriteSettingsLocked();
4059                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4060                        || hadState) {
4061                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4062                }
4063            }
4064        }
4065    }
4066
4067    /**
4068     * Update the permission flags for all packages and runtime permissions of a user in order
4069     * to allow device or profile owner to remove POLICY_FIXED.
4070     */
4071    @Override
4072    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4073        if (!sUserManager.exists(userId)) {
4074            return;
4075        }
4076
4077        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4078
4079        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4080                "updatePermissionFlagsForAllApps");
4081
4082        // Only the system can change system fixed flags.
4083        if (getCallingUid() != Process.SYSTEM_UID) {
4084            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4085            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4086        }
4087
4088        synchronized (mPackages) {
4089            boolean changed = false;
4090            final int packageCount = mPackages.size();
4091            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4092                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4093                SettingBase sb = (SettingBase) pkg.mExtras;
4094                if (sb == null) {
4095                    continue;
4096                }
4097                PermissionsState permissionsState = sb.getPermissionsState();
4098                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4099                        userId, flagMask, flagValues);
4100            }
4101            if (changed) {
4102                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4103            }
4104        }
4105    }
4106
4107    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4108        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4109                != PackageManager.PERMISSION_GRANTED
4110            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4111                != PackageManager.PERMISSION_GRANTED) {
4112            throw new SecurityException(message + " requires "
4113                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4114                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4115        }
4116    }
4117
4118    @Override
4119    public boolean shouldShowRequestPermissionRationale(String permissionName,
4120            String packageName, int userId) {
4121        if (UserHandle.getCallingUserId() != userId) {
4122            mContext.enforceCallingPermission(
4123                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4124                    "canShowRequestPermissionRationale for user " + userId);
4125        }
4126
4127        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4128        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4129            return false;
4130        }
4131
4132        if (checkPermission(permissionName, packageName, userId)
4133                == PackageManager.PERMISSION_GRANTED) {
4134            return false;
4135        }
4136
4137        final int flags;
4138
4139        final long identity = Binder.clearCallingIdentity();
4140        try {
4141            flags = getPermissionFlags(permissionName,
4142                    packageName, userId);
4143        } finally {
4144            Binder.restoreCallingIdentity(identity);
4145        }
4146
4147        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4148                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4149                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4150
4151        if ((flags & fixedFlags) != 0) {
4152            return false;
4153        }
4154
4155        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4156    }
4157
4158    @Override
4159    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4160        mContext.enforceCallingOrSelfPermission(
4161                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4162                "addOnPermissionsChangeListener");
4163
4164        synchronized (mPackages) {
4165            mOnPermissionChangeListeners.addListenerLocked(listener);
4166        }
4167    }
4168
4169    @Override
4170    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4171        synchronized (mPackages) {
4172            mOnPermissionChangeListeners.removeListenerLocked(listener);
4173        }
4174    }
4175
4176    @Override
4177    public boolean isProtectedBroadcast(String actionName) {
4178        synchronized (mPackages) {
4179            if (mProtectedBroadcasts.contains(actionName)) {
4180                return true;
4181            } else if (actionName != null) {
4182                // TODO: remove these terrible hacks
4183                if (actionName.startsWith("android.net.netmon.lingerExpired")
4184                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4185                    return true;
4186                }
4187            }
4188        }
4189        return false;
4190    }
4191
4192    @Override
4193    public int checkSignatures(String pkg1, String pkg2) {
4194        synchronized (mPackages) {
4195            final PackageParser.Package p1 = mPackages.get(pkg1);
4196            final PackageParser.Package p2 = mPackages.get(pkg2);
4197            if (p1 == null || p1.mExtras == null
4198                    || p2 == null || p2.mExtras == null) {
4199                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4200            }
4201            return compareSignatures(p1.mSignatures, p2.mSignatures);
4202        }
4203    }
4204
4205    @Override
4206    public int checkUidSignatures(int uid1, int uid2) {
4207        // Map to base uids.
4208        uid1 = UserHandle.getAppId(uid1);
4209        uid2 = UserHandle.getAppId(uid2);
4210        // reader
4211        synchronized (mPackages) {
4212            Signature[] s1;
4213            Signature[] s2;
4214            Object obj = mSettings.getUserIdLPr(uid1);
4215            if (obj != null) {
4216                if (obj instanceof SharedUserSetting) {
4217                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4218                } else if (obj instanceof PackageSetting) {
4219                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4220                } else {
4221                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4222                }
4223            } else {
4224                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4225            }
4226            obj = mSettings.getUserIdLPr(uid2);
4227            if (obj != null) {
4228                if (obj instanceof SharedUserSetting) {
4229                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4230                } else if (obj instanceof PackageSetting) {
4231                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4232                } else {
4233                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4234                }
4235            } else {
4236                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4237            }
4238            return compareSignatures(s1, s2);
4239        }
4240    }
4241
4242    private void killUid(int appId, int userId, String reason) {
4243        final long identity = Binder.clearCallingIdentity();
4244        try {
4245            IActivityManager am = ActivityManagerNative.getDefault();
4246            if (am != null) {
4247                try {
4248                    am.killUid(appId, userId, reason);
4249                } catch (RemoteException e) {
4250                    /* ignore - same process */
4251                }
4252            }
4253        } finally {
4254            Binder.restoreCallingIdentity(identity);
4255        }
4256    }
4257
4258    /**
4259     * Compares two sets of signatures. Returns:
4260     * <br />
4261     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4262     * <br />
4263     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4264     * <br />
4265     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4266     * <br />
4267     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4268     * <br />
4269     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4270     */
4271    static int compareSignatures(Signature[] s1, Signature[] s2) {
4272        if (s1 == null) {
4273            return s2 == null
4274                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4275                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4276        }
4277
4278        if (s2 == null) {
4279            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4280        }
4281
4282        if (s1.length != s2.length) {
4283            return PackageManager.SIGNATURE_NO_MATCH;
4284        }
4285
4286        // Since both signature sets are of size 1, we can compare without HashSets.
4287        if (s1.length == 1) {
4288            return s1[0].equals(s2[0]) ?
4289                    PackageManager.SIGNATURE_MATCH :
4290                    PackageManager.SIGNATURE_NO_MATCH;
4291        }
4292
4293        ArraySet<Signature> set1 = new ArraySet<Signature>();
4294        for (Signature sig : s1) {
4295            set1.add(sig);
4296        }
4297        ArraySet<Signature> set2 = new ArraySet<Signature>();
4298        for (Signature sig : s2) {
4299            set2.add(sig);
4300        }
4301        // Make sure s2 contains all signatures in s1.
4302        if (set1.equals(set2)) {
4303            return PackageManager.SIGNATURE_MATCH;
4304        }
4305        return PackageManager.SIGNATURE_NO_MATCH;
4306    }
4307
4308    /**
4309     * If the database version for this type of package (internal storage or
4310     * external storage) is less than the version where package signatures
4311     * were updated, return true.
4312     */
4313    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4314        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4315        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4316    }
4317
4318    /**
4319     * Used for backward compatibility to make sure any packages with
4320     * certificate chains get upgraded to the new style. {@code existingSigs}
4321     * will be in the old format (since they were stored on disk from before the
4322     * system upgrade) and {@code scannedSigs} will be in the newer format.
4323     */
4324    private int compareSignaturesCompat(PackageSignatures existingSigs,
4325            PackageParser.Package scannedPkg) {
4326        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4327            return PackageManager.SIGNATURE_NO_MATCH;
4328        }
4329
4330        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4331        for (Signature sig : existingSigs.mSignatures) {
4332            existingSet.add(sig);
4333        }
4334        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4335        for (Signature sig : scannedPkg.mSignatures) {
4336            try {
4337                Signature[] chainSignatures = sig.getChainSignatures();
4338                for (Signature chainSig : chainSignatures) {
4339                    scannedCompatSet.add(chainSig);
4340                }
4341            } catch (CertificateEncodingException e) {
4342                scannedCompatSet.add(sig);
4343            }
4344        }
4345        /*
4346         * Make sure the expanded scanned set contains all signatures in the
4347         * existing one.
4348         */
4349        if (scannedCompatSet.equals(existingSet)) {
4350            // Migrate the old signatures to the new scheme.
4351            existingSigs.assignSignatures(scannedPkg.mSignatures);
4352            // The new KeySets will be re-added later in the scanning process.
4353            synchronized (mPackages) {
4354                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4355            }
4356            return PackageManager.SIGNATURE_MATCH;
4357        }
4358        return PackageManager.SIGNATURE_NO_MATCH;
4359    }
4360
4361    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4362        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4363        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4364    }
4365
4366    private int compareSignaturesRecover(PackageSignatures existingSigs,
4367            PackageParser.Package scannedPkg) {
4368        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4369            return PackageManager.SIGNATURE_NO_MATCH;
4370        }
4371
4372        String msg = null;
4373        try {
4374            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4375                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4376                        + scannedPkg.packageName);
4377                return PackageManager.SIGNATURE_MATCH;
4378            }
4379        } catch (CertificateException e) {
4380            msg = e.getMessage();
4381        }
4382
4383        logCriticalInfo(Log.INFO,
4384                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4385        return PackageManager.SIGNATURE_NO_MATCH;
4386    }
4387
4388    @Override
4389    public String[] getPackagesForUid(int uid) {
4390        uid = UserHandle.getAppId(uid);
4391        // reader
4392        synchronized (mPackages) {
4393            Object obj = mSettings.getUserIdLPr(uid);
4394            if (obj instanceof SharedUserSetting) {
4395                final SharedUserSetting sus = (SharedUserSetting) obj;
4396                final int N = sus.packages.size();
4397                final String[] res = new String[N];
4398                final Iterator<PackageSetting> it = sus.packages.iterator();
4399                int i = 0;
4400                while (it.hasNext()) {
4401                    res[i++] = it.next().name;
4402                }
4403                return res;
4404            } else if (obj instanceof PackageSetting) {
4405                final PackageSetting ps = (PackageSetting) obj;
4406                return new String[] { ps.name };
4407            }
4408        }
4409        return null;
4410    }
4411
4412    @Override
4413    public String getNameForUid(int uid) {
4414        // reader
4415        synchronized (mPackages) {
4416            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4417            if (obj instanceof SharedUserSetting) {
4418                final SharedUserSetting sus = (SharedUserSetting) obj;
4419                return sus.name + ":" + sus.userId;
4420            } else if (obj instanceof PackageSetting) {
4421                final PackageSetting ps = (PackageSetting) obj;
4422                return ps.name;
4423            }
4424        }
4425        return null;
4426    }
4427
4428    @Override
4429    public int getUidForSharedUser(String sharedUserName) {
4430        if(sharedUserName == null) {
4431            return -1;
4432        }
4433        // reader
4434        synchronized (mPackages) {
4435            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4436            if (suid == null) {
4437                return -1;
4438            }
4439            return suid.userId;
4440        }
4441    }
4442
4443    @Override
4444    public int getFlagsForUid(int uid) {
4445        synchronized (mPackages) {
4446            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4447            if (obj instanceof SharedUserSetting) {
4448                final SharedUserSetting sus = (SharedUserSetting) obj;
4449                return sus.pkgFlags;
4450            } else if (obj instanceof PackageSetting) {
4451                final PackageSetting ps = (PackageSetting) obj;
4452                return ps.pkgFlags;
4453            }
4454        }
4455        return 0;
4456    }
4457
4458    @Override
4459    public int getPrivateFlagsForUid(int uid) {
4460        synchronized (mPackages) {
4461            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4462            if (obj instanceof SharedUserSetting) {
4463                final SharedUserSetting sus = (SharedUserSetting) obj;
4464                return sus.pkgPrivateFlags;
4465            } else if (obj instanceof PackageSetting) {
4466                final PackageSetting ps = (PackageSetting) obj;
4467                return ps.pkgPrivateFlags;
4468            }
4469        }
4470        return 0;
4471    }
4472
4473    @Override
4474    public boolean isUidPrivileged(int uid) {
4475        uid = UserHandle.getAppId(uid);
4476        // reader
4477        synchronized (mPackages) {
4478            Object obj = mSettings.getUserIdLPr(uid);
4479            if (obj instanceof SharedUserSetting) {
4480                final SharedUserSetting sus = (SharedUserSetting) obj;
4481                final Iterator<PackageSetting> it = sus.packages.iterator();
4482                while (it.hasNext()) {
4483                    if (it.next().isPrivileged()) {
4484                        return true;
4485                    }
4486                }
4487            } else if (obj instanceof PackageSetting) {
4488                final PackageSetting ps = (PackageSetting) obj;
4489                return ps.isPrivileged();
4490            }
4491        }
4492        return false;
4493    }
4494
4495    @Override
4496    public String[] getAppOpPermissionPackages(String permissionName) {
4497        synchronized (mPackages) {
4498            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4499            if (pkgs == null) {
4500                return null;
4501            }
4502            return pkgs.toArray(new String[pkgs.size()]);
4503        }
4504    }
4505
4506    @Override
4507    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4508            int flags, int userId) {
4509        if (!sUserManager.exists(userId)) return null;
4510        flags = updateFlagsForResolve(flags, userId, intent);
4511        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4512        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4513        final ResolveInfo bestChoice =
4514                chooseBestActivity(intent, resolvedType, flags, query, userId);
4515
4516        if (isEphemeralAllowed(intent, query, userId)) {
4517            final EphemeralResolveInfo ai =
4518                    getEphemeralResolveInfo(intent, resolvedType, userId);
4519            if (ai != null) {
4520                if (DEBUG_EPHEMERAL) {
4521                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4522                }
4523                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4524                bestChoice.ephemeralResolveInfo = ai;
4525            }
4526        }
4527        return bestChoice;
4528    }
4529
4530    @Override
4531    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4532            IntentFilter filter, int match, ComponentName activity) {
4533        final int userId = UserHandle.getCallingUserId();
4534        if (DEBUG_PREFERRED) {
4535            Log.v(TAG, "setLastChosenActivity intent=" + intent
4536                + " resolvedType=" + resolvedType
4537                + " flags=" + flags
4538                + " filter=" + filter
4539                + " match=" + match
4540                + " activity=" + activity);
4541            filter.dump(new PrintStreamPrinter(System.out), "    ");
4542        }
4543        intent.setComponent(null);
4544        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4545        // Find any earlier preferred or last chosen entries and nuke them
4546        findPreferredActivity(intent, resolvedType,
4547                flags, query, 0, false, true, false, userId);
4548        // Add the new activity as the last chosen for this filter
4549        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4550                "Setting last chosen");
4551    }
4552
4553    @Override
4554    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4555        final int userId = UserHandle.getCallingUserId();
4556        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4557        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4558        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4559                false, false, false, userId);
4560    }
4561
4562
4563    private boolean isEphemeralAllowed(
4564            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4565        // Short circuit and return early if possible.
4566        if (DISABLE_EPHEMERAL_APPS) {
4567            return false;
4568        }
4569        final int callingUser = UserHandle.getCallingUserId();
4570        if (callingUser != UserHandle.USER_SYSTEM) {
4571            return false;
4572        }
4573        if (mEphemeralResolverConnection == null) {
4574            return false;
4575        }
4576        if (intent.getComponent() != null) {
4577            return false;
4578        }
4579        if (intent.getPackage() != null) {
4580            return false;
4581        }
4582        final boolean isWebUri = hasWebURI(intent);
4583        if (!isWebUri) {
4584            return false;
4585        }
4586        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4587        synchronized (mPackages) {
4588            final int count = resolvedActivites.size();
4589            for (int n = 0; n < count; n++) {
4590                ResolveInfo info = resolvedActivites.get(n);
4591                String packageName = info.activityInfo.packageName;
4592                PackageSetting ps = mSettings.mPackages.get(packageName);
4593                if (ps != null) {
4594                    // Try to get the status from User settings first
4595                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4596                    int status = (int) (packedStatus >> 32);
4597                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4598                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4599                        if (DEBUG_EPHEMERAL) {
4600                            Slog.v(TAG, "DENY ephemeral apps;"
4601                                + " pkg: " + packageName + ", status: " + status);
4602                        }
4603                        return false;
4604                    }
4605                }
4606            }
4607        }
4608        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4609        return true;
4610    }
4611
4612    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4613            int userId) {
4614        MessageDigest digest = null;
4615        try {
4616            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4617        } catch (NoSuchAlgorithmException e) {
4618            // If we can't create a digest, ignore ephemeral apps.
4619            return null;
4620        }
4621
4622        final byte[] hostBytes = intent.getData().getHost().getBytes();
4623        final byte[] digestBytes = digest.digest(hostBytes);
4624        int shaPrefix =
4625                digestBytes[0] << 24
4626                | digestBytes[1] << 16
4627                | digestBytes[2] << 8
4628                | digestBytes[3] << 0;
4629        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4630                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4631        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4632            // No hash prefix match; there are no ephemeral apps for this domain.
4633            return null;
4634        }
4635        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4636            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4637            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4638                continue;
4639            }
4640            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4641            // No filters; this should never happen.
4642            if (filters.isEmpty()) {
4643                continue;
4644            }
4645            // We have a domain match; resolve the filters to see if anything matches.
4646            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4647            for (int j = filters.size() - 1; j >= 0; --j) {
4648                final EphemeralResolveIntentInfo intentInfo =
4649                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4650                ephemeralResolver.addFilter(intentInfo);
4651            }
4652            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4653                    intent, resolvedType, false /*defaultOnly*/, userId);
4654            if (!matchedResolveInfoList.isEmpty()) {
4655                return matchedResolveInfoList.get(0);
4656            }
4657        }
4658        // Hash or filter mis-match; no ephemeral apps for this domain.
4659        return null;
4660    }
4661
4662    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4663            int flags, List<ResolveInfo> query, int userId) {
4664        if (query != null) {
4665            final int N = query.size();
4666            if (N == 1) {
4667                return query.get(0);
4668            } else if (N > 1) {
4669                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4670                // If there is more than one activity with the same priority,
4671                // then let the user decide between them.
4672                ResolveInfo r0 = query.get(0);
4673                ResolveInfo r1 = query.get(1);
4674                if (DEBUG_INTENT_MATCHING || debug) {
4675                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4676                            + r1.activityInfo.name + "=" + r1.priority);
4677                }
4678                // If the first activity has a higher priority, or a different
4679                // default, then it is always desirable to pick it.
4680                if (r0.priority != r1.priority
4681                        || r0.preferredOrder != r1.preferredOrder
4682                        || r0.isDefault != r1.isDefault) {
4683                    return query.get(0);
4684                }
4685                // If we have saved a preference for a preferred activity for
4686                // this Intent, use that.
4687                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4688                        flags, query, r0.priority, true, false, debug, userId);
4689                if (ri != null) {
4690                    return ri;
4691                }
4692                ri = new ResolveInfo(mResolveInfo);
4693                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4694                ri.activityInfo.applicationInfo = new ApplicationInfo(
4695                        ri.activityInfo.applicationInfo);
4696                if (userId != 0) {
4697                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4698                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4699                }
4700                // Make sure that the resolver is displayable in car mode
4701                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4702                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4703                return ri;
4704            }
4705        }
4706        return null;
4707    }
4708
4709    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4710            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4711        final int N = query.size();
4712        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4713                .get(userId);
4714        // Get the list of persistent preferred activities that handle the intent
4715        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4716        List<PersistentPreferredActivity> pprefs = ppir != null
4717                ? ppir.queryIntent(intent, resolvedType,
4718                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4719                : null;
4720        if (pprefs != null && pprefs.size() > 0) {
4721            final int M = pprefs.size();
4722            for (int i=0; i<M; i++) {
4723                final PersistentPreferredActivity ppa = pprefs.get(i);
4724                if (DEBUG_PREFERRED || debug) {
4725                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4726                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4727                            + "\n  component=" + ppa.mComponent);
4728                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4729                }
4730                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4731                        flags | MATCH_DISABLED_COMPONENTS, userId);
4732                if (DEBUG_PREFERRED || debug) {
4733                    Slog.v(TAG, "Found persistent preferred activity:");
4734                    if (ai != null) {
4735                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4736                    } else {
4737                        Slog.v(TAG, "  null");
4738                    }
4739                }
4740                if (ai == null) {
4741                    // This previously registered persistent preferred activity
4742                    // component is no longer known. Ignore it and do NOT remove it.
4743                    continue;
4744                }
4745                for (int j=0; j<N; j++) {
4746                    final ResolveInfo ri = query.get(j);
4747                    if (!ri.activityInfo.applicationInfo.packageName
4748                            .equals(ai.applicationInfo.packageName)) {
4749                        continue;
4750                    }
4751                    if (!ri.activityInfo.name.equals(ai.name)) {
4752                        continue;
4753                    }
4754                    //  Found a persistent preference that can handle the intent.
4755                    if (DEBUG_PREFERRED || debug) {
4756                        Slog.v(TAG, "Returning persistent preferred activity: " +
4757                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4758                    }
4759                    return ri;
4760                }
4761            }
4762        }
4763        return null;
4764    }
4765
4766    // TODO: handle preferred activities missing while user has amnesia
4767    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4768            List<ResolveInfo> query, int priority, boolean always,
4769            boolean removeMatches, boolean debug, int userId) {
4770        if (!sUserManager.exists(userId)) return null;
4771        flags = updateFlagsForResolve(flags, userId, intent);
4772        // writer
4773        synchronized (mPackages) {
4774            if (intent.getSelector() != null) {
4775                intent = intent.getSelector();
4776            }
4777            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4778
4779            // Try to find a matching persistent preferred activity.
4780            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4781                    debug, userId);
4782
4783            // If a persistent preferred activity matched, use it.
4784            if (pri != null) {
4785                return pri;
4786            }
4787
4788            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4789            // Get the list of preferred activities that handle the intent
4790            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4791            List<PreferredActivity> prefs = pir != null
4792                    ? pir.queryIntent(intent, resolvedType,
4793                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4794                    : null;
4795            if (prefs != null && prefs.size() > 0) {
4796                boolean changed = false;
4797                try {
4798                    // First figure out how good the original match set is.
4799                    // We will only allow preferred activities that came
4800                    // from the same match quality.
4801                    int match = 0;
4802
4803                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4804
4805                    final int N = query.size();
4806                    for (int j=0; j<N; j++) {
4807                        final ResolveInfo ri = query.get(j);
4808                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4809                                + ": 0x" + Integer.toHexString(match));
4810                        if (ri.match > match) {
4811                            match = ri.match;
4812                        }
4813                    }
4814
4815                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4816                            + Integer.toHexString(match));
4817
4818                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4819                    final int M = prefs.size();
4820                    for (int i=0; i<M; i++) {
4821                        final PreferredActivity pa = prefs.get(i);
4822                        if (DEBUG_PREFERRED || debug) {
4823                            Slog.v(TAG, "Checking PreferredActivity ds="
4824                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4825                                    + "\n  component=" + pa.mPref.mComponent);
4826                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4827                        }
4828                        if (pa.mPref.mMatch != match) {
4829                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4830                                    + Integer.toHexString(pa.mPref.mMatch));
4831                            continue;
4832                        }
4833                        // If it's not an "always" type preferred activity and that's what we're
4834                        // looking for, skip it.
4835                        if (always && !pa.mPref.mAlways) {
4836                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4837                            continue;
4838                        }
4839                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4840                                flags | MATCH_DISABLED_COMPONENTS, userId);
4841                        if (DEBUG_PREFERRED || debug) {
4842                            Slog.v(TAG, "Found preferred activity:");
4843                            if (ai != null) {
4844                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4845                            } else {
4846                                Slog.v(TAG, "  null");
4847                            }
4848                        }
4849                        if (ai == null) {
4850                            // This previously registered preferred activity
4851                            // component is no longer known.  Most likely an update
4852                            // to the app was installed and in the new version this
4853                            // component no longer exists.  Clean it up by removing
4854                            // it from the preferred activities list, and skip it.
4855                            Slog.w(TAG, "Removing dangling preferred activity: "
4856                                    + pa.mPref.mComponent);
4857                            pir.removeFilter(pa);
4858                            changed = true;
4859                            continue;
4860                        }
4861                        for (int j=0; j<N; j++) {
4862                            final ResolveInfo ri = query.get(j);
4863                            if (!ri.activityInfo.applicationInfo.packageName
4864                                    .equals(ai.applicationInfo.packageName)) {
4865                                continue;
4866                            }
4867                            if (!ri.activityInfo.name.equals(ai.name)) {
4868                                continue;
4869                            }
4870
4871                            if (removeMatches) {
4872                                pir.removeFilter(pa);
4873                                changed = true;
4874                                if (DEBUG_PREFERRED) {
4875                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4876                                }
4877                                break;
4878                            }
4879
4880                            // Okay we found a previously set preferred or last chosen app.
4881                            // If the result set is different from when this
4882                            // was created, we need to clear it and re-ask the
4883                            // user their preference, if we're looking for an "always" type entry.
4884                            if (always && !pa.mPref.sameSet(query)) {
4885                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4886                                        + intent + " type " + resolvedType);
4887                                if (DEBUG_PREFERRED) {
4888                                    Slog.v(TAG, "Removing preferred activity since set changed "
4889                                            + pa.mPref.mComponent);
4890                                }
4891                                pir.removeFilter(pa);
4892                                // Re-add the filter as a "last chosen" entry (!always)
4893                                PreferredActivity lastChosen = new PreferredActivity(
4894                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4895                                pir.addFilter(lastChosen);
4896                                changed = true;
4897                                return null;
4898                            }
4899
4900                            // Yay! Either the set matched or we're looking for the last chosen
4901                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4902                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4903                            return ri;
4904                        }
4905                    }
4906                } finally {
4907                    if (changed) {
4908                        if (DEBUG_PREFERRED) {
4909                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4910                        }
4911                        scheduleWritePackageRestrictionsLocked(userId);
4912                    }
4913                }
4914            }
4915        }
4916        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4917        return null;
4918    }
4919
4920    /*
4921     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4922     */
4923    @Override
4924    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4925            int targetUserId) {
4926        mContext.enforceCallingOrSelfPermission(
4927                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4928        List<CrossProfileIntentFilter> matches =
4929                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4930        if (matches != null) {
4931            int size = matches.size();
4932            for (int i = 0; i < size; i++) {
4933                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4934            }
4935        }
4936        if (hasWebURI(intent)) {
4937            // cross-profile app linking works only towards the parent.
4938            final UserInfo parent = getProfileParent(sourceUserId);
4939            synchronized(mPackages) {
4940                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4941                        intent, resolvedType, 0, sourceUserId, parent.id);
4942                return xpDomainInfo != null;
4943            }
4944        }
4945        return false;
4946    }
4947
4948    private UserInfo getProfileParent(int userId) {
4949        final long identity = Binder.clearCallingIdentity();
4950        try {
4951            return sUserManager.getProfileParent(userId);
4952        } finally {
4953            Binder.restoreCallingIdentity(identity);
4954        }
4955    }
4956
4957    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4958            String resolvedType, int userId) {
4959        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4960        if (resolver != null) {
4961            return resolver.queryIntent(intent, resolvedType, false, userId);
4962        }
4963        return null;
4964    }
4965
4966    @Override
4967    public List<ResolveInfo> queryIntentActivities(Intent intent,
4968            String resolvedType, int flags, int userId) {
4969        if (!sUserManager.exists(userId)) return Collections.emptyList();
4970        flags = updateFlagsForResolve(flags, userId, intent);
4971        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4972        ComponentName comp = intent.getComponent();
4973        if (comp == null) {
4974            if (intent.getSelector() != null) {
4975                intent = intent.getSelector();
4976                comp = intent.getComponent();
4977            }
4978        }
4979
4980        if (comp != null) {
4981            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4982            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4983            if (ai != null) {
4984                final ResolveInfo ri = new ResolveInfo();
4985                ri.activityInfo = ai;
4986                list.add(ri);
4987            }
4988            return list;
4989        }
4990
4991        // reader
4992        synchronized (mPackages) {
4993            final String pkgName = intent.getPackage();
4994            if (pkgName == null) {
4995                List<CrossProfileIntentFilter> matchingFilters =
4996                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4997                // Check for results that need to skip the current profile.
4998                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4999                        resolvedType, flags, userId);
5000                if (xpResolveInfo != null) {
5001                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5002                    result.add(xpResolveInfo);
5003                    return filterIfNotSystemUser(result, userId);
5004                }
5005
5006                // Check for results in the current profile.
5007                List<ResolveInfo> result = mActivities.queryIntent(
5008                        intent, resolvedType, flags, userId);
5009                result = filterIfNotSystemUser(result, userId);
5010
5011                // Check for cross profile results.
5012                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5013                xpResolveInfo = queryCrossProfileIntents(
5014                        matchingFilters, intent, resolvedType, flags, userId,
5015                        hasNonNegativePriorityResult);
5016                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5017                    boolean isVisibleToUser = filterIfNotSystemUser(
5018                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5019                    if (isVisibleToUser) {
5020                        result.add(xpResolveInfo);
5021                        Collections.sort(result, mResolvePrioritySorter);
5022                    }
5023                }
5024                if (hasWebURI(intent)) {
5025                    CrossProfileDomainInfo xpDomainInfo = null;
5026                    final UserInfo parent = getProfileParent(userId);
5027                    if (parent != null) {
5028                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5029                                flags, userId, parent.id);
5030                    }
5031                    if (xpDomainInfo != null) {
5032                        if (xpResolveInfo != null) {
5033                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5034                            // in the result.
5035                            result.remove(xpResolveInfo);
5036                        }
5037                        if (result.size() == 0) {
5038                            result.add(xpDomainInfo.resolveInfo);
5039                            return result;
5040                        }
5041                    } else if (result.size() <= 1) {
5042                        return result;
5043                    }
5044                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5045                            xpDomainInfo, userId);
5046                    Collections.sort(result, mResolvePrioritySorter);
5047                }
5048                return result;
5049            }
5050            final PackageParser.Package pkg = mPackages.get(pkgName);
5051            if (pkg != null) {
5052                return filterIfNotSystemUser(
5053                        mActivities.queryIntentForPackage(
5054                                intent, resolvedType, flags, pkg.activities, userId),
5055                        userId);
5056            }
5057            return new ArrayList<ResolveInfo>();
5058        }
5059    }
5060
5061    private static class CrossProfileDomainInfo {
5062        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5063        ResolveInfo resolveInfo;
5064        /* Best domain verification status of the activities found in the other profile */
5065        int bestDomainVerificationStatus;
5066    }
5067
5068    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5069            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5070        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5071                sourceUserId)) {
5072            return null;
5073        }
5074        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5075                resolvedType, flags, parentUserId);
5076
5077        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5078            return null;
5079        }
5080        CrossProfileDomainInfo result = null;
5081        int size = resultTargetUser.size();
5082        for (int i = 0; i < size; i++) {
5083            ResolveInfo riTargetUser = resultTargetUser.get(i);
5084            // Intent filter verification is only for filters that specify a host. So don't return
5085            // those that handle all web uris.
5086            if (riTargetUser.handleAllWebDataURI) {
5087                continue;
5088            }
5089            String packageName = riTargetUser.activityInfo.packageName;
5090            PackageSetting ps = mSettings.mPackages.get(packageName);
5091            if (ps == null) {
5092                continue;
5093            }
5094            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5095            int status = (int)(verificationState >> 32);
5096            if (result == null) {
5097                result = new CrossProfileDomainInfo();
5098                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5099                        sourceUserId, parentUserId);
5100                result.bestDomainVerificationStatus = status;
5101            } else {
5102                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5103                        result.bestDomainVerificationStatus);
5104            }
5105        }
5106        // Don't consider matches with status NEVER across profiles.
5107        if (result != null && result.bestDomainVerificationStatus
5108                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5109            return null;
5110        }
5111        return result;
5112    }
5113
5114    /**
5115     * Verification statuses are ordered from the worse to the best, except for
5116     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5117     */
5118    private int bestDomainVerificationStatus(int status1, int status2) {
5119        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5120            return status2;
5121        }
5122        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5123            return status1;
5124        }
5125        return (int) MathUtils.max(status1, status2);
5126    }
5127
5128    private boolean isUserEnabled(int userId) {
5129        long callingId = Binder.clearCallingIdentity();
5130        try {
5131            UserInfo userInfo = sUserManager.getUserInfo(userId);
5132            return userInfo != null && userInfo.isEnabled();
5133        } finally {
5134            Binder.restoreCallingIdentity(callingId);
5135        }
5136    }
5137
5138    /**
5139     * Filter out activities with systemUserOnly flag set, when current user is not System.
5140     *
5141     * @return filtered list
5142     */
5143    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5144        if (userId == UserHandle.USER_SYSTEM) {
5145            return resolveInfos;
5146        }
5147        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5148            ResolveInfo info = resolveInfos.get(i);
5149            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5150                resolveInfos.remove(i);
5151            }
5152        }
5153        return resolveInfos;
5154    }
5155
5156    /**
5157     * @param resolveInfos list of resolve infos in descending priority order
5158     * @return if the list contains a resolve info with non-negative priority
5159     */
5160    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5161        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5162    }
5163
5164    private static boolean hasWebURI(Intent intent) {
5165        if (intent.getData() == null) {
5166            return false;
5167        }
5168        final String scheme = intent.getScheme();
5169        if (TextUtils.isEmpty(scheme)) {
5170            return false;
5171        }
5172        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5173    }
5174
5175    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5176            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5177            int userId) {
5178        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5179
5180        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5181            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5182                    candidates.size());
5183        }
5184
5185        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5186        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5187        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5188        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5189        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5190        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5191
5192        synchronized (mPackages) {
5193            final int count = candidates.size();
5194            // First, try to use linked apps. Partition the candidates into four lists:
5195            // one for the final results, one for the "do not use ever", one for "undefined status"
5196            // and finally one for "browser app type".
5197            for (int n=0; n<count; n++) {
5198                ResolveInfo info = candidates.get(n);
5199                String packageName = info.activityInfo.packageName;
5200                PackageSetting ps = mSettings.mPackages.get(packageName);
5201                if (ps != null) {
5202                    // Add to the special match all list (Browser use case)
5203                    if (info.handleAllWebDataURI) {
5204                        matchAllList.add(info);
5205                        continue;
5206                    }
5207                    // Try to get the status from User settings first
5208                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5209                    int status = (int)(packedStatus >> 32);
5210                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5211                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5212                        if (DEBUG_DOMAIN_VERIFICATION) {
5213                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5214                                    + " : linkgen=" + linkGeneration);
5215                        }
5216                        // Use link-enabled generation as preferredOrder, i.e.
5217                        // prefer newly-enabled over earlier-enabled.
5218                        info.preferredOrder = linkGeneration;
5219                        alwaysList.add(info);
5220                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5221                        if (DEBUG_DOMAIN_VERIFICATION) {
5222                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5223                        }
5224                        neverList.add(info);
5225                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5226                        if (DEBUG_DOMAIN_VERIFICATION) {
5227                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5228                        }
5229                        alwaysAskList.add(info);
5230                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5231                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5232                        if (DEBUG_DOMAIN_VERIFICATION) {
5233                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5234                        }
5235                        undefinedList.add(info);
5236                    }
5237                }
5238            }
5239
5240            // We'll want to include browser possibilities in a few cases
5241            boolean includeBrowser = false;
5242
5243            // First try to add the "always" resolution(s) for the current user, if any
5244            if (alwaysList.size() > 0) {
5245                result.addAll(alwaysList);
5246            } else {
5247                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5248                result.addAll(undefinedList);
5249                // Maybe add one for the other profile.
5250                if (xpDomainInfo != null && (
5251                        xpDomainInfo.bestDomainVerificationStatus
5252                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5253                    result.add(xpDomainInfo.resolveInfo);
5254                }
5255                includeBrowser = true;
5256            }
5257
5258            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5259            // If there were 'always' entries their preferred order has been set, so we also
5260            // back that off to make the alternatives equivalent
5261            if (alwaysAskList.size() > 0) {
5262                for (ResolveInfo i : result) {
5263                    i.preferredOrder = 0;
5264                }
5265                result.addAll(alwaysAskList);
5266                includeBrowser = true;
5267            }
5268
5269            if (includeBrowser) {
5270                // Also add browsers (all of them or only the default one)
5271                if (DEBUG_DOMAIN_VERIFICATION) {
5272                    Slog.v(TAG, "   ...including browsers in candidate set");
5273                }
5274                if ((matchFlags & MATCH_ALL) != 0) {
5275                    result.addAll(matchAllList);
5276                } else {
5277                    // Browser/generic handling case.  If there's a default browser, go straight
5278                    // to that (but only if there is no other higher-priority match).
5279                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5280                    int maxMatchPrio = 0;
5281                    ResolveInfo defaultBrowserMatch = null;
5282                    final int numCandidates = matchAllList.size();
5283                    for (int n = 0; n < numCandidates; n++) {
5284                        ResolveInfo info = matchAllList.get(n);
5285                        // track the highest overall match priority...
5286                        if (info.priority > maxMatchPrio) {
5287                            maxMatchPrio = info.priority;
5288                        }
5289                        // ...and the highest-priority default browser match
5290                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5291                            if (defaultBrowserMatch == null
5292                                    || (defaultBrowserMatch.priority < info.priority)) {
5293                                if (debug) {
5294                                    Slog.v(TAG, "Considering default browser match " + info);
5295                                }
5296                                defaultBrowserMatch = info;
5297                            }
5298                        }
5299                    }
5300                    if (defaultBrowserMatch != null
5301                            && defaultBrowserMatch.priority >= maxMatchPrio
5302                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5303                    {
5304                        if (debug) {
5305                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5306                        }
5307                        result.add(defaultBrowserMatch);
5308                    } else {
5309                        result.addAll(matchAllList);
5310                    }
5311                }
5312
5313                // If there is nothing selected, add all candidates and remove the ones that the user
5314                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5315                if (result.size() == 0) {
5316                    result.addAll(candidates);
5317                    result.removeAll(neverList);
5318                }
5319            }
5320        }
5321        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5322            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5323                    result.size());
5324            for (ResolveInfo info : result) {
5325                Slog.v(TAG, "  + " + info.activityInfo);
5326            }
5327        }
5328        return result;
5329    }
5330
5331    // Returns a packed value as a long:
5332    //
5333    // high 'int'-sized word: link status: undefined/ask/never/always.
5334    // low 'int'-sized word: relative priority among 'always' results.
5335    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5336        long result = ps.getDomainVerificationStatusForUser(userId);
5337        // if none available, get the master status
5338        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5339            if (ps.getIntentFilterVerificationInfo() != null) {
5340                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5341            }
5342        }
5343        return result;
5344    }
5345
5346    private ResolveInfo querySkipCurrentProfileIntents(
5347            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5348            int flags, int sourceUserId) {
5349        if (matchingFilters != null) {
5350            int size = matchingFilters.size();
5351            for (int i = 0; i < size; i ++) {
5352                CrossProfileIntentFilter filter = matchingFilters.get(i);
5353                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5354                    // Checking if there are activities in the target user that can handle the
5355                    // intent.
5356                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5357                            resolvedType, flags, sourceUserId);
5358                    if (resolveInfo != null) {
5359                        return resolveInfo;
5360                    }
5361                }
5362            }
5363        }
5364        return null;
5365    }
5366
5367    // Return matching ResolveInfo in target user if any.
5368    private ResolveInfo queryCrossProfileIntents(
5369            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5370            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5371        if (matchingFilters != null) {
5372            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5373            // match the same intent. For performance reasons, it is better not to
5374            // run queryIntent twice for the same userId
5375            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5376            int size = matchingFilters.size();
5377            for (int i = 0; i < size; i++) {
5378                CrossProfileIntentFilter filter = matchingFilters.get(i);
5379                int targetUserId = filter.getTargetUserId();
5380                boolean skipCurrentProfile =
5381                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5382                boolean skipCurrentProfileIfNoMatchFound =
5383                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5384                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5385                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5386                    // Checking if there are activities in the target user that can handle the
5387                    // intent.
5388                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5389                            resolvedType, flags, sourceUserId);
5390                    if (resolveInfo != null) return resolveInfo;
5391                    alreadyTriedUserIds.put(targetUserId, true);
5392                }
5393            }
5394        }
5395        return null;
5396    }
5397
5398    /**
5399     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5400     * will forward the intent to the filter's target user.
5401     * Otherwise, returns null.
5402     */
5403    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5404            String resolvedType, int flags, int sourceUserId) {
5405        int targetUserId = filter.getTargetUserId();
5406        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5407                resolvedType, flags, targetUserId);
5408        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5409            // If all the matches in the target profile are suspended, return null.
5410            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5411                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5412                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5413                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5414                            targetUserId);
5415                }
5416            }
5417        }
5418        return null;
5419    }
5420
5421    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5422            int sourceUserId, int targetUserId) {
5423        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5424        long ident = Binder.clearCallingIdentity();
5425        boolean targetIsProfile;
5426        try {
5427            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5428        } finally {
5429            Binder.restoreCallingIdentity(ident);
5430        }
5431        String className;
5432        if (targetIsProfile) {
5433            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5434        } else {
5435            className = FORWARD_INTENT_TO_PARENT;
5436        }
5437        ComponentName forwardingActivityComponentName = new ComponentName(
5438                mAndroidApplication.packageName, className);
5439        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5440                sourceUserId);
5441        if (!targetIsProfile) {
5442            forwardingActivityInfo.showUserIcon = targetUserId;
5443            forwardingResolveInfo.noResourceId = true;
5444        }
5445        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5446        forwardingResolveInfo.priority = 0;
5447        forwardingResolveInfo.preferredOrder = 0;
5448        forwardingResolveInfo.match = 0;
5449        forwardingResolveInfo.isDefault = true;
5450        forwardingResolveInfo.filter = filter;
5451        forwardingResolveInfo.targetUserId = targetUserId;
5452        return forwardingResolveInfo;
5453    }
5454
5455    @Override
5456    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5457            Intent[] specifics, String[] specificTypes, Intent intent,
5458            String resolvedType, int flags, int userId) {
5459        if (!sUserManager.exists(userId)) return Collections.emptyList();
5460        flags = updateFlagsForResolve(flags, userId, intent);
5461        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5462                false, "query intent activity options");
5463        final String resultsAction = intent.getAction();
5464
5465        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5466                | PackageManager.GET_RESOLVED_FILTER, userId);
5467
5468        if (DEBUG_INTENT_MATCHING) {
5469            Log.v(TAG, "Query " + intent + ": " + results);
5470        }
5471
5472        int specificsPos = 0;
5473        int N;
5474
5475        // todo: note that the algorithm used here is O(N^2).  This
5476        // isn't a problem in our current environment, but if we start running
5477        // into situations where we have more than 5 or 10 matches then this
5478        // should probably be changed to something smarter...
5479
5480        // First we go through and resolve each of the specific items
5481        // that were supplied, taking care of removing any corresponding
5482        // duplicate items in the generic resolve list.
5483        if (specifics != null) {
5484            for (int i=0; i<specifics.length; i++) {
5485                final Intent sintent = specifics[i];
5486                if (sintent == null) {
5487                    continue;
5488                }
5489
5490                if (DEBUG_INTENT_MATCHING) {
5491                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5492                }
5493
5494                String action = sintent.getAction();
5495                if (resultsAction != null && resultsAction.equals(action)) {
5496                    // If this action was explicitly requested, then don't
5497                    // remove things that have it.
5498                    action = null;
5499                }
5500
5501                ResolveInfo ri = null;
5502                ActivityInfo ai = null;
5503
5504                ComponentName comp = sintent.getComponent();
5505                if (comp == null) {
5506                    ri = resolveIntent(
5507                        sintent,
5508                        specificTypes != null ? specificTypes[i] : null,
5509                            flags, userId);
5510                    if (ri == null) {
5511                        continue;
5512                    }
5513                    if (ri == mResolveInfo) {
5514                        // ACK!  Must do something better with this.
5515                    }
5516                    ai = ri.activityInfo;
5517                    comp = new ComponentName(ai.applicationInfo.packageName,
5518                            ai.name);
5519                } else {
5520                    ai = getActivityInfo(comp, flags, userId);
5521                    if (ai == null) {
5522                        continue;
5523                    }
5524                }
5525
5526                // Look for any generic query activities that are duplicates
5527                // of this specific one, and remove them from the results.
5528                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5529                N = results.size();
5530                int j;
5531                for (j=specificsPos; j<N; j++) {
5532                    ResolveInfo sri = results.get(j);
5533                    if ((sri.activityInfo.name.equals(comp.getClassName())
5534                            && sri.activityInfo.applicationInfo.packageName.equals(
5535                                    comp.getPackageName()))
5536                        || (action != null && sri.filter.matchAction(action))) {
5537                        results.remove(j);
5538                        if (DEBUG_INTENT_MATCHING) Log.v(
5539                            TAG, "Removing duplicate item from " + j
5540                            + " due to specific " + specificsPos);
5541                        if (ri == null) {
5542                            ri = sri;
5543                        }
5544                        j--;
5545                        N--;
5546                    }
5547                }
5548
5549                // Add this specific item to its proper place.
5550                if (ri == null) {
5551                    ri = new ResolveInfo();
5552                    ri.activityInfo = ai;
5553                }
5554                results.add(specificsPos, ri);
5555                ri.specificIndex = i;
5556                specificsPos++;
5557            }
5558        }
5559
5560        // Now we go through the remaining generic results and remove any
5561        // duplicate actions that are found here.
5562        N = results.size();
5563        for (int i=specificsPos; i<N-1; i++) {
5564            final ResolveInfo rii = results.get(i);
5565            if (rii.filter == null) {
5566                continue;
5567            }
5568
5569            // Iterate over all of the actions of this result's intent
5570            // filter...  typically this should be just one.
5571            final Iterator<String> it = rii.filter.actionsIterator();
5572            if (it == null) {
5573                continue;
5574            }
5575            while (it.hasNext()) {
5576                final String action = it.next();
5577                if (resultsAction != null && resultsAction.equals(action)) {
5578                    // If this action was explicitly requested, then don't
5579                    // remove things that have it.
5580                    continue;
5581                }
5582                for (int j=i+1; j<N; j++) {
5583                    final ResolveInfo rij = results.get(j);
5584                    if (rij.filter != null && rij.filter.hasAction(action)) {
5585                        results.remove(j);
5586                        if (DEBUG_INTENT_MATCHING) Log.v(
5587                            TAG, "Removing duplicate item from " + j
5588                            + " due to action " + action + " at " + i);
5589                        j--;
5590                        N--;
5591                    }
5592                }
5593            }
5594
5595            // If the caller didn't request filter information, drop it now
5596            // so we don't have to marshall/unmarshall it.
5597            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5598                rii.filter = null;
5599            }
5600        }
5601
5602        // Filter out the caller activity if so requested.
5603        if (caller != null) {
5604            N = results.size();
5605            for (int i=0; i<N; i++) {
5606                ActivityInfo ainfo = results.get(i).activityInfo;
5607                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5608                        && caller.getClassName().equals(ainfo.name)) {
5609                    results.remove(i);
5610                    break;
5611                }
5612            }
5613        }
5614
5615        // If the caller didn't request filter information,
5616        // drop them now so we don't have to
5617        // marshall/unmarshall it.
5618        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5619            N = results.size();
5620            for (int i=0; i<N; i++) {
5621                results.get(i).filter = null;
5622            }
5623        }
5624
5625        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5626        return results;
5627    }
5628
5629    @Override
5630    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5631            int userId) {
5632        if (!sUserManager.exists(userId)) return Collections.emptyList();
5633        flags = updateFlagsForResolve(flags, userId, intent);
5634        ComponentName comp = intent.getComponent();
5635        if (comp == null) {
5636            if (intent.getSelector() != null) {
5637                intent = intent.getSelector();
5638                comp = intent.getComponent();
5639            }
5640        }
5641        if (comp != null) {
5642            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5643            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5644            if (ai != null) {
5645                ResolveInfo ri = new ResolveInfo();
5646                ri.activityInfo = ai;
5647                list.add(ri);
5648            }
5649            return list;
5650        }
5651
5652        // reader
5653        synchronized (mPackages) {
5654            String pkgName = intent.getPackage();
5655            if (pkgName == null) {
5656                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5657            }
5658            final PackageParser.Package pkg = mPackages.get(pkgName);
5659            if (pkg != null) {
5660                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5661                        userId);
5662            }
5663            return null;
5664        }
5665    }
5666
5667    @Override
5668    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5669        if (!sUserManager.exists(userId)) return null;
5670        flags = updateFlagsForResolve(flags, userId, intent);
5671        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5672        if (query != null) {
5673            if (query.size() >= 1) {
5674                // If there is more than one service with the same priority,
5675                // just arbitrarily pick the first one.
5676                return query.get(0);
5677            }
5678        }
5679        return null;
5680    }
5681
5682    @Override
5683    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5684            int userId) {
5685        if (!sUserManager.exists(userId)) return Collections.emptyList();
5686        flags = updateFlagsForResolve(flags, userId, intent);
5687        ComponentName comp = intent.getComponent();
5688        if (comp == null) {
5689            if (intent.getSelector() != null) {
5690                intent = intent.getSelector();
5691                comp = intent.getComponent();
5692            }
5693        }
5694        if (comp != null) {
5695            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5696            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5697            if (si != null) {
5698                final ResolveInfo ri = new ResolveInfo();
5699                ri.serviceInfo = si;
5700                list.add(ri);
5701            }
5702            return list;
5703        }
5704
5705        // reader
5706        synchronized (mPackages) {
5707            String pkgName = intent.getPackage();
5708            if (pkgName == null) {
5709                return mServices.queryIntent(intent, resolvedType, flags, userId);
5710            }
5711            final PackageParser.Package pkg = mPackages.get(pkgName);
5712            if (pkg != null) {
5713                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5714                        userId);
5715            }
5716            return null;
5717        }
5718    }
5719
5720    @Override
5721    public List<ResolveInfo> queryIntentContentProviders(
5722            Intent intent, String resolvedType, int flags, int userId) {
5723        if (!sUserManager.exists(userId)) return Collections.emptyList();
5724        flags = updateFlagsForResolve(flags, userId, intent);
5725        ComponentName comp = intent.getComponent();
5726        if (comp == null) {
5727            if (intent.getSelector() != null) {
5728                intent = intent.getSelector();
5729                comp = intent.getComponent();
5730            }
5731        }
5732        if (comp != null) {
5733            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5734            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5735            if (pi != null) {
5736                final ResolveInfo ri = new ResolveInfo();
5737                ri.providerInfo = pi;
5738                list.add(ri);
5739            }
5740            return list;
5741        }
5742
5743        // reader
5744        synchronized (mPackages) {
5745            String pkgName = intent.getPackage();
5746            if (pkgName == null) {
5747                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5748            }
5749            final PackageParser.Package pkg = mPackages.get(pkgName);
5750            if (pkg != null) {
5751                return mProviders.queryIntentForPackage(
5752                        intent, resolvedType, flags, pkg.providers, userId);
5753            }
5754            return null;
5755        }
5756    }
5757
5758    @Override
5759    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5760        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5761        flags = updateFlagsForPackage(flags, userId, null);
5762        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5763        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5764
5765        // writer
5766        synchronized (mPackages) {
5767            ArrayList<PackageInfo> list;
5768            if (listUninstalled) {
5769                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5770                for (PackageSetting ps : mSettings.mPackages.values()) {
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                    if (pi != null) {
5778                        list.add(pi);
5779                    }
5780                }
5781            } else {
5782                list = new ArrayList<PackageInfo>(mPackages.size());
5783                for (PackageParser.Package p : mPackages.values()) {
5784                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5785                    if (pi != null) {
5786                        list.add(pi);
5787                    }
5788                }
5789            }
5790
5791            return new ParceledListSlice<PackageInfo>(list);
5792        }
5793    }
5794
5795    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5796            String[] permissions, boolean[] tmp, int flags, int userId) {
5797        int numMatch = 0;
5798        final PermissionsState permissionsState = ps.getPermissionsState();
5799        for (int i=0; i<permissions.length; i++) {
5800            final String permission = permissions[i];
5801            if (permissionsState.hasPermission(permission, userId)) {
5802                tmp[i] = true;
5803                numMatch++;
5804            } else {
5805                tmp[i] = false;
5806            }
5807        }
5808        if (numMatch == 0) {
5809            return;
5810        }
5811        PackageInfo pi;
5812        if (ps.pkg != null) {
5813            pi = generatePackageInfo(ps.pkg, flags, userId);
5814        } else {
5815            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5816        }
5817        // The above might return null in cases of uninstalled apps or install-state
5818        // skew across users/profiles.
5819        if (pi != null) {
5820            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5821                if (numMatch == permissions.length) {
5822                    pi.requestedPermissions = permissions;
5823                } else {
5824                    pi.requestedPermissions = new String[numMatch];
5825                    numMatch = 0;
5826                    for (int i=0; i<permissions.length; i++) {
5827                        if (tmp[i]) {
5828                            pi.requestedPermissions[numMatch] = permissions[i];
5829                            numMatch++;
5830                        }
5831                    }
5832                }
5833            }
5834            list.add(pi);
5835        }
5836    }
5837
5838    @Override
5839    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5840            String[] permissions, int flags, int userId) {
5841        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5842        flags = updateFlagsForPackage(flags, userId, permissions);
5843        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5844
5845        // writer
5846        synchronized (mPackages) {
5847            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5848            boolean[] tmpBools = new boolean[permissions.length];
5849            if (listUninstalled) {
5850                for (PackageSetting ps : mSettings.mPackages.values()) {
5851                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5852                }
5853            } else {
5854                for (PackageParser.Package pkg : mPackages.values()) {
5855                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5856                    if (ps != null) {
5857                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5858                                userId);
5859                    }
5860                }
5861            }
5862
5863            return new ParceledListSlice<PackageInfo>(list);
5864        }
5865    }
5866
5867    @Override
5868    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5869        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5870        flags = updateFlagsForApplication(flags, userId, null);
5871        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5872
5873        // writer
5874        synchronized (mPackages) {
5875            ArrayList<ApplicationInfo> list;
5876            if (listUninstalled) {
5877                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5878                for (PackageSetting ps : mSettings.mPackages.values()) {
5879                    ApplicationInfo ai;
5880                    if (ps.pkg != null) {
5881                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5882                                ps.readUserState(userId), userId);
5883                    } else {
5884                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5885                    }
5886                    if (ai != null) {
5887                        list.add(ai);
5888                    }
5889                }
5890            } else {
5891                list = new ArrayList<ApplicationInfo>(mPackages.size());
5892                for (PackageParser.Package p : mPackages.values()) {
5893                    if (p.mExtras != null) {
5894                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5895                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5896                        if (ai != null) {
5897                            list.add(ai);
5898                        }
5899                    }
5900                }
5901            }
5902
5903            return new ParceledListSlice<ApplicationInfo>(list);
5904        }
5905    }
5906
5907    @Override
5908    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5909        if (DISABLE_EPHEMERAL_APPS) {
5910            return null;
5911        }
5912
5913        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5914                "getEphemeralApplications");
5915        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5916                "getEphemeralApplications");
5917        synchronized (mPackages) {
5918            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5919                    .getEphemeralApplicationsLPw(userId);
5920            if (ephemeralApps != null) {
5921                return new ParceledListSlice<>(ephemeralApps);
5922            }
5923        }
5924        return null;
5925    }
5926
5927    @Override
5928    public boolean isEphemeralApplication(String packageName, int userId) {
5929        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5930                "isEphemeral");
5931        if (DISABLE_EPHEMERAL_APPS) {
5932            return false;
5933        }
5934
5935        if (!isCallerSameApp(packageName)) {
5936            return false;
5937        }
5938        synchronized (mPackages) {
5939            PackageParser.Package pkg = mPackages.get(packageName);
5940            if (pkg != null) {
5941                return pkg.applicationInfo.isEphemeralApp();
5942            }
5943        }
5944        return false;
5945    }
5946
5947    @Override
5948    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5949        if (DISABLE_EPHEMERAL_APPS) {
5950            return null;
5951        }
5952
5953        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5954                "getCookie");
5955        if (!isCallerSameApp(packageName)) {
5956            return null;
5957        }
5958        synchronized (mPackages) {
5959            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5960                    packageName, userId);
5961        }
5962    }
5963
5964    @Override
5965    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5966        if (DISABLE_EPHEMERAL_APPS) {
5967            return true;
5968        }
5969
5970        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5971                "setCookie");
5972        if (!isCallerSameApp(packageName)) {
5973            return false;
5974        }
5975        synchronized (mPackages) {
5976            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5977                    packageName, cookie, userId);
5978        }
5979    }
5980
5981    @Override
5982    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5983        if (DISABLE_EPHEMERAL_APPS) {
5984            return null;
5985        }
5986
5987        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5988                "getEphemeralApplicationIcon");
5989        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5990                "getEphemeralApplicationIcon");
5991        synchronized (mPackages) {
5992            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5993                    packageName, userId);
5994        }
5995    }
5996
5997    private boolean isCallerSameApp(String packageName) {
5998        PackageParser.Package pkg = mPackages.get(packageName);
5999        return pkg != null
6000                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6001    }
6002
6003    public List<ApplicationInfo> getPersistentApplications(int flags) {
6004        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6005
6006        // reader
6007        synchronized (mPackages) {
6008            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6009            final int userId = UserHandle.getCallingUserId();
6010            while (i.hasNext()) {
6011                final PackageParser.Package p = i.next();
6012                if (p.applicationInfo != null
6013                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6014                        && (!mSafeMode || isSystemApp(p))) {
6015                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6016                    if (ps != null) {
6017                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6018                                ps.readUserState(userId), userId);
6019                        if (ai != null) {
6020                            finalList.add(ai);
6021                        }
6022                    }
6023                }
6024            }
6025        }
6026
6027        return finalList;
6028    }
6029
6030    @Override
6031    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6032        if (!sUserManager.exists(userId)) return null;
6033        flags = updateFlagsForComponent(flags, userId, name);
6034        // reader
6035        synchronized (mPackages) {
6036            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6037            PackageSetting ps = provider != null
6038                    ? mSettings.mPackages.get(provider.owner.packageName)
6039                    : null;
6040            return ps != null
6041                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6042                    ? PackageParser.generateProviderInfo(provider, flags,
6043                            ps.readUserState(userId), userId)
6044                    : null;
6045        }
6046    }
6047
6048    /**
6049     * @deprecated
6050     */
6051    @Deprecated
6052    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6053        // reader
6054        synchronized (mPackages) {
6055            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6056                    .entrySet().iterator();
6057            final int userId = UserHandle.getCallingUserId();
6058            while (i.hasNext()) {
6059                Map.Entry<String, PackageParser.Provider> entry = i.next();
6060                PackageParser.Provider p = entry.getValue();
6061                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6062
6063                if (ps != null && p.syncable
6064                        && (!mSafeMode || (p.info.applicationInfo.flags
6065                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6066                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6067                            ps.readUserState(userId), userId);
6068                    if (info != null) {
6069                        outNames.add(entry.getKey());
6070                        outInfo.add(info);
6071                    }
6072                }
6073            }
6074        }
6075    }
6076
6077    @Override
6078    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6079            int uid, int flags) {
6080        final int userId = processName != null ? UserHandle.getUserId(uid)
6081                : UserHandle.getCallingUserId();
6082        if (!sUserManager.exists(userId)) return null;
6083        flags = updateFlagsForComponent(flags, userId, processName);
6084
6085        ArrayList<ProviderInfo> finalList = null;
6086        // reader
6087        synchronized (mPackages) {
6088            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6089            while (i.hasNext()) {
6090                final PackageParser.Provider p = i.next();
6091                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6092                if (ps != null && p.info.authority != null
6093                        && (processName == null
6094                                || (p.info.processName.equals(processName)
6095                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6096                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6097                    if (finalList == null) {
6098                        finalList = new ArrayList<ProviderInfo>(3);
6099                    }
6100                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6101                            ps.readUserState(userId), userId);
6102                    if (info != null) {
6103                        finalList.add(info);
6104                    }
6105                }
6106            }
6107        }
6108
6109        if (finalList != null) {
6110            Collections.sort(finalList, mProviderInitOrderSorter);
6111            return new ParceledListSlice<ProviderInfo>(finalList);
6112        }
6113
6114        return null;
6115    }
6116
6117    @Override
6118    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6119        // reader
6120        synchronized (mPackages) {
6121            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6122            return PackageParser.generateInstrumentationInfo(i, flags);
6123        }
6124    }
6125
6126    @Override
6127    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6128            int flags) {
6129        ArrayList<InstrumentationInfo> finalList =
6130            new ArrayList<InstrumentationInfo>();
6131
6132        // reader
6133        synchronized (mPackages) {
6134            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6135            while (i.hasNext()) {
6136                final PackageParser.Instrumentation p = i.next();
6137                if (targetPackage == null
6138                        || targetPackage.equals(p.info.targetPackage)) {
6139                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6140                            flags);
6141                    if (ii != null) {
6142                        finalList.add(ii);
6143                    }
6144                }
6145            }
6146        }
6147
6148        return finalList;
6149    }
6150
6151    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6152        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6153        if (overlays == null) {
6154            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6155            return;
6156        }
6157        for (PackageParser.Package opkg : overlays.values()) {
6158            // Not much to do if idmap fails: we already logged the error
6159            // and we certainly don't want to abort installation of pkg simply
6160            // because an overlay didn't fit properly. For these reasons,
6161            // ignore the return value of createIdmapForPackagePairLI.
6162            createIdmapForPackagePairLI(pkg, opkg);
6163        }
6164    }
6165
6166    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6167            PackageParser.Package opkg) {
6168        if (!opkg.mTrustedOverlay) {
6169            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6170                    opkg.baseCodePath + ": overlay not trusted");
6171            return false;
6172        }
6173        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6174        if (overlaySet == null) {
6175            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6176                    opkg.baseCodePath + " but target package has no known overlays");
6177            return false;
6178        }
6179        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6180        // TODO: generate idmap for split APKs
6181        try {
6182            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6183        } catch (InstallerException e) {
6184            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6185                    + opkg.baseCodePath);
6186            return false;
6187        }
6188        PackageParser.Package[] overlayArray =
6189            overlaySet.values().toArray(new PackageParser.Package[0]);
6190        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6191            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6192                return p1.mOverlayPriority - p2.mOverlayPriority;
6193            }
6194        };
6195        Arrays.sort(overlayArray, cmp);
6196
6197        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6198        int i = 0;
6199        for (PackageParser.Package p : overlayArray) {
6200            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6201        }
6202        return true;
6203    }
6204
6205    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6206        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6207        try {
6208            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6209        } finally {
6210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6211        }
6212    }
6213
6214    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6215        final File[] files = dir.listFiles();
6216        if (ArrayUtils.isEmpty(files)) {
6217            Log.d(TAG, "No files in app dir " + dir);
6218            return;
6219        }
6220
6221        if (DEBUG_PACKAGE_SCANNING) {
6222            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6223                    + " flags=0x" + Integer.toHexString(parseFlags));
6224        }
6225
6226        for (File file : files) {
6227            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6228                    && !PackageInstallerService.isStageName(file.getName());
6229            if (!isPackage) {
6230                // Ignore entries which are not packages
6231                continue;
6232            }
6233            try {
6234                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6235                        scanFlags, currentTime, null);
6236            } catch (PackageManagerException e) {
6237                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6238
6239                // Delete invalid userdata apps
6240                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6241                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6242                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6243                    removeCodePathLI(file);
6244                }
6245            }
6246        }
6247    }
6248
6249    private static File getSettingsProblemFile() {
6250        File dataDir = Environment.getDataDirectory();
6251        File systemDir = new File(dataDir, "system");
6252        File fname = new File(systemDir, "uiderrors.txt");
6253        return fname;
6254    }
6255
6256    static void reportSettingsProblem(int priority, String msg) {
6257        logCriticalInfo(priority, msg);
6258    }
6259
6260    static void logCriticalInfo(int priority, String msg) {
6261        Slog.println(priority, TAG, msg);
6262        EventLogTags.writePmCriticalInfo(msg);
6263        try {
6264            File fname = getSettingsProblemFile();
6265            FileOutputStream out = new FileOutputStream(fname, true);
6266            PrintWriter pw = new FastPrintWriter(out);
6267            SimpleDateFormat formatter = new SimpleDateFormat();
6268            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6269            pw.println(dateString + ": " + msg);
6270            pw.close();
6271            FileUtils.setPermissions(
6272                    fname.toString(),
6273                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6274                    -1, -1);
6275        } catch (java.io.IOException e) {
6276        }
6277    }
6278
6279    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6280            int parseFlags) throws PackageManagerException {
6281        if (ps != null
6282                && ps.codePath.equals(srcFile)
6283                && ps.timeStamp == srcFile.lastModified()
6284                && !isCompatSignatureUpdateNeeded(pkg)
6285                && !isRecoverSignatureUpdateNeeded(pkg)) {
6286            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6287            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6288            ArraySet<PublicKey> signingKs;
6289            synchronized (mPackages) {
6290                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6291            }
6292            if (ps.signatures.mSignatures != null
6293                    && ps.signatures.mSignatures.length != 0
6294                    && signingKs != null) {
6295                // Optimization: reuse the existing cached certificates
6296                // if the package appears to be unchanged.
6297                pkg.mSignatures = ps.signatures.mSignatures;
6298                pkg.mSigningKeys = signingKs;
6299                return;
6300            }
6301
6302            Slog.w(TAG, "PackageSetting for " + ps.name
6303                    + " is missing signatures.  Collecting certs again to recover them.");
6304        } else {
6305            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6306        }
6307
6308        try {
6309            PackageParser.collectCertificates(pkg, parseFlags);
6310        } catch (PackageParserException e) {
6311            throw PackageManagerException.from(e);
6312        }
6313    }
6314
6315    /**
6316     *  Traces a package scan.
6317     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6318     */
6319    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6320            long currentTime, UserHandle user) throws PackageManagerException {
6321        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6322        try {
6323            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6324        } finally {
6325            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6326        }
6327    }
6328
6329    /**
6330     *  Scans a package and returns the newly parsed package.
6331     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6332     */
6333    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6334            long currentTime, UserHandle user) throws PackageManagerException {
6335        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6336        parseFlags |= mDefParseFlags;
6337        PackageParser pp = new PackageParser();
6338        pp.setSeparateProcesses(mSeparateProcesses);
6339        pp.setOnlyCoreApps(mOnlyCore);
6340        pp.setDisplayMetrics(mMetrics);
6341
6342        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6343            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6344        }
6345
6346        final PackageParser.Package pkg;
6347        try {
6348            pkg = pp.parsePackage(scanFile, parseFlags);
6349        } catch (PackageParserException e) {
6350            throw PackageManagerException.from(e);
6351        }
6352
6353        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6354    }
6355
6356    /**
6357     *  Scans a package and returns the newly parsed package.
6358     *  @throws PackageManagerException on a parse error.
6359     */
6360    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6361            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6362            throws PackageManagerException {
6363        // If the package has children and this is the first dive in the function
6364        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6365        // packages (parent and children) would be successfully scanned before the
6366        // actual scan since scanning mutates internal state and we want to atomically
6367        // install the package and its children.
6368        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6369            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6370                scanFlags |= SCAN_CHECK_ONLY;
6371            }
6372        } else {
6373            scanFlags &= ~SCAN_CHECK_ONLY;
6374        }
6375
6376        // Scan the parent
6377        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6378                scanFlags, currentTime, user);
6379
6380        // Scan the children
6381        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6382        for (int i = 0; i < childCount; i++) {
6383            PackageParser.Package childPackage = pkg.childPackages.get(i);
6384            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6385                    currentTime, user);
6386        }
6387
6388
6389        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6390            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6391        }
6392
6393        return scannedPkg;
6394    }
6395
6396    /**
6397     *  Scans a package and returns the newly parsed package.
6398     *  @throws PackageManagerException on a parse error.
6399     */
6400    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6401            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6402            throws PackageManagerException {
6403        PackageSetting ps = null;
6404        PackageSetting updatedPkg;
6405        // reader
6406        synchronized (mPackages) {
6407            // Look to see if we already know about this package.
6408            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6409            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6410                // This package has been renamed to its original name.  Let's
6411                // use that.
6412                ps = mSettings.peekPackageLPr(oldName);
6413            }
6414            // If there was no original package, see one for the real package name.
6415            if (ps == null) {
6416                ps = mSettings.peekPackageLPr(pkg.packageName);
6417            }
6418            // Check to see if this package could be hiding/updating a system
6419            // package.  Must look for it either under the original or real
6420            // package name depending on our state.
6421            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6422            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6423
6424            // If this is a package we don't know about on the system partition, we
6425            // may need to remove disabled child packages on the system partition
6426            // or may need to not add child packages if the parent apk is updated
6427            // on the data partition and no longer defines this child package.
6428            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6429                // If this is a parent package for an updated system app and this system
6430                // app got an OTA update which no longer defines some of the child packages
6431                // we have to prune them from the disabled system packages.
6432                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6433                if (disabledPs != null) {
6434                    final int scannedChildCount = (pkg.childPackages != null)
6435                            ? pkg.childPackages.size() : 0;
6436                    final int disabledChildCount = disabledPs.childPackageNames != null
6437                            ? disabledPs.childPackageNames.size() : 0;
6438                    for (int i = 0; i < disabledChildCount; i++) {
6439                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6440                        boolean disabledPackageAvailable = false;
6441                        for (int j = 0; j < scannedChildCount; j++) {
6442                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6443                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6444                                disabledPackageAvailable = true;
6445                                break;
6446                            }
6447                         }
6448                         if (!disabledPackageAvailable) {
6449                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6450                         }
6451                    }
6452                }
6453            }
6454        }
6455
6456        boolean updatedPkgBetter = false;
6457        // First check if this is a system package that may involve an update
6458        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6459            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6460            // it needs to drop FLAG_PRIVILEGED.
6461            if (locationIsPrivileged(scanFile)) {
6462                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6463            } else {
6464                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6465            }
6466
6467            if (ps != null && !ps.codePath.equals(scanFile)) {
6468                // The path has changed from what was last scanned...  check the
6469                // version of the new path against what we have stored to determine
6470                // what to do.
6471                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6472                if (pkg.mVersionCode <= ps.versionCode) {
6473                    // The system package has been updated and the code path does not match
6474                    // Ignore entry. Skip it.
6475                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6476                            + " ignored: updated version " + ps.versionCode
6477                            + " better than this " + pkg.mVersionCode);
6478                    if (!updatedPkg.codePath.equals(scanFile)) {
6479                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6480                                + ps.name + " changing from " + updatedPkg.codePathString
6481                                + " to " + scanFile);
6482                        updatedPkg.codePath = scanFile;
6483                        updatedPkg.codePathString = scanFile.toString();
6484                        updatedPkg.resourcePath = scanFile;
6485                        updatedPkg.resourcePathString = scanFile.toString();
6486                    }
6487                    updatedPkg.pkg = pkg;
6488                    updatedPkg.versionCode = pkg.mVersionCode;
6489
6490                    // Update the disabled system child packages to point to the package too.
6491                    final int childCount = updatedPkg.childPackageNames != null
6492                            ? updatedPkg.childPackageNames.size() : 0;
6493                    for (int i = 0; i < childCount; i++) {
6494                        String childPackageName = updatedPkg.childPackageNames.get(i);
6495                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6496                                childPackageName);
6497                        if (updatedChildPkg != null) {
6498                            updatedChildPkg.pkg = pkg;
6499                            updatedChildPkg.versionCode = pkg.mVersionCode;
6500                        }
6501                    }
6502
6503                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6504                            + scanFile + " ignored: updated version " + ps.versionCode
6505                            + " better than this " + pkg.mVersionCode);
6506                } else {
6507                    // The current app on the system partition is better than
6508                    // what we have updated to on the data partition; switch
6509                    // back to the system partition version.
6510                    // At this point, its safely assumed that package installation for
6511                    // apps in system partition will go through. If not there won't be a working
6512                    // version of the app
6513                    // writer
6514                    synchronized (mPackages) {
6515                        // Just remove the loaded entries from package lists.
6516                        mPackages.remove(ps.name);
6517                    }
6518
6519                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6520                            + " reverting from " + ps.codePathString
6521                            + ": new version " + pkg.mVersionCode
6522                            + " better than installed " + ps.versionCode);
6523
6524                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6525                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6526                    synchronized (mInstallLock) {
6527                        args.cleanUpResourcesLI();
6528                    }
6529                    synchronized (mPackages) {
6530                        mSettings.enableSystemPackageLPw(ps.name);
6531                    }
6532                    updatedPkgBetter = true;
6533                }
6534            }
6535        }
6536
6537        if (updatedPkg != null) {
6538            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6539            // initially
6540            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6541
6542            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6543            // flag set initially
6544            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6545                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6546            }
6547        }
6548
6549        // Verify certificates against what was last scanned
6550        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6551
6552        /*
6553         * A new system app appeared, but we already had a non-system one of the
6554         * same name installed earlier.
6555         */
6556        boolean shouldHideSystemApp = false;
6557        if (updatedPkg == null && ps != null
6558                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6559            /*
6560             * Check to make sure the signatures match first. If they don't,
6561             * wipe the installed application and its data.
6562             */
6563            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6564                    != PackageManager.SIGNATURE_MATCH) {
6565                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6566                        + " signatures don't match existing userdata copy; removing");
6567                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false, null);
6568                ps = null;
6569            } else {
6570                /*
6571                 * If the newly-added system app is an older version than the
6572                 * already installed version, hide it. It will be scanned later
6573                 * and re-added like an update.
6574                 */
6575                if (pkg.mVersionCode <= ps.versionCode) {
6576                    shouldHideSystemApp = true;
6577                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6578                            + " but new version " + pkg.mVersionCode + " better than installed "
6579                            + ps.versionCode + "; hiding system");
6580                } else {
6581                    /*
6582                     * The newly found system app is a newer version that the
6583                     * one previously installed. Simply remove the
6584                     * already-installed application and replace it with our own
6585                     * while keeping the application data.
6586                     */
6587                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6588                            + " reverting from " + ps.codePathString + ": new version "
6589                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6590                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6591                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6592                    synchronized (mInstallLock) {
6593                        args.cleanUpResourcesLI();
6594                    }
6595                }
6596            }
6597        }
6598
6599        // The apk is forward locked (not public) if its code and resources
6600        // are kept in different files. (except for app in either system or
6601        // vendor path).
6602        // TODO grab this value from PackageSettings
6603        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6604            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6605                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6606            }
6607        }
6608
6609        // TODO: extend to support forward-locked splits
6610        String resourcePath = null;
6611        String baseResourcePath = null;
6612        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6613            if (ps != null && ps.resourcePathString != null) {
6614                resourcePath = ps.resourcePathString;
6615                baseResourcePath = ps.resourcePathString;
6616            } else {
6617                // Should not happen at all. Just log an error.
6618                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6619            }
6620        } else {
6621            resourcePath = pkg.codePath;
6622            baseResourcePath = pkg.baseCodePath;
6623        }
6624
6625        // Set application objects path explicitly.
6626        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6627        pkg.setApplicationInfoCodePath(pkg.codePath);
6628        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6629        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6630        pkg.setApplicationInfoResourcePath(resourcePath);
6631        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6632        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6633
6634        // Note that we invoke the following method only if we are about to unpack an application
6635        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6636                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6637
6638        /*
6639         * If the system app should be overridden by a previously installed
6640         * data, hide the system app now and let the /data/app scan pick it up
6641         * again.
6642         */
6643        if (shouldHideSystemApp) {
6644            synchronized (mPackages) {
6645                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6646            }
6647        }
6648
6649        return scannedPkg;
6650    }
6651
6652    private static String fixProcessName(String defProcessName,
6653            String processName, int uid) {
6654        if (processName == null) {
6655            return defProcessName;
6656        }
6657        return processName;
6658    }
6659
6660    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6661            throws PackageManagerException {
6662        if (pkgSetting.signatures.mSignatures != null) {
6663            // Already existing package. Make sure signatures match
6664            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6665                    == PackageManager.SIGNATURE_MATCH;
6666            if (!match) {
6667                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6668                        == PackageManager.SIGNATURE_MATCH;
6669            }
6670            if (!match) {
6671                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6672                        == PackageManager.SIGNATURE_MATCH;
6673            }
6674            if (!match) {
6675                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6676                        + pkg.packageName + " signatures do not match the "
6677                        + "previously installed version; ignoring!");
6678            }
6679        }
6680
6681        // Check for shared user signatures
6682        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6683            // Already existing package. Make sure signatures match
6684            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6685                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6686            if (!match) {
6687                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6688                        == PackageManager.SIGNATURE_MATCH;
6689            }
6690            if (!match) {
6691                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6692                        == PackageManager.SIGNATURE_MATCH;
6693            }
6694            if (!match) {
6695                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6696                        "Package " + pkg.packageName
6697                        + " has no signatures that match those in shared user "
6698                        + pkgSetting.sharedUser.name + "; ignoring!");
6699            }
6700        }
6701    }
6702
6703    /**
6704     * Enforces that only the system UID or root's UID can call a method exposed
6705     * via Binder.
6706     *
6707     * @param message used as message if SecurityException is thrown
6708     * @throws SecurityException if the caller is not system or root
6709     */
6710    private static final void enforceSystemOrRoot(String message) {
6711        final int uid = Binder.getCallingUid();
6712        if (uid != Process.SYSTEM_UID && uid != 0) {
6713            throw new SecurityException(message);
6714        }
6715    }
6716
6717    @Override
6718    public void performFstrimIfNeeded() {
6719        enforceSystemOrRoot("Only the system can request fstrim");
6720
6721        // Before everything else, see whether we need to fstrim.
6722        try {
6723            IMountService ms = PackageHelper.getMountService();
6724            if (ms != null) {
6725                final boolean isUpgrade = isUpgrade();
6726                boolean doTrim = isUpgrade;
6727                if (doTrim) {
6728                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6729                } else {
6730                    final long interval = android.provider.Settings.Global.getLong(
6731                            mContext.getContentResolver(),
6732                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6733                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6734                    if (interval > 0) {
6735                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6736                        if (timeSinceLast > interval) {
6737                            doTrim = true;
6738                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6739                                    + "; running immediately");
6740                        }
6741                    }
6742                }
6743                if (doTrim) {
6744                    if (!isFirstBoot()) {
6745                        try {
6746                            ActivityManagerNative.getDefault().showBootMessage(
6747                                    mContext.getResources().getString(
6748                                            R.string.android_upgrading_fstrim), true);
6749                        } catch (RemoteException e) {
6750                        }
6751                    }
6752                    ms.runMaintenance();
6753                }
6754            } else {
6755                Slog.e(TAG, "Mount service unavailable!");
6756            }
6757        } catch (RemoteException e) {
6758            // Can't happen; MountService is local
6759        }
6760    }
6761
6762    @Override
6763    public void extractPackagesIfNeeded() {
6764        enforceSystemOrRoot("Only the system can request package extraction");
6765
6766        // Extract pacakges only if profile-guided compilation is enabled because
6767        // otherwise BackgroundDexOptService will not dexopt them later.
6768        if (mUseJitProfiles) {
6769            ArraySet<String> pkgs = getOptimizablePackages();
6770            if (pkgs != null) {
6771                for (String pkg : pkgs) {
6772                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6773                            true /* extractOnly */, false /* force */);
6774                }
6775            }
6776        }
6777    }
6778
6779    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6780        List<ResolveInfo> ris = null;
6781        try {
6782            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6783                    intent, null, 0, userId);
6784        } catch (RemoteException e) {
6785        }
6786        ArraySet<String> pkgNames = new ArraySet<String>();
6787        if (ris != null) {
6788            for (ResolveInfo ri : ris) {
6789                pkgNames.add(ri.activityInfo.packageName);
6790            }
6791        }
6792        return pkgNames;
6793    }
6794
6795    @Override
6796    public void notifyPackageUse(String packageName) {
6797        synchronized (mPackages) {
6798            PackageParser.Package p = mPackages.get(packageName);
6799            if (p == null) {
6800                return;
6801            }
6802            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6803        }
6804    }
6805
6806    // TODO: this is not used nor needed. Delete it.
6807    @Override
6808    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6809        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6810                false /* extractOnly */, false /* force */);
6811    }
6812
6813    @Override
6814    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6815            boolean extractOnly, boolean force) {
6816        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6817    }
6818
6819    private boolean performDexOptTraced(String packageName, String instructionSet,
6820                boolean useProfiles, boolean extractOnly, boolean force) {
6821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6822        try {
6823            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6824                    force);
6825        } finally {
6826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6827        }
6828    }
6829
6830    private boolean performDexOptInternal(String packageName, String instructionSet,
6831                boolean useProfiles, boolean extractOnly, boolean force) {
6832        PackageParser.Package p;
6833        final String targetInstructionSet;
6834        synchronized (mPackages) {
6835            p = mPackages.get(packageName);
6836            if (p == null) {
6837                return false;
6838            }
6839            mPackageUsage.write(false);
6840
6841            targetInstructionSet = instructionSet != null ? instructionSet :
6842                    getPrimaryInstructionSet(p.applicationInfo);
6843            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6844                // Skip only if we do not use profiles since they might trigger a recompilation.
6845                return false;
6846            }
6847        }
6848        long callingId = Binder.clearCallingIdentity();
6849        try {
6850            synchronized (mInstallLock) {
6851                final String[] instructionSets = new String[] { targetInstructionSet };
6852                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6853                        useProfiles, extractOnly, force);
6854                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6855            }
6856        } finally {
6857            Binder.restoreCallingIdentity(callingId);
6858        }
6859    }
6860
6861    public ArraySet<String> getOptimizablePackages() {
6862        ArraySet<String> pkgs = new ArraySet<String>();
6863        synchronized (mPackages) {
6864            for (PackageParser.Package p : mPackages.values()) {
6865                if (PackageDexOptimizer.canOptimizePackage(p)) {
6866                    pkgs.add(p.packageName);
6867                }
6868            }
6869        }
6870        return pkgs;
6871    }
6872
6873    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6874            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6875        // Select the dex optimizer based on the force parameter.
6876        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6877        //       allocate an object here.
6878        PackageDexOptimizer pdo = force
6879                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6880                : mPackageDexOptimizer;
6881
6882        // Optimize all dependencies first. Note: we ignore the return value and march on
6883        // on errors.
6884        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6885        if (!deps.isEmpty()) {
6886            for (PackageParser.Package depPackage : deps) {
6887                // TODO: Analyze and investigate if we (should) profile libraries.
6888                // Currently this will do a full compilation of the library.
6889                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6890                        false /* extractOnly */);
6891            }
6892        }
6893
6894        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6895    }
6896
6897    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6898        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6899            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6900            Set<String> collectedNames = new HashSet<>();
6901            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6902
6903            retValue.remove(p);
6904
6905            return retValue;
6906        } else {
6907            return Collections.emptyList();
6908        }
6909    }
6910
6911    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6912            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6913        if (!collectedNames.contains(p.packageName)) {
6914            collectedNames.add(p.packageName);
6915            collected.add(p);
6916
6917            if (p.usesLibraries != null) {
6918                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6919            }
6920            if (p.usesOptionalLibraries != null) {
6921                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6922                        collectedNames);
6923            }
6924        }
6925    }
6926
6927    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6928            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6929        for (String libName : libs) {
6930            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6931            if (libPkg != null) {
6932                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6933            }
6934        }
6935    }
6936
6937    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6938        synchronized (mPackages) {
6939            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6940            if (lib != null && lib.apk != null) {
6941                return mPackages.get(lib.apk);
6942            }
6943        }
6944        return null;
6945    }
6946
6947    public void shutdown() {
6948        mPackageUsage.write(true);
6949    }
6950
6951    @Override
6952    public void forceDexOpt(String packageName) {
6953        enforceSystemOrRoot("forceDexOpt");
6954
6955        PackageParser.Package pkg;
6956        synchronized (mPackages) {
6957            pkg = mPackages.get(packageName);
6958            if (pkg == null) {
6959                throw new IllegalArgumentException("Unknown package: " + packageName);
6960            }
6961        }
6962
6963        synchronized (mInstallLock) {
6964            final String[] instructionSets = new String[] {
6965                    getPrimaryInstructionSet(pkg.applicationInfo) };
6966
6967            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6968
6969            // Whoever is calling forceDexOpt wants a fully compiled package.
6970            // Don't use profiles since that may cause compilation to be skipped.
6971            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
6972                    false /* useProfiles */, false /* extractOnly */, true /* force */);
6973
6974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6975            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6976                throw new IllegalStateException("Failed to dexopt: " + res);
6977            }
6978        }
6979    }
6980
6981    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6982        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6983            Slog.w(TAG, "Unable to update from " + oldPkg.name
6984                    + " to " + newPkg.packageName
6985                    + ": old package not in system partition");
6986            return false;
6987        } else if (mPackages.get(oldPkg.name) != null) {
6988            Slog.w(TAG, "Unable to update from " + oldPkg.name
6989                    + " to " + newPkg.packageName
6990                    + ": old package still exists");
6991            return false;
6992        }
6993        return true;
6994    }
6995
6996    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6997        // TODO: triage flags as part of 26466827
6998        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
6999
7000        boolean res = true;
7001        final int[] users = sUserManager.getUserIds();
7002        for (int user : users) {
7003            try {
7004                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7005            } catch (InstallerException e) {
7006                Slog.w(TAG, "Failed to delete data directory", e);
7007                res = false;
7008            }
7009        }
7010        return res;
7011    }
7012
7013    void removeCodePathLI(File codePath) {
7014        if (codePath.isDirectory()) {
7015            try {
7016                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7017            } catch (InstallerException e) {
7018                Slog.w(TAG, "Failed to remove code path", e);
7019            }
7020        } else {
7021            codePath.delete();
7022        }
7023    }
7024
7025    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7026        try {
7027            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7028        } catch (InstallerException e) {
7029            Slog.w(TAG, "Failed to destroy app data", e);
7030        }
7031    }
7032
7033    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7034            int appId, String seinfo) {
7035        try {
7036            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7037        } catch (InstallerException e) {
7038            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7039        }
7040    }
7041
7042    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7043        final PackageParser.Package pkg;
7044        synchronized (mPackages) {
7045            pkg = mPackages.get(packageName);
7046        }
7047        if (pkg == null) {
7048            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7049            return;
7050        }
7051        deleteCodeCacheDirsLI(pkg);
7052    }
7053
7054    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7055        // TODO: triage flags as part of 26466827
7056        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7057
7058        int[] users = sUserManager.getUserIds();
7059        int res = 0;
7060        for (int user : users) {
7061            // Remove the parent code cache
7062            try {
7063                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7064                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7065            } catch (InstallerException e) {
7066                Slog.w(TAG, "Failed to delete code cache directory", e);
7067            }
7068            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7069            for (int i = 0; i < childCount; i++) {
7070                PackageParser.Package childPkg = pkg.childPackages.get(i);
7071                // Remove the child code cache
7072                try {
7073                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7074                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7075                } catch (InstallerException e) {
7076                    Slog.w(TAG, "Failed to delete code cache directory", e);
7077                }
7078            }
7079        }
7080    }
7081
7082    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7083            long lastUpdateTime) {
7084        // Set parent install/update time
7085        PackageSetting ps = (PackageSetting) pkg.mExtras;
7086        if (ps != null) {
7087            ps.firstInstallTime = firstInstallTime;
7088            ps.lastUpdateTime = lastUpdateTime;
7089        }
7090        // Set children install/update time
7091        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7092        for (int i = 0; i < childCount; i++) {
7093            PackageParser.Package childPkg = pkg.childPackages.get(i);
7094            ps = (PackageSetting) childPkg.mExtras;
7095            if (ps != null) {
7096                ps.firstInstallTime = firstInstallTime;
7097                ps.lastUpdateTime = lastUpdateTime;
7098            }
7099        }
7100    }
7101
7102    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7103            PackageParser.Package changingLib) {
7104        if (file.path != null) {
7105            usesLibraryFiles.add(file.path);
7106            return;
7107        }
7108        PackageParser.Package p = mPackages.get(file.apk);
7109        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7110            // If we are doing this while in the middle of updating a library apk,
7111            // then we need to make sure to use that new apk for determining the
7112            // dependencies here.  (We haven't yet finished committing the new apk
7113            // to the package manager state.)
7114            if (p == null || p.packageName.equals(changingLib.packageName)) {
7115                p = changingLib;
7116            }
7117        }
7118        if (p != null) {
7119            usesLibraryFiles.addAll(p.getAllCodePaths());
7120        }
7121    }
7122
7123    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7124            PackageParser.Package changingLib) throws PackageManagerException {
7125        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7126            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7127            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7128            for (int i=0; i<N; i++) {
7129                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7130                if (file == null) {
7131                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7132                            "Package " + pkg.packageName + " requires unavailable shared library "
7133                            + pkg.usesLibraries.get(i) + "; failing!");
7134                }
7135                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7136            }
7137            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7138            for (int i=0; i<N; i++) {
7139                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7140                if (file == null) {
7141                    Slog.w(TAG, "Package " + pkg.packageName
7142                            + " desires unavailable shared library "
7143                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7144                } else {
7145                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7146                }
7147            }
7148            N = usesLibraryFiles.size();
7149            if (N > 0) {
7150                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7151            } else {
7152                pkg.usesLibraryFiles = null;
7153            }
7154        }
7155    }
7156
7157    private static boolean hasString(List<String> list, List<String> which) {
7158        if (list == null) {
7159            return false;
7160        }
7161        for (int i=list.size()-1; i>=0; i--) {
7162            for (int j=which.size()-1; j>=0; j--) {
7163                if (which.get(j).equals(list.get(i))) {
7164                    return true;
7165                }
7166            }
7167        }
7168        return false;
7169    }
7170
7171    private void updateAllSharedLibrariesLPw() {
7172        for (PackageParser.Package pkg : mPackages.values()) {
7173            try {
7174                updateSharedLibrariesLPw(pkg, null);
7175            } catch (PackageManagerException e) {
7176                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7177            }
7178        }
7179    }
7180
7181    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7182            PackageParser.Package changingPkg) {
7183        ArrayList<PackageParser.Package> res = null;
7184        for (PackageParser.Package pkg : mPackages.values()) {
7185            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7186                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7187                if (res == null) {
7188                    res = new ArrayList<PackageParser.Package>();
7189                }
7190                res.add(pkg);
7191                try {
7192                    updateSharedLibrariesLPw(pkg, changingPkg);
7193                } catch (PackageManagerException e) {
7194                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7195                }
7196            }
7197        }
7198        return res;
7199    }
7200
7201    /**
7202     * Derive the value of the {@code cpuAbiOverride} based on the provided
7203     * value and an optional stored value from the package settings.
7204     */
7205    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7206        String cpuAbiOverride = null;
7207
7208        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7209            cpuAbiOverride = null;
7210        } else if (abiOverride != null) {
7211            cpuAbiOverride = abiOverride;
7212        } else if (settings != null) {
7213            cpuAbiOverride = settings.cpuAbiOverrideString;
7214        }
7215
7216        return cpuAbiOverride;
7217    }
7218
7219    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7220            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7221        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7222        // If the package has children and this is the first dive in the function
7223        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7224        // whether all packages (parent and children) would be successfully scanned
7225        // before the actual scan since scanning mutates internal state and we want
7226        // to atomically install the package and its children.
7227        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7228            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7229                scanFlags |= SCAN_CHECK_ONLY;
7230            }
7231        } else {
7232            scanFlags &= ~SCAN_CHECK_ONLY;
7233        }
7234
7235        final PackageParser.Package scannedPkg;
7236        try {
7237            // Scan the parent
7238            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7239            // Scan the children
7240            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7241            for (int i = 0; i < childCount; i++) {
7242                PackageParser.Package childPkg = pkg.childPackages.get(i);
7243                scanPackageLI(childPkg, parseFlags,
7244                        scanFlags, currentTime, user);
7245            }
7246        } finally {
7247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7248        }
7249
7250        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7251            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7252        }
7253
7254        return scannedPkg;
7255    }
7256
7257    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7258            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7259        boolean success = false;
7260        try {
7261            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7262                    currentTime, user);
7263            success = true;
7264            return res;
7265        } finally {
7266            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7267                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7268            }
7269        }
7270    }
7271
7272    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7273            int scanFlags, long currentTime, UserHandle user)
7274            throws PackageManagerException {
7275        final File scanFile = new File(pkg.codePath);
7276        if (pkg.applicationInfo.getCodePath() == null ||
7277                pkg.applicationInfo.getResourcePath() == null) {
7278            // Bail out. The resource and code paths haven't been set.
7279            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7280                    "Code and resource paths haven't been set correctly");
7281        }
7282
7283        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7284            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7285        } else {
7286            // Only allow system apps to be flagged as core apps.
7287            pkg.coreApp = false;
7288        }
7289
7290        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7291            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7292        }
7293
7294        if (mCustomResolverComponentName != null &&
7295                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7296            setUpCustomResolverActivity(pkg);
7297        }
7298
7299        if (pkg.packageName.equals("android")) {
7300            synchronized (mPackages) {
7301                if (mAndroidApplication != null) {
7302                    Slog.w(TAG, "*************************************************");
7303                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7304                    Slog.w(TAG, " file=" + scanFile);
7305                    Slog.w(TAG, "*************************************************");
7306                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7307                            "Core android package being redefined.  Skipping.");
7308                }
7309
7310                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7311                    // Set up information for our fall-back user intent resolution activity.
7312                    mPlatformPackage = pkg;
7313                    pkg.mVersionCode = mSdkVersion;
7314                    mAndroidApplication = pkg.applicationInfo;
7315
7316                    if (!mResolverReplaced) {
7317                        mResolveActivity.applicationInfo = mAndroidApplication;
7318                        mResolveActivity.name = ResolverActivity.class.getName();
7319                        mResolveActivity.packageName = mAndroidApplication.packageName;
7320                        mResolveActivity.processName = "system:ui";
7321                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7322                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7323                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7324                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7325                        mResolveActivity.exported = true;
7326                        mResolveActivity.enabled = true;
7327                        mResolveInfo.activityInfo = mResolveActivity;
7328                        mResolveInfo.priority = 0;
7329                        mResolveInfo.preferredOrder = 0;
7330                        mResolveInfo.match = 0;
7331                        mResolveComponentName = new ComponentName(
7332                                mAndroidApplication.packageName, mResolveActivity.name);
7333                    }
7334                }
7335            }
7336        }
7337
7338        if (DEBUG_PACKAGE_SCANNING) {
7339            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7340                Log.d(TAG, "Scanning package " + pkg.packageName);
7341        }
7342
7343        synchronized (mPackages) {
7344            if (mPackages.containsKey(pkg.packageName)
7345                    || mSharedLibraries.containsKey(pkg.packageName)) {
7346                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7347                        "Application package " + pkg.packageName
7348                                + " already installed.  Skipping duplicate.");
7349            }
7350
7351            // If we're only installing presumed-existing packages, require that the
7352            // scanned APK is both already known and at the path previously established
7353            // for it.  Previously unknown packages we pick up normally, but if we have an
7354            // a priori expectation about this package's install presence, enforce it.
7355            // With a singular exception for new system packages. When an OTA contains
7356            // a new system package, we allow the codepath to change from a system location
7357            // to the user-installed location. If we don't allow this change, any newer,
7358            // user-installed version of the application will be ignored.
7359            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7360                if (mExpectingBetter.containsKey(pkg.packageName)) {
7361                    logCriticalInfo(Log.WARN,
7362                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7363                } else {
7364                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7365                    if (known != null) {
7366                        if (DEBUG_PACKAGE_SCANNING) {
7367                            Log.d(TAG, "Examining " + pkg.codePath
7368                                    + " and requiring known paths " + known.codePathString
7369                                    + " & " + known.resourcePathString);
7370                        }
7371                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7372                                || !pkg.applicationInfo.getResourcePath().equals(
7373                                known.resourcePathString)) {
7374                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7375                                    "Application package " + pkg.packageName
7376                                            + " found at " + pkg.applicationInfo.getCodePath()
7377                                            + " but expected at " + known.codePathString
7378                                            + "; ignoring.");
7379                        }
7380                    }
7381                }
7382            }
7383        }
7384
7385        // Initialize package source and resource directories
7386        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7387        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7388
7389        SharedUserSetting suid = null;
7390        PackageSetting pkgSetting = null;
7391
7392        if (!isSystemApp(pkg)) {
7393            // Only system apps can use these features.
7394            pkg.mOriginalPackages = null;
7395            pkg.mRealPackage = null;
7396            pkg.mAdoptPermissions = null;
7397        }
7398
7399        // Getting the package setting may have a side-effect, so if we
7400        // are only checking if scan would succeed, stash a copy of the
7401        // old setting to restore at the end.
7402        PackageSetting nonMutatedPs = null;
7403
7404        // writer
7405        synchronized (mPackages) {
7406            if (pkg.mSharedUserId != null) {
7407                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7408                if (suid == null) {
7409                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7410                            "Creating application package " + pkg.packageName
7411                            + " for shared user failed");
7412                }
7413                if (DEBUG_PACKAGE_SCANNING) {
7414                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7415                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7416                                + "): packages=" + suid.packages);
7417                }
7418            }
7419
7420            // Check if we are renaming from an original package name.
7421            PackageSetting origPackage = null;
7422            String realName = null;
7423            if (pkg.mOriginalPackages != null) {
7424                // This package may need to be renamed to a previously
7425                // installed name.  Let's check on that...
7426                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7427                if (pkg.mOriginalPackages.contains(renamed)) {
7428                    // This package had originally been installed as the
7429                    // original name, and we have already taken care of
7430                    // transitioning to the new one.  Just update the new
7431                    // one to continue using the old name.
7432                    realName = pkg.mRealPackage;
7433                    if (!pkg.packageName.equals(renamed)) {
7434                        // Callers into this function may have already taken
7435                        // care of renaming the package; only do it here if
7436                        // it is not already done.
7437                        pkg.setPackageName(renamed);
7438                    }
7439
7440                } else {
7441                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7442                        if ((origPackage = mSettings.peekPackageLPr(
7443                                pkg.mOriginalPackages.get(i))) != null) {
7444                            // We do have the package already installed under its
7445                            // original name...  should we use it?
7446                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7447                                // New package is not compatible with original.
7448                                origPackage = null;
7449                                continue;
7450                            } else if (origPackage.sharedUser != null) {
7451                                // Make sure uid is compatible between packages.
7452                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7453                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7454                                            + " to " + pkg.packageName + ": old uid "
7455                                            + origPackage.sharedUser.name
7456                                            + " differs from " + pkg.mSharedUserId);
7457                                    origPackage = null;
7458                                    continue;
7459                                }
7460                            } else {
7461                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7462                                        + pkg.packageName + " to old name " + origPackage.name);
7463                            }
7464                            break;
7465                        }
7466                    }
7467                }
7468            }
7469
7470            if (mTransferedPackages.contains(pkg.packageName)) {
7471                Slog.w(TAG, "Package " + pkg.packageName
7472                        + " was transferred to another, but its .apk remains");
7473            }
7474
7475            // See comments in nonMutatedPs declaration
7476            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7477                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7478                if (foundPs != null) {
7479                    nonMutatedPs = new PackageSetting(foundPs);
7480                }
7481            }
7482
7483            // Just create the setting, don't add it yet. For already existing packages
7484            // the PkgSetting exists already and doesn't have to be created.
7485            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7486                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7487                    pkg.applicationInfo.primaryCpuAbi,
7488                    pkg.applicationInfo.secondaryCpuAbi,
7489                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7490                    user, false);
7491            if (pkgSetting == null) {
7492                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7493                        "Creating application package " + pkg.packageName + " failed");
7494            }
7495
7496            if (pkgSetting.origPackage != null) {
7497                // If we are first transitioning from an original package,
7498                // fix up the new package's name now.  We need to do this after
7499                // looking up the package under its new name, so getPackageLP
7500                // can take care of fiddling things correctly.
7501                pkg.setPackageName(origPackage.name);
7502
7503                // File a report about this.
7504                String msg = "New package " + pkgSetting.realName
7505                        + " renamed to replace old package " + pkgSetting.name;
7506                reportSettingsProblem(Log.WARN, msg);
7507
7508                // Make a note of it.
7509                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7510                    mTransferedPackages.add(origPackage.name);
7511                }
7512
7513                // No longer need to retain this.
7514                pkgSetting.origPackage = null;
7515            }
7516
7517            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7518                // Make a note of it.
7519                mTransferedPackages.add(pkg.packageName);
7520            }
7521
7522            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7523                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7524            }
7525
7526            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7527                // Check all shared libraries and map to their actual file path.
7528                // We only do this here for apps not on a system dir, because those
7529                // are the only ones that can fail an install due to this.  We
7530                // will take care of the system apps by updating all of their
7531                // library paths after the scan is done.
7532                updateSharedLibrariesLPw(pkg, null);
7533            }
7534
7535            if (mFoundPolicyFile) {
7536                SELinuxMMAC.assignSeinfoValue(pkg);
7537            }
7538
7539            pkg.applicationInfo.uid = pkgSetting.appId;
7540            pkg.mExtras = pkgSetting;
7541            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7542                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7543                    // We just determined the app is signed correctly, so bring
7544                    // over the latest parsed certs.
7545                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7546                } else {
7547                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7548                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7549                                "Package " + pkg.packageName + " upgrade keys do not match the "
7550                                + "previously installed version");
7551                    } else {
7552                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7553                        String msg = "System package " + pkg.packageName
7554                            + " signature changed; retaining data.";
7555                        reportSettingsProblem(Log.WARN, msg);
7556                    }
7557                }
7558            } else {
7559                try {
7560                    verifySignaturesLP(pkgSetting, pkg);
7561                    // We just determined the app is signed correctly, so bring
7562                    // over the latest parsed certs.
7563                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7564                } catch (PackageManagerException e) {
7565                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7566                        throw e;
7567                    }
7568                    // The signature has changed, but this package is in the system
7569                    // image...  let's recover!
7570                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7571                    // However...  if this package is part of a shared user, but it
7572                    // doesn't match the signature of the shared user, let's fail.
7573                    // What this means is that you can't change the signatures
7574                    // associated with an overall shared user, which doesn't seem all
7575                    // that unreasonable.
7576                    if (pkgSetting.sharedUser != null) {
7577                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7578                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7579                            throw new PackageManagerException(
7580                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7581                                            "Signature mismatch for shared user: "
7582                                            + pkgSetting.sharedUser);
7583                        }
7584                    }
7585                    // File a report about this.
7586                    String msg = "System package " + pkg.packageName
7587                        + " signature changed; retaining data.";
7588                    reportSettingsProblem(Log.WARN, msg);
7589                }
7590            }
7591            // Verify that this new package doesn't have any content providers
7592            // that conflict with existing packages.  Only do this if the
7593            // package isn't already installed, since we don't want to break
7594            // things that are installed.
7595            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7596                final int N = pkg.providers.size();
7597                int i;
7598                for (i=0; i<N; i++) {
7599                    PackageParser.Provider p = pkg.providers.get(i);
7600                    if (p.info.authority != null) {
7601                        String names[] = p.info.authority.split(";");
7602                        for (int j = 0; j < names.length; j++) {
7603                            if (mProvidersByAuthority.containsKey(names[j])) {
7604                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7605                                final String otherPackageName =
7606                                        ((other != null && other.getComponentName() != null) ?
7607                                                other.getComponentName().getPackageName() : "?");
7608                                throw new PackageManagerException(
7609                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7610                                                "Can't install because provider name " + names[j]
7611                                                + " (in package " + pkg.applicationInfo.packageName
7612                                                + ") is already used by " + otherPackageName);
7613                            }
7614                        }
7615                    }
7616                }
7617            }
7618
7619            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7620                // This package wants to adopt ownership of permissions from
7621                // another package.
7622                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7623                    final String origName = pkg.mAdoptPermissions.get(i);
7624                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7625                    if (orig != null) {
7626                        if (verifyPackageUpdateLPr(orig, pkg)) {
7627                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7628                                    + pkg.packageName);
7629                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7630                        }
7631                    }
7632                }
7633            }
7634        }
7635
7636        final String pkgName = pkg.packageName;
7637
7638        final long scanFileTime = scanFile.lastModified();
7639        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7640        pkg.applicationInfo.processName = fixProcessName(
7641                pkg.applicationInfo.packageName,
7642                pkg.applicationInfo.processName,
7643                pkg.applicationInfo.uid);
7644
7645        if (pkg != mPlatformPackage) {
7646            // Get all of our default paths setup
7647            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7648        }
7649
7650        final String path = scanFile.getPath();
7651        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7652
7653        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7654            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7655
7656            // Some system apps still use directory structure for native libraries
7657            // in which case we might end up not detecting abi solely based on apk
7658            // structure. Try to detect abi based on directory structure.
7659            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7660                    pkg.applicationInfo.primaryCpuAbi == null) {
7661                setBundledAppAbisAndRoots(pkg, pkgSetting);
7662                setNativeLibraryPaths(pkg);
7663            }
7664
7665        } else {
7666            if ((scanFlags & SCAN_MOVE) != 0) {
7667                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7668                // but we already have this packages package info in the PackageSetting. We just
7669                // use that and derive the native library path based on the new codepath.
7670                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7671                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7672            }
7673
7674            // Set native library paths again. For moves, the path will be updated based on the
7675            // ABIs we've determined above. For non-moves, the path will be updated based on the
7676            // ABIs we determined during compilation, but the path will depend on the final
7677            // package path (after the rename away from the stage path).
7678            setNativeLibraryPaths(pkg);
7679        }
7680
7681        // This is a special case for the "system" package, where the ABI is
7682        // dictated by the zygote configuration (and init.rc). We should keep track
7683        // of this ABI so that we can deal with "normal" applications that run under
7684        // the same UID correctly.
7685        if (mPlatformPackage == pkg) {
7686            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7687                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7688        }
7689
7690        // If there's a mismatch between the abi-override in the package setting
7691        // and the abiOverride specified for the install. Warn about this because we
7692        // would've already compiled the app without taking the package setting into
7693        // account.
7694        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7695            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7696                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7697                        " for package " + pkg.packageName);
7698            }
7699        }
7700
7701        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7702        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7703        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7704
7705        // Copy the derived override back to the parsed package, so that we can
7706        // update the package settings accordingly.
7707        pkg.cpuAbiOverride = cpuAbiOverride;
7708
7709        if (DEBUG_ABI_SELECTION) {
7710            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7711                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7712                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7713        }
7714
7715        // Push the derived path down into PackageSettings so we know what to
7716        // clean up at uninstall time.
7717        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7718
7719        if (DEBUG_ABI_SELECTION) {
7720            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7721                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7722                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7723        }
7724
7725        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7726            // We don't do this here during boot because we can do it all
7727            // at once after scanning all existing packages.
7728            //
7729            // We also do this *before* we perform dexopt on this package, so that
7730            // we can avoid redundant dexopts, and also to make sure we've got the
7731            // code and package path correct.
7732            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7733                    pkg, true /* boot complete */);
7734        }
7735
7736        if (mFactoryTest && pkg.requestedPermissions.contains(
7737                android.Manifest.permission.FACTORY_TEST)) {
7738            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7739        }
7740
7741        ArrayList<PackageParser.Package> clientLibPkgs = null;
7742
7743        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7744            if (nonMutatedPs != null) {
7745                synchronized (mPackages) {
7746                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7747                }
7748            }
7749            return pkg;
7750        }
7751
7752        // Only privileged apps and updated privileged apps can add child packages.
7753        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7754            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7755                throw new PackageManagerException("Only privileged apps and updated "
7756                        + "privileged apps can add child packages. Ignoring package "
7757                        + pkg.packageName);
7758            }
7759            final int childCount = pkg.childPackages.size();
7760            for (int i = 0; i < childCount; i++) {
7761                PackageParser.Package childPkg = pkg.childPackages.get(i);
7762                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7763                        childPkg.packageName)) {
7764                    throw new PackageManagerException("Cannot override a child package of "
7765                            + "another disabled system app. Ignoring package " + pkg.packageName);
7766                }
7767            }
7768        }
7769
7770        // writer
7771        synchronized (mPackages) {
7772            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7773                // Only system apps can add new shared libraries.
7774                if (pkg.libraryNames != null) {
7775                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7776                        String name = pkg.libraryNames.get(i);
7777                        boolean allowed = false;
7778                        if (pkg.isUpdatedSystemApp()) {
7779                            // New library entries can only be added through the
7780                            // system image.  This is important to get rid of a lot
7781                            // of nasty edge cases: for example if we allowed a non-
7782                            // system update of the app to add a library, then uninstalling
7783                            // the update would make the library go away, and assumptions
7784                            // we made such as through app install filtering would now
7785                            // have allowed apps on the device which aren't compatible
7786                            // with it.  Better to just have the restriction here, be
7787                            // conservative, and create many fewer cases that can negatively
7788                            // impact the user experience.
7789                            final PackageSetting sysPs = mSettings
7790                                    .getDisabledSystemPkgLPr(pkg.packageName);
7791                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7792                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7793                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7794                                        allowed = true;
7795                                        break;
7796                                    }
7797                                }
7798                            }
7799                        } else {
7800                            allowed = true;
7801                        }
7802                        if (allowed) {
7803                            if (!mSharedLibraries.containsKey(name)) {
7804                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7805                            } else if (!name.equals(pkg.packageName)) {
7806                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7807                                        + name + " already exists; skipping");
7808                            }
7809                        } else {
7810                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7811                                    + name + " that is not declared on system image; skipping");
7812                        }
7813                    }
7814                    if ((scanFlags & SCAN_BOOTING) == 0) {
7815                        // If we are not booting, we need to update any applications
7816                        // that are clients of our shared library.  If we are booting,
7817                        // this will all be done once the scan is complete.
7818                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7819                    }
7820                }
7821            }
7822        }
7823
7824        // Request the ActivityManager to kill the process(only for existing packages)
7825        // so that we do not end up in a confused state while the user is still using the older
7826        // version of the application while the new one gets installed.
7827        if ((scanFlags & SCAN_REPLACING) != 0) {
7828            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7829
7830            killApplication(pkg.applicationInfo.packageName,
7831                        pkg.applicationInfo.uid, "replace pkg");
7832
7833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7834        }
7835
7836        // Also need to kill any apps that are dependent on the library.
7837        if (clientLibPkgs != null) {
7838            for (int i=0; i<clientLibPkgs.size(); i++) {
7839                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7840                killApplication(clientPkg.applicationInfo.packageName,
7841                        clientPkg.applicationInfo.uid, "update lib");
7842            }
7843        }
7844
7845        // Make sure we're not adding any bogus keyset info
7846        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7847        ksms.assertScannedPackageValid(pkg);
7848
7849        // writer
7850        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7851
7852        boolean createIdmapFailed = false;
7853        synchronized (mPackages) {
7854            // We don't expect installation to fail beyond this point
7855
7856            // Add the new setting to mSettings
7857            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7858            // Add the new setting to mPackages
7859            mPackages.put(pkg.applicationInfo.packageName, pkg);
7860            // Make sure we don't accidentally delete its data.
7861            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7862            while (iter.hasNext()) {
7863                PackageCleanItem item = iter.next();
7864                if (pkgName.equals(item.packageName)) {
7865                    iter.remove();
7866                }
7867            }
7868
7869            // Take care of first install / last update times.
7870            if (currentTime != 0) {
7871                if (pkgSetting.firstInstallTime == 0) {
7872                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7873                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7874                    pkgSetting.lastUpdateTime = currentTime;
7875                }
7876            } else if (pkgSetting.firstInstallTime == 0) {
7877                // We need *something*.  Take time time stamp of the file.
7878                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7879            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7880                if (scanFileTime != pkgSetting.timeStamp) {
7881                    // A package on the system image has changed; consider this
7882                    // to be an update.
7883                    pkgSetting.lastUpdateTime = scanFileTime;
7884                }
7885            }
7886
7887            // Add the package's KeySets to the global KeySetManagerService
7888            ksms.addScannedPackageLPw(pkg);
7889
7890            int N = pkg.providers.size();
7891            StringBuilder r = null;
7892            int i;
7893            for (i=0; i<N; i++) {
7894                PackageParser.Provider p = pkg.providers.get(i);
7895                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7896                        p.info.processName, pkg.applicationInfo.uid);
7897                mProviders.addProvider(p);
7898                p.syncable = p.info.isSyncable;
7899                if (p.info.authority != null) {
7900                    String names[] = p.info.authority.split(";");
7901                    p.info.authority = null;
7902                    for (int j = 0; j < names.length; j++) {
7903                        if (j == 1 && p.syncable) {
7904                            // We only want the first authority for a provider to possibly be
7905                            // syncable, so if we already added this provider using a different
7906                            // authority clear the syncable flag. We copy the provider before
7907                            // changing it because the mProviders object contains a reference
7908                            // to a provider that we don't want to change.
7909                            // Only do this for the second authority since the resulting provider
7910                            // object can be the same for all future authorities for this provider.
7911                            p = new PackageParser.Provider(p);
7912                            p.syncable = false;
7913                        }
7914                        if (!mProvidersByAuthority.containsKey(names[j])) {
7915                            mProvidersByAuthority.put(names[j], p);
7916                            if (p.info.authority == null) {
7917                                p.info.authority = names[j];
7918                            } else {
7919                                p.info.authority = p.info.authority + ";" + names[j];
7920                            }
7921                            if (DEBUG_PACKAGE_SCANNING) {
7922                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7923                                    Log.d(TAG, "Registered content provider: " + names[j]
7924                                            + ", className = " + p.info.name + ", isSyncable = "
7925                                            + p.info.isSyncable);
7926                            }
7927                        } else {
7928                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7929                            Slog.w(TAG, "Skipping provider name " + names[j] +
7930                                    " (in package " + pkg.applicationInfo.packageName +
7931                                    "): name already used by "
7932                                    + ((other != null && other.getComponentName() != null)
7933                                            ? other.getComponentName().getPackageName() : "?"));
7934                        }
7935                    }
7936                }
7937                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7938                    if (r == null) {
7939                        r = new StringBuilder(256);
7940                    } else {
7941                        r.append(' ');
7942                    }
7943                    r.append(p.info.name);
7944                }
7945            }
7946            if (r != null) {
7947                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7948            }
7949
7950            N = pkg.services.size();
7951            r = null;
7952            for (i=0; i<N; i++) {
7953                PackageParser.Service s = pkg.services.get(i);
7954                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7955                        s.info.processName, pkg.applicationInfo.uid);
7956                mServices.addService(s);
7957                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7958                    if (r == null) {
7959                        r = new StringBuilder(256);
7960                    } else {
7961                        r.append(' ');
7962                    }
7963                    r.append(s.info.name);
7964                }
7965            }
7966            if (r != null) {
7967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7968            }
7969
7970            N = pkg.receivers.size();
7971            r = null;
7972            for (i=0; i<N; i++) {
7973                PackageParser.Activity a = pkg.receivers.get(i);
7974                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7975                        a.info.processName, pkg.applicationInfo.uid);
7976                mReceivers.addActivity(a, "receiver");
7977                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7978                    if (r == null) {
7979                        r = new StringBuilder(256);
7980                    } else {
7981                        r.append(' ');
7982                    }
7983                    r.append(a.info.name);
7984                }
7985            }
7986            if (r != null) {
7987                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7988            }
7989
7990            N = pkg.activities.size();
7991            r = null;
7992            for (i=0; i<N; i++) {
7993                PackageParser.Activity a = pkg.activities.get(i);
7994                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7995                        a.info.processName, pkg.applicationInfo.uid);
7996                mActivities.addActivity(a, "activity");
7997                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7998                    if (r == null) {
7999                        r = new StringBuilder(256);
8000                    } else {
8001                        r.append(' ');
8002                    }
8003                    r.append(a.info.name);
8004                }
8005            }
8006            if (r != null) {
8007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8008            }
8009
8010            N = pkg.permissionGroups.size();
8011            r = null;
8012            for (i=0; i<N; i++) {
8013                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8014                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8015                if (cur == null) {
8016                    mPermissionGroups.put(pg.info.name, pg);
8017                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8018                        if (r == null) {
8019                            r = new StringBuilder(256);
8020                        } else {
8021                            r.append(' ');
8022                        }
8023                        r.append(pg.info.name);
8024                    }
8025                } else {
8026                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8027                            + pg.info.packageName + " ignored: original from "
8028                            + cur.info.packageName);
8029                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8030                        if (r == null) {
8031                            r = new StringBuilder(256);
8032                        } else {
8033                            r.append(' ');
8034                        }
8035                        r.append("DUP:");
8036                        r.append(pg.info.name);
8037                    }
8038                }
8039            }
8040            if (r != null) {
8041                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8042            }
8043
8044            N = pkg.permissions.size();
8045            r = null;
8046            for (i=0; i<N; i++) {
8047                PackageParser.Permission p = pkg.permissions.get(i);
8048
8049                // Assume by default that we did not install this permission into the system.
8050                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8051
8052                // Now that permission groups have a special meaning, we ignore permission
8053                // groups for legacy apps to prevent unexpected behavior. In particular,
8054                // permissions for one app being granted to someone just becase they happen
8055                // to be in a group defined by another app (before this had no implications).
8056                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8057                    p.group = mPermissionGroups.get(p.info.group);
8058                    // Warn for a permission in an unknown group.
8059                    if (p.info.group != null && p.group == null) {
8060                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8061                                + p.info.packageName + " in an unknown group " + p.info.group);
8062                    }
8063                }
8064
8065                ArrayMap<String, BasePermission> permissionMap =
8066                        p.tree ? mSettings.mPermissionTrees
8067                                : mSettings.mPermissions;
8068                BasePermission bp = permissionMap.get(p.info.name);
8069
8070                // Allow system apps to redefine non-system permissions
8071                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8072                    final boolean currentOwnerIsSystem = (bp.perm != null
8073                            && isSystemApp(bp.perm.owner));
8074                    if (isSystemApp(p.owner)) {
8075                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8076                            // It's a built-in permission and no owner, take ownership now
8077                            bp.packageSetting = pkgSetting;
8078                            bp.perm = p;
8079                            bp.uid = pkg.applicationInfo.uid;
8080                            bp.sourcePackage = p.info.packageName;
8081                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8082                        } else if (!currentOwnerIsSystem) {
8083                            String msg = "New decl " + p.owner + " of permission  "
8084                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8085                            reportSettingsProblem(Log.WARN, msg);
8086                            bp = null;
8087                        }
8088                    }
8089                }
8090
8091                if (bp == null) {
8092                    bp = new BasePermission(p.info.name, p.info.packageName,
8093                            BasePermission.TYPE_NORMAL);
8094                    permissionMap.put(p.info.name, bp);
8095                }
8096
8097                if (bp.perm == null) {
8098                    if (bp.sourcePackage == null
8099                            || bp.sourcePackage.equals(p.info.packageName)) {
8100                        BasePermission tree = findPermissionTreeLP(p.info.name);
8101                        if (tree == null
8102                                || tree.sourcePackage.equals(p.info.packageName)) {
8103                            bp.packageSetting = pkgSetting;
8104                            bp.perm = p;
8105                            bp.uid = pkg.applicationInfo.uid;
8106                            bp.sourcePackage = p.info.packageName;
8107                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8108                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8109                                if (r == null) {
8110                                    r = new StringBuilder(256);
8111                                } else {
8112                                    r.append(' ');
8113                                }
8114                                r.append(p.info.name);
8115                            }
8116                        } else {
8117                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8118                                    + p.info.packageName + " ignored: base tree "
8119                                    + tree.name + " is from package "
8120                                    + tree.sourcePackage);
8121                        }
8122                    } else {
8123                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8124                                + p.info.packageName + " ignored: original from "
8125                                + bp.sourcePackage);
8126                    }
8127                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8128                    if (r == null) {
8129                        r = new StringBuilder(256);
8130                    } else {
8131                        r.append(' ');
8132                    }
8133                    r.append("DUP:");
8134                    r.append(p.info.name);
8135                }
8136                if (bp.perm == p) {
8137                    bp.protectionLevel = p.info.protectionLevel;
8138                }
8139            }
8140
8141            if (r != null) {
8142                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8143            }
8144
8145            N = pkg.instrumentation.size();
8146            r = null;
8147            for (i=0; i<N; i++) {
8148                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8149                a.info.packageName = pkg.applicationInfo.packageName;
8150                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8151                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8152                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8153                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8154                a.info.dataDir = pkg.applicationInfo.dataDir;
8155                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8156                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8157
8158                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8159                // need other information about the application, like the ABI and what not ?
8160                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8161                mInstrumentation.put(a.getComponentName(), a);
8162                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8163                    if (r == null) {
8164                        r = new StringBuilder(256);
8165                    } else {
8166                        r.append(' ');
8167                    }
8168                    r.append(a.info.name);
8169                }
8170            }
8171            if (r != null) {
8172                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8173            }
8174
8175            if (pkg.protectedBroadcasts != null) {
8176                N = pkg.protectedBroadcasts.size();
8177                for (i=0; i<N; i++) {
8178                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8179                }
8180            }
8181
8182            pkgSetting.setTimeStamp(scanFileTime);
8183
8184            // Create idmap files for pairs of (packages, overlay packages).
8185            // Note: "android", ie framework-res.apk, is handled by native layers.
8186            if (pkg.mOverlayTarget != null) {
8187                // This is an overlay package.
8188                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8189                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8190                        mOverlays.put(pkg.mOverlayTarget,
8191                                new ArrayMap<String, PackageParser.Package>());
8192                    }
8193                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8194                    map.put(pkg.packageName, pkg);
8195                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8196                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8197                        createIdmapFailed = true;
8198                    }
8199                }
8200            } else if (mOverlays.containsKey(pkg.packageName) &&
8201                    !pkg.packageName.equals("android")) {
8202                // This is a regular package, with one or more known overlay packages.
8203                createIdmapsForPackageLI(pkg);
8204            }
8205        }
8206
8207        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8208
8209        if (createIdmapFailed) {
8210            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8211                    "scanPackageLI failed to createIdmap");
8212        }
8213        return pkg;
8214    }
8215
8216    /**
8217     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8218     * is derived purely on the basis of the contents of {@code scanFile} and
8219     * {@code cpuAbiOverride}.
8220     *
8221     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8222     */
8223    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8224                                 String cpuAbiOverride, boolean extractLibs)
8225            throws PackageManagerException {
8226        // TODO: We can probably be smarter about this stuff. For installed apps,
8227        // we can calculate this information at install time once and for all. For
8228        // system apps, we can probably assume that this information doesn't change
8229        // after the first boot scan. As things stand, we do lots of unnecessary work.
8230
8231        // Give ourselves some initial paths; we'll come back for another
8232        // pass once we've determined ABI below.
8233        setNativeLibraryPaths(pkg);
8234
8235        // We would never need to extract libs for forward-locked and external packages,
8236        // since the container service will do it for us. We shouldn't attempt to
8237        // extract libs from system app when it was not updated.
8238        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8239                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8240            extractLibs = false;
8241        }
8242
8243        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8244        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8245
8246        NativeLibraryHelper.Handle handle = null;
8247        try {
8248            handle = NativeLibraryHelper.Handle.create(pkg);
8249            // TODO(multiArch): This can be null for apps that didn't go through the
8250            // usual installation process. We can calculate it again, like we
8251            // do during install time.
8252            //
8253            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8254            // unnecessary.
8255            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8256
8257            // Null out the abis so that they can be recalculated.
8258            pkg.applicationInfo.primaryCpuAbi = null;
8259            pkg.applicationInfo.secondaryCpuAbi = null;
8260            if (isMultiArch(pkg.applicationInfo)) {
8261                // Warn if we've set an abiOverride for multi-lib packages..
8262                // By definition, we need to copy both 32 and 64 bit libraries for
8263                // such packages.
8264                if (pkg.cpuAbiOverride != null
8265                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8266                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8267                }
8268
8269                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8270                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8271                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8272                    if (extractLibs) {
8273                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8274                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8275                                useIsaSpecificSubdirs);
8276                    } else {
8277                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8278                    }
8279                }
8280
8281                maybeThrowExceptionForMultiArchCopy(
8282                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8283
8284                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8285                    if (extractLibs) {
8286                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8287                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8288                                useIsaSpecificSubdirs);
8289                    } else {
8290                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8291                    }
8292                }
8293
8294                maybeThrowExceptionForMultiArchCopy(
8295                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8296
8297                if (abi64 >= 0) {
8298                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8299                }
8300
8301                if (abi32 >= 0) {
8302                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8303                    if (abi64 >= 0) {
8304                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8305                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8306                            pkg.applicationInfo.primaryCpuAbi = abi;
8307                        } else {
8308                            pkg.applicationInfo.secondaryCpuAbi = abi;
8309                        }
8310                    } else {
8311                        pkg.applicationInfo.primaryCpuAbi = abi;
8312                    }
8313                }
8314
8315            } else {
8316                String[] abiList = (cpuAbiOverride != null) ?
8317                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8318
8319                // Enable gross and lame hacks for apps that are built with old
8320                // SDK tools. We must scan their APKs for renderscript bitcode and
8321                // not launch them if it's present. Don't bother checking on devices
8322                // that don't have 64 bit support.
8323                boolean needsRenderScriptOverride = false;
8324                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8325                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8326                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8327                    needsRenderScriptOverride = true;
8328                }
8329
8330                final int copyRet;
8331                if (extractLibs) {
8332                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8333                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8334                } else {
8335                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8336                }
8337
8338                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8339                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8340                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8341                }
8342
8343                if (copyRet >= 0) {
8344                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8345                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8346                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8347                } else if (needsRenderScriptOverride) {
8348                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8349                }
8350            }
8351        } catch (IOException ioe) {
8352            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8353        } finally {
8354            IoUtils.closeQuietly(handle);
8355        }
8356
8357        // Now that we've calculated the ABIs and determined if it's an internal app,
8358        // we will go ahead and populate the nativeLibraryPath.
8359        setNativeLibraryPaths(pkg);
8360    }
8361
8362    /**
8363     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8364     * i.e, so that all packages can be run inside a single process if required.
8365     *
8366     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8367     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8368     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8369     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8370     * updating a package that belongs to a shared user.
8371     *
8372     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8373     * adds unnecessary complexity.
8374     */
8375    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8376            PackageParser.Package scannedPackage, boolean bootComplete) {
8377        String requiredInstructionSet = null;
8378        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8379            requiredInstructionSet = VMRuntime.getInstructionSet(
8380                     scannedPackage.applicationInfo.primaryCpuAbi);
8381        }
8382
8383        PackageSetting requirer = null;
8384        for (PackageSetting ps : packagesForUser) {
8385            // If packagesForUser contains scannedPackage, we skip it. This will happen
8386            // when scannedPackage is an update of an existing package. Without this check,
8387            // we will never be able to change the ABI of any package belonging to a shared
8388            // user, even if it's compatible with other packages.
8389            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8390                if (ps.primaryCpuAbiString == null) {
8391                    continue;
8392                }
8393
8394                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8395                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8396                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8397                    // this but there's not much we can do.
8398                    String errorMessage = "Instruction set mismatch, "
8399                            + ((requirer == null) ? "[caller]" : requirer)
8400                            + " requires " + requiredInstructionSet + " whereas " + ps
8401                            + " requires " + instructionSet;
8402                    Slog.w(TAG, errorMessage);
8403                }
8404
8405                if (requiredInstructionSet == null) {
8406                    requiredInstructionSet = instructionSet;
8407                    requirer = ps;
8408                }
8409            }
8410        }
8411
8412        if (requiredInstructionSet != null) {
8413            String adjustedAbi;
8414            if (requirer != null) {
8415                // requirer != null implies that either scannedPackage was null or that scannedPackage
8416                // did not require an ABI, in which case we have to adjust scannedPackage to match
8417                // the ABI of the set (which is the same as requirer's ABI)
8418                adjustedAbi = requirer.primaryCpuAbiString;
8419                if (scannedPackage != null) {
8420                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8421                }
8422            } else {
8423                // requirer == null implies that we're updating all ABIs in the set to
8424                // match scannedPackage.
8425                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8426            }
8427
8428            for (PackageSetting ps : packagesForUser) {
8429                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8430                    if (ps.primaryCpuAbiString != null) {
8431                        continue;
8432                    }
8433
8434                    ps.primaryCpuAbiString = adjustedAbi;
8435                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8436                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8437                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8438                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8439                                + " (requirer="
8440                                + (requirer == null ? "null" : requirer.pkg.packageName)
8441                                + ", scannedPackage="
8442                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8443                                + ")");
8444                        try {
8445                            mInstaller.rmdex(ps.codePathString,
8446                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8447                        } catch (InstallerException ignored) {
8448                        }
8449                    }
8450                }
8451            }
8452        }
8453    }
8454
8455    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8456        synchronized (mPackages) {
8457            mResolverReplaced = true;
8458            // Set up information for custom user intent resolution activity.
8459            mResolveActivity.applicationInfo = pkg.applicationInfo;
8460            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8461            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8462            mResolveActivity.processName = pkg.applicationInfo.packageName;
8463            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8464            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8465                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8466            mResolveActivity.theme = 0;
8467            mResolveActivity.exported = true;
8468            mResolveActivity.enabled = true;
8469            mResolveInfo.activityInfo = mResolveActivity;
8470            mResolveInfo.priority = 0;
8471            mResolveInfo.preferredOrder = 0;
8472            mResolveInfo.match = 0;
8473            mResolveComponentName = mCustomResolverComponentName;
8474            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8475                    mResolveComponentName);
8476        }
8477    }
8478
8479    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8480        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8481
8482        // Set up information for ephemeral installer activity
8483        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8484        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8485        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8486        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8487        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8488        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8489                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8490        mEphemeralInstallerActivity.theme = 0;
8491        mEphemeralInstallerActivity.exported = true;
8492        mEphemeralInstallerActivity.enabled = true;
8493        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8494        mEphemeralInstallerInfo.priority = 0;
8495        mEphemeralInstallerInfo.preferredOrder = 0;
8496        mEphemeralInstallerInfo.match = 0;
8497
8498        if (DEBUG_EPHEMERAL) {
8499            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8500        }
8501    }
8502
8503    private static String calculateBundledApkRoot(final String codePathString) {
8504        final File codePath = new File(codePathString);
8505        final File codeRoot;
8506        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8507            codeRoot = Environment.getRootDirectory();
8508        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8509            codeRoot = Environment.getOemDirectory();
8510        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8511            codeRoot = Environment.getVendorDirectory();
8512        } else {
8513            // Unrecognized code path; take its top real segment as the apk root:
8514            // e.g. /something/app/blah.apk => /something
8515            try {
8516                File f = codePath.getCanonicalFile();
8517                File parent = f.getParentFile();    // non-null because codePath is a file
8518                File tmp;
8519                while ((tmp = parent.getParentFile()) != null) {
8520                    f = parent;
8521                    parent = tmp;
8522                }
8523                codeRoot = f;
8524                Slog.w(TAG, "Unrecognized code path "
8525                        + codePath + " - using " + codeRoot);
8526            } catch (IOException e) {
8527                // Can't canonicalize the code path -- shenanigans?
8528                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8529                return Environment.getRootDirectory().getPath();
8530            }
8531        }
8532        return codeRoot.getPath();
8533    }
8534
8535    /**
8536     * Derive and set the location of native libraries for the given package,
8537     * which varies depending on where and how the package was installed.
8538     */
8539    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8540        final ApplicationInfo info = pkg.applicationInfo;
8541        final String codePath = pkg.codePath;
8542        final File codeFile = new File(codePath);
8543        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8544        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8545
8546        info.nativeLibraryRootDir = null;
8547        info.nativeLibraryRootRequiresIsa = false;
8548        info.nativeLibraryDir = null;
8549        info.secondaryNativeLibraryDir = null;
8550
8551        if (isApkFile(codeFile)) {
8552            // Monolithic install
8553            if (bundledApp) {
8554                // If "/system/lib64/apkname" exists, assume that is the per-package
8555                // native library directory to use; otherwise use "/system/lib/apkname".
8556                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8557                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8558                        getPrimaryInstructionSet(info));
8559
8560                // This is a bundled system app so choose the path based on the ABI.
8561                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8562                // is just the default path.
8563                final String apkName = deriveCodePathName(codePath);
8564                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8565                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8566                        apkName).getAbsolutePath();
8567
8568                if (info.secondaryCpuAbi != null) {
8569                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8570                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8571                            secondaryLibDir, apkName).getAbsolutePath();
8572                }
8573            } else if (asecApp) {
8574                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8575                        .getAbsolutePath();
8576            } else {
8577                final String apkName = deriveCodePathName(codePath);
8578                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8579                        .getAbsolutePath();
8580            }
8581
8582            info.nativeLibraryRootRequiresIsa = false;
8583            info.nativeLibraryDir = info.nativeLibraryRootDir;
8584        } else {
8585            // Cluster install
8586            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8587            info.nativeLibraryRootRequiresIsa = true;
8588
8589            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8590                    getPrimaryInstructionSet(info)).getAbsolutePath();
8591
8592            if (info.secondaryCpuAbi != null) {
8593                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8594                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8595            }
8596        }
8597    }
8598
8599    /**
8600     * Calculate the abis and roots for a bundled app. These can uniquely
8601     * be determined from the contents of the system partition, i.e whether
8602     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8603     * of this information, and instead assume that the system was built
8604     * sensibly.
8605     */
8606    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8607                                           PackageSetting pkgSetting) {
8608        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8609
8610        // If "/system/lib64/apkname" exists, assume that is the per-package
8611        // native library directory to use; otherwise use "/system/lib/apkname".
8612        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8613        setBundledAppAbi(pkg, apkRoot, apkName);
8614        // pkgSetting might be null during rescan following uninstall of updates
8615        // to a bundled app, so accommodate that possibility.  The settings in
8616        // that case will be established later from the parsed package.
8617        //
8618        // If the settings aren't null, sync them up with what we've just derived.
8619        // note that apkRoot isn't stored in the package settings.
8620        if (pkgSetting != null) {
8621            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8622            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8623        }
8624    }
8625
8626    /**
8627     * Deduces the ABI of a bundled app and sets the relevant fields on the
8628     * parsed pkg object.
8629     *
8630     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8631     *        under which system libraries are installed.
8632     * @param apkName the name of the installed package.
8633     */
8634    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8635        final File codeFile = new File(pkg.codePath);
8636
8637        final boolean has64BitLibs;
8638        final boolean has32BitLibs;
8639        if (isApkFile(codeFile)) {
8640            // Monolithic install
8641            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8642            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8643        } else {
8644            // Cluster install
8645            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8646            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8647                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8648                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8649                has64BitLibs = (new File(rootDir, isa)).exists();
8650            } else {
8651                has64BitLibs = false;
8652            }
8653            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8654                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8655                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8656                has32BitLibs = (new File(rootDir, isa)).exists();
8657            } else {
8658                has32BitLibs = false;
8659            }
8660        }
8661
8662        if (has64BitLibs && !has32BitLibs) {
8663            // The package has 64 bit libs, but not 32 bit libs. Its primary
8664            // ABI should be 64 bit. We can safely assume here that the bundled
8665            // native libraries correspond to the most preferred ABI in the list.
8666
8667            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8668            pkg.applicationInfo.secondaryCpuAbi = null;
8669        } else if (has32BitLibs && !has64BitLibs) {
8670            // The package has 32 bit libs but not 64 bit libs. Its primary
8671            // ABI should be 32 bit.
8672
8673            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8674            pkg.applicationInfo.secondaryCpuAbi = null;
8675        } else if (has32BitLibs && has64BitLibs) {
8676            // The application has both 64 and 32 bit bundled libraries. We check
8677            // here that the app declares multiArch support, and warn if it doesn't.
8678            //
8679            // We will be lenient here and record both ABIs. The primary will be the
8680            // ABI that's higher on the list, i.e, a device that's configured to prefer
8681            // 64 bit apps will see a 64 bit primary ABI,
8682
8683            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8684                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8685            }
8686
8687            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8688                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8689                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8690            } else {
8691                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8692                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8693            }
8694        } else {
8695            pkg.applicationInfo.primaryCpuAbi = null;
8696            pkg.applicationInfo.secondaryCpuAbi = null;
8697        }
8698    }
8699
8700    private void killPackage(PackageParser.Package pkg, String reason) {
8701        // Kill the parent package
8702        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8703        // Kill the child packages
8704        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8705        for (int i = 0; i < childCount; i++) {
8706            PackageParser.Package childPkg = pkg.childPackages.get(i);
8707            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8708        }
8709    }
8710
8711    private void killApplication(String pkgName, int appId, String reason) {
8712        // Request the ActivityManager to kill the process(only for existing packages)
8713        // so that we do not end up in a confused state while the user is still using the older
8714        // version of the application while the new one gets installed.
8715        IActivityManager am = ActivityManagerNative.getDefault();
8716        if (am != null) {
8717            try {
8718                am.killApplicationWithAppId(pkgName, appId, reason);
8719            } catch (RemoteException e) {
8720            }
8721        }
8722    }
8723
8724    private void removePackageSettingLI(PackageParser.Package pkg, boolean chatty) {
8725        // Remove the parent package setting
8726        PackageSetting ps = (PackageSetting) pkg.mExtras;
8727        if (ps != null) {
8728            removePackageSettingLI(ps, chatty);
8729        }
8730        // Remove the child package setting
8731        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8732        for (int i = 0; i < childCount; i++) {
8733            PackageParser.Package childPkg = pkg.childPackages.get(i);
8734            ps = (PackageSetting) childPkg.mExtras;
8735            if (ps != null) {
8736                removePackageSettingLI(ps, chatty);
8737            }
8738        }
8739    }
8740
8741    void removePackageSettingLI(PackageSetting ps, boolean chatty) {
8742        if (DEBUG_INSTALL) {
8743            if (chatty)
8744                Log.d(TAG, "Removing package " + ps.name);
8745        }
8746
8747        // writer
8748        synchronized (mPackages) {
8749            mPackages.remove(ps.name);
8750            final PackageParser.Package pkg = ps.pkg;
8751            if (pkg != null) {
8752                cleanPackageDataStructuresLILPw(pkg, chatty);
8753            }
8754        }
8755    }
8756
8757    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8758        if (DEBUG_INSTALL) {
8759            if (chatty)
8760                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8761        }
8762
8763        // writer
8764        synchronized (mPackages) {
8765            // Remove the parent package
8766            mPackages.remove(pkg.applicationInfo.packageName);
8767            cleanPackageDataStructuresLILPw(pkg, chatty);
8768
8769            // Remove the child packages
8770            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8771            for (int i = 0; i < childCount; i++) {
8772                PackageParser.Package childPkg = pkg.childPackages.get(i);
8773                mPackages.remove(childPkg.applicationInfo.packageName);
8774                cleanPackageDataStructuresLILPw(childPkg, chatty);
8775            }
8776        }
8777    }
8778
8779    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8780        int N = pkg.providers.size();
8781        StringBuilder r = null;
8782        int i;
8783        for (i=0; i<N; i++) {
8784            PackageParser.Provider p = pkg.providers.get(i);
8785            mProviders.removeProvider(p);
8786            if (p.info.authority == null) {
8787
8788                /* There was another ContentProvider with this authority when
8789                 * this app was installed so this authority is null,
8790                 * Ignore it as we don't have to unregister the provider.
8791                 */
8792                continue;
8793            }
8794            String names[] = p.info.authority.split(";");
8795            for (int j = 0; j < names.length; j++) {
8796                if (mProvidersByAuthority.get(names[j]) == p) {
8797                    mProvidersByAuthority.remove(names[j]);
8798                    if (DEBUG_REMOVE) {
8799                        if (chatty)
8800                            Log.d(TAG, "Unregistered content provider: " + names[j]
8801                                    + ", className = " + p.info.name + ", isSyncable = "
8802                                    + p.info.isSyncable);
8803                    }
8804                }
8805            }
8806            if (DEBUG_REMOVE && chatty) {
8807                if (r == null) {
8808                    r = new StringBuilder(256);
8809                } else {
8810                    r.append(' ');
8811                }
8812                r.append(p.info.name);
8813            }
8814        }
8815        if (r != null) {
8816            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8817        }
8818
8819        N = pkg.services.size();
8820        r = null;
8821        for (i=0; i<N; i++) {
8822            PackageParser.Service s = pkg.services.get(i);
8823            mServices.removeService(s);
8824            if (chatty) {
8825                if (r == null) {
8826                    r = new StringBuilder(256);
8827                } else {
8828                    r.append(' ');
8829                }
8830                r.append(s.info.name);
8831            }
8832        }
8833        if (r != null) {
8834            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8835        }
8836
8837        N = pkg.receivers.size();
8838        r = null;
8839        for (i=0; i<N; i++) {
8840            PackageParser.Activity a = pkg.receivers.get(i);
8841            mReceivers.removeActivity(a, "receiver");
8842            if (DEBUG_REMOVE && chatty) {
8843                if (r == null) {
8844                    r = new StringBuilder(256);
8845                } else {
8846                    r.append(' ');
8847                }
8848                r.append(a.info.name);
8849            }
8850        }
8851        if (r != null) {
8852            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8853        }
8854
8855        N = pkg.activities.size();
8856        r = null;
8857        for (i=0; i<N; i++) {
8858            PackageParser.Activity a = pkg.activities.get(i);
8859            mActivities.removeActivity(a, "activity");
8860            if (DEBUG_REMOVE && chatty) {
8861                if (r == null) {
8862                    r = new StringBuilder(256);
8863                } else {
8864                    r.append(' ');
8865                }
8866                r.append(a.info.name);
8867            }
8868        }
8869        if (r != null) {
8870            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8871        }
8872
8873        N = pkg.permissions.size();
8874        r = null;
8875        for (i=0; i<N; i++) {
8876            PackageParser.Permission p = pkg.permissions.get(i);
8877            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8878            if (bp == null) {
8879                bp = mSettings.mPermissionTrees.get(p.info.name);
8880            }
8881            if (bp != null && bp.perm == p) {
8882                bp.perm = null;
8883                if (DEBUG_REMOVE && chatty) {
8884                    if (r == null) {
8885                        r = new StringBuilder(256);
8886                    } else {
8887                        r.append(' ');
8888                    }
8889                    r.append(p.info.name);
8890                }
8891            }
8892            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8893                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8894                if (appOpPkgs != null) {
8895                    appOpPkgs.remove(pkg.packageName);
8896                }
8897            }
8898        }
8899        if (r != null) {
8900            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8901        }
8902
8903        N = pkg.requestedPermissions.size();
8904        r = null;
8905        for (i=0; i<N; i++) {
8906            String perm = pkg.requestedPermissions.get(i);
8907            BasePermission bp = mSettings.mPermissions.get(perm);
8908            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8909                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8910                if (appOpPkgs != null) {
8911                    appOpPkgs.remove(pkg.packageName);
8912                    if (appOpPkgs.isEmpty()) {
8913                        mAppOpPermissionPackages.remove(perm);
8914                    }
8915                }
8916            }
8917        }
8918        if (r != null) {
8919            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8920        }
8921
8922        N = pkg.instrumentation.size();
8923        r = null;
8924        for (i=0; i<N; i++) {
8925            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8926            mInstrumentation.remove(a.getComponentName());
8927            if (DEBUG_REMOVE && chatty) {
8928                if (r == null) {
8929                    r = new StringBuilder(256);
8930                } else {
8931                    r.append(' ');
8932                }
8933                r.append(a.info.name);
8934            }
8935        }
8936        if (r != null) {
8937            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8938        }
8939
8940        r = null;
8941        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8942            // Only system apps can hold shared libraries.
8943            if (pkg.libraryNames != null) {
8944                for (i=0; i<pkg.libraryNames.size(); i++) {
8945                    String name = pkg.libraryNames.get(i);
8946                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8947                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8948                        mSharedLibraries.remove(name);
8949                        if (DEBUG_REMOVE && chatty) {
8950                            if (r == null) {
8951                                r = new StringBuilder(256);
8952                            } else {
8953                                r.append(' ');
8954                            }
8955                            r.append(name);
8956                        }
8957                    }
8958                }
8959            }
8960        }
8961        if (r != null) {
8962            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8963        }
8964    }
8965
8966    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8967        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8968            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8969                return true;
8970            }
8971        }
8972        return false;
8973    }
8974
8975    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8976    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8977    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8978
8979    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
8980        // Update the parent permissions
8981        updatePermissionsLPw(pkg.packageName, pkg, flags);
8982        // Update the child permissions
8983        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8984        for (int i = 0; i < childCount; i++) {
8985            PackageParser.Package childPkg = pkg.childPackages.get(i);
8986            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
8987        }
8988    }
8989
8990    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8991            int flags) {
8992        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8993        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8994    }
8995
8996    private void updatePermissionsLPw(String changingPkg,
8997            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8998        // Make sure there are no dangling permission trees.
8999        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9000        while (it.hasNext()) {
9001            final BasePermission bp = it.next();
9002            if (bp.packageSetting == null) {
9003                // We may not yet have parsed the package, so just see if
9004                // we still know about its settings.
9005                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9006            }
9007            if (bp.packageSetting == null) {
9008                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9009                        + " from package " + bp.sourcePackage);
9010                it.remove();
9011            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9012                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9013                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9014                            + " from package " + bp.sourcePackage);
9015                    flags |= UPDATE_PERMISSIONS_ALL;
9016                    it.remove();
9017                }
9018            }
9019        }
9020
9021        // Make sure all dynamic permissions have been assigned to a package,
9022        // and make sure there are no dangling permissions.
9023        it = mSettings.mPermissions.values().iterator();
9024        while (it.hasNext()) {
9025            final BasePermission bp = it.next();
9026            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9027                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9028                        + bp.name + " pkg=" + bp.sourcePackage
9029                        + " info=" + bp.pendingInfo);
9030                if (bp.packageSetting == null && bp.pendingInfo != null) {
9031                    final BasePermission tree = findPermissionTreeLP(bp.name);
9032                    if (tree != null && tree.perm != null) {
9033                        bp.packageSetting = tree.packageSetting;
9034                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9035                                new PermissionInfo(bp.pendingInfo));
9036                        bp.perm.info.packageName = tree.perm.info.packageName;
9037                        bp.perm.info.name = bp.name;
9038                        bp.uid = tree.uid;
9039                    }
9040                }
9041            }
9042            if (bp.packageSetting == null) {
9043                // We may not yet have parsed the package, so just see if
9044                // we still know about its settings.
9045                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9046            }
9047            if (bp.packageSetting == null) {
9048                Slog.w(TAG, "Removing dangling permission: " + bp.name
9049                        + " from package " + bp.sourcePackage);
9050                it.remove();
9051            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9052                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9053                    Slog.i(TAG, "Removing old permission: " + bp.name
9054                            + " from package " + bp.sourcePackage);
9055                    flags |= UPDATE_PERMISSIONS_ALL;
9056                    it.remove();
9057                }
9058            }
9059        }
9060
9061        // Now update the permissions for all packages, in particular
9062        // replace the granted permissions of the system packages.
9063        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9064            for (PackageParser.Package pkg : mPackages.values()) {
9065                if (pkg != pkgInfo) {
9066                    // Only replace for packages on requested volume
9067                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9068                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9069                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9070                    grantPermissionsLPw(pkg, replace, changingPkg);
9071                }
9072            }
9073        }
9074
9075        if (pkgInfo != null) {
9076            // Only replace for packages on requested volume
9077            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9078            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9079                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9080            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9081        }
9082    }
9083
9084    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9085            String packageOfInterest) {
9086        // IMPORTANT: There are two types of permissions: install and runtime.
9087        // Install time permissions are granted when the app is installed to
9088        // all device users and users added in the future. Runtime permissions
9089        // are granted at runtime explicitly to specific users. Normal and signature
9090        // protected permissions are install time permissions. Dangerous permissions
9091        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9092        // otherwise they are runtime permissions. This function does not manage
9093        // runtime permissions except for the case an app targeting Lollipop MR1
9094        // being upgraded to target a newer SDK, in which case dangerous permissions
9095        // are transformed from install time to runtime ones.
9096
9097        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9098        if (ps == null) {
9099            return;
9100        }
9101
9102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9103
9104        PermissionsState permissionsState = ps.getPermissionsState();
9105        PermissionsState origPermissions = permissionsState;
9106
9107        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9108
9109        boolean runtimePermissionsRevoked = false;
9110        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9111
9112        boolean changedInstallPermission = false;
9113
9114        if (replace) {
9115            ps.installPermissionsFixed = false;
9116            if (!ps.isSharedUser()) {
9117                origPermissions = new PermissionsState(permissionsState);
9118                permissionsState.reset();
9119            } else {
9120                // We need to know only about runtime permission changes since the
9121                // calling code always writes the install permissions state but
9122                // the runtime ones are written only if changed. The only cases of
9123                // changed runtime permissions here are promotion of an install to
9124                // runtime and revocation of a runtime from a shared user.
9125                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9126                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9127                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9128                    runtimePermissionsRevoked = true;
9129                }
9130            }
9131        }
9132
9133        permissionsState.setGlobalGids(mGlobalGids);
9134
9135        final int N = pkg.requestedPermissions.size();
9136        for (int i=0; i<N; i++) {
9137            final String name = pkg.requestedPermissions.get(i);
9138            final BasePermission bp = mSettings.mPermissions.get(name);
9139
9140            if (DEBUG_INSTALL) {
9141                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9142            }
9143
9144            if (bp == null || bp.packageSetting == null) {
9145                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9146                    Slog.w(TAG, "Unknown permission " + name
9147                            + " in package " + pkg.packageName);
9148                }
9149                continue;
9150            }
9151
9152            final String perm = bp.name;
9153            boolean allowedSig = false;
9154            int grant = GRANT_DENIED;
9155
9156            // Keep track of app op permissions.
9157            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9158                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9159                if (pkgs == null) {
9160                    pkgs = new ArraySet<>();
9161                    mAppOpPermissionPackages.put(bp.name, pkgs);
9162                }
9163                pkgs.add(pkg.packageName);
9164            }
9165
9166            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9167            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9168                    >= Build.VERSION_CODES.M;
9169            switch (level) {
9170                case PermissionInfo.PROTECTION_NORMAL: {
9171                    // For all apps normal permissions are install time ones.
9172                    grant = GRANT_INSTALL;
9173                } break;
9174
9175                case PermissionInfo.PROTECTION_DANGEROUS: {
9176                    // If a permission review is required for legacy apps we represent
9177                    // their permissions as always granted runtime ones since we need
9178                    // to keep the review required permission flag per user while an
9179                    // install permission's state is shared across all users.
9180                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9181                        // For legacy apps dangerous permissions are install time ones.
9182                        grant = GRANT_INSTALL;
9183                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9184                        // For legacy apps that became modern, install becomes runtime.
9185                        grant = GRANT_UPGRADE;
9186                    } else if (mPromoteSystemApps
9187                            && isSystemApp(ps)
9188                            && mExistingSystemPackages.contains(ps.name)) {
9189                        // For legacy system apps, install becomes runtime.
9190                        // We cannot check hasInstallPermission() for system apps since those
9191                        // permissions were granted implicitly and not persisted pre-M.
9192                        grant = GRANT_UPGRADE;
9193                    } else {
9194                        // For modern apps keep runtime permissions unchanged.
9195                        grant = GRANT_RUNTIME;
9196                    }
9197                } break;
9198
9199                case PermissionInfo.PROTECTION_SIGNATURE: {
9200                    // For all apps signature permissions are install time ones.
9201                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9202                    if (allowedSig) {
9203                        grant = GRANT_INSTALL;
9204                    }
9205                } break;
9206            }
9207
9208            if (DEBUG_INSTALL) {
9209                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9210            }
9211
9212            if (grant != GRANT_DENIED) {
9213                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9214                    // If this is an existing, non-system package, then
9215                    // we can't add any new permissions to it.
9216                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9217                        // Except...  if this is a permission that was added
9218                        // to the platform (note: need to only do this when
9219                        // updating the platform).
9220                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9221                            grant = GRANT_DENIED;
9222                        }
9223                    }
9224                }
9225
9226                switch (grant) {
9227                    case GRANT_INSTALL: {
9228                        // Revoke this as runtime permission to handle the case of
9229                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9230                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9231                            if (origPermissions.getRuntimePermissionState(
9232                                    bp.name, userId) != null) {
9233                                // Revoke the runtime permission and clear the flags.
9234                                origPermissions.revokeRuntimePermission(bp, userId);
9235                                origPermissions.updatePermissionFlags(bp, userId,
9236                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9237                                // If we revoked a permission permission, we have to write.
9238                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9239                                        changedRuntimePermissionUserIds, userId);
9240                            }
9241                        }
9242                        // Grant an install permission.
9243                        if (permissionsState.grantInstallPermission(bp) !=
9244                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9245                            changedInstallPermission = true;
9246                        }
9247                    } break;
9248
9249                    case GRANT_RUNTIME: {
9250                        // Grant previously granted runtime permissions.
9251                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9252                            PermissionState permissionState = origPermissions
9253                                    .getRuntimePermissionState(bp.name, userId);
9254                            int flags = permissionState != null
9255                                    ? permissionState.getFlags() : 0;
9256                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9257                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9258                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9259                                    // If we cannot put the permission as it was, we have to write.
9260                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9261                                            changedRuntimePermissionUserIds, userId);
9262                                }
9263                                // If the app supports runtime permissions no need for a review.
9264                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9265                                        && appSupportsRuntimePermissions
9266                                        && (flags & PackageManager
9267                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9268                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9269                                    // Since we changed the flags, we have to write.
9270                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9271                                            changedRuntimePermissionUserIds, userId);
9272                                }
9273                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9274                                    && !appSupportsRuntimePermissions) {
9275                                // For legacy apps that need a permission review, every new
9276                                // runtime permission is granted but it is pending a review.
9277                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9278                                    permissionsState.grantRuntimePermission(bp, userId);
9279                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9280                                    // We changed the permission and flags, hence have to write.
9281                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9282                                            changedRuntimePermissionUserIds, userId);
9283                                }
9284                            }
9285                            // Propagate the permission flags.
9286                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9287                        }
9288                    } break;
9289
9290                    case GRANT_UPGRADE: {
9291                        // Grant runtime permissions for a previously held install permission.
9292                        PermissionState permissionState = origPermissions
9293                                .getInstallPermissionState(bp.name);
9294                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9295
9296                        if (origPermissions.revokeInstallPermission(bp)
9297                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9298                            // We will be transferring the permission flags, so clear them.
9299                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9300                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9301                            changedInstallPermission = true;
9302                        }
9303
9304                        // If the permission is not to be promoted to runtime we ignore it and
9305                        // also its other flags as they are not applicable to install permissions.
9306                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9307                            for (int userId : currentUserIds) {
9308                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9309                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9310                                    // Transfer the permission flags.
9311                                    permissionsState.updatePermissionFlags(bp, userId,
9312                                            flags, flags);
9313                                    // If we granted the permission, we have to write.
9314                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9315                                            changedRuntimePermissionUserIds, userId);
9316                                }
9317                            }
9318                        }
9319                    } break;
9320
9321                    default: {
9322                        if (packageOfInterest == null
9323                                || packageOfInterest.equals(pkg.packageName)) {
9324                            Slog.w(TAG, "Not granting permission " + perm
9325                                    + " to package " + pkg.packageName
9326                                    + " because it was previously installed without");
9327                        }
9328                    } break;
9329                }
9330            } else {
9331                if (permissionsState.revokeInstallPermission(bp) !=
9332                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9333                    // Also drop the permission flags.
9334                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9335                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9336                    changedInstallPermission = true;
9337                    Slog.i(TAG, "Un-granting permission " + perm
9338                            + " from package " + pkg.packageName
9339                            + " (protectionLevel=" + bp.protectionLevel
9340                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9341                            + ")");
9342                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9343                    // Don't print warning for app op permissions, since it is fine for them
9344                    // not to be granted, there is a UI for the user to decide.
9345                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9346                        Slog.w(TAG, "Not granting permission " + perm
9347                                + " to package " + pkg.packageName
9348                                + " (protectionLevel=" + bp.protectionLevel
9349                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9350                                + ")");
9351                    }
9352                }
9353            }
9354        }
9355
9356        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9357                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9358            // This is the first that we have heard about this package, so the
9359            // permissions we have now selected are fixed until explicitly
9360            // changed.
9361            ps.installPermissionsFixed = true;
9362        }
9363
9364        // Persist the runtime permissions state for users with changes. If permissions
9365        // were revoked because no app in the shared user declares them we have to
9366        // write synchronously to avoid losing runtime permissions state.
9367        for (int userId : changedRuntimePermissionUserIds) {
9368            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9369        }
9370
9371        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9372    }
9373
9374    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9375        boolean allowed = false;
9376        final int NP = PackageParser.NEW_PERMISSIONS.length;
9377        for (int ip=0; ip<NP; ip++) {
9378            final PackageParser.NewPermissionInfo npi
9379                    = PackageParser.NEW_PERMISSIONS[ip];
9380            if (npi.name.equals(perm)
9381                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9382                allowed = true;
9383                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9384                        + pkg.packageName);
9385                break;
9386            }
9387        }
9388        return allowed;
9389    }
9390
9391    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9392            BasePermission bp, PermissionsState origPermissions) {
9393        boolean allowed;
9394        allowed = (compareSignatures(
9395                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9396                        == PackageManager.SIGNATURE_MATCH)
9397                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9398                        == PackageManager.SIGNATURE_MATCH);
9399        if (!allowed && (bp.protectionLevel
9400                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9401            if (isSystemApp(pkg)) {
9402                // For updated system applications, a system permission
9403                // is granted only if it had been defined by the original application.
9404                if (pkg.isUpdatedSystemApp()) {
9405                    final PackageSetting sysPs = mSettings
9406                            .getDisabledSystemPkgLPr(pkg.packageName);
9407                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9408                        // If the original was granted this permission, we take
9409                        // that grant decision as read and propagate it to the
9410                        // update.
9411                        if (sysPs.isPrivileged()) {
9412                            allowed = true;
9413                        }
9414                    } else {
9415                        // The system apk may have been updated with an older
9416                        // version of the one on the data partition, but which
9417                        // granted a new system permission that it didn't have
9418                        // before.  In this case we do want to allow the app to
9419                        // now get the new permission if the ancestral apk is
9420                        // privileged to get it.
9421                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9422                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9423                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9424                                    allowed = true;
9425                                    break;
9426                                }
9427                            }
9428                        }
9429                        // Also if a privileged parent package on the system image or any of
9430                        // its children requested a privileged permission, the updated child
9431                        // packages can also get the permission.
9432                        if (pkg.parentPackage != null) {
9433                            final PackageSetting disabledSysParentPs = mSettings
9434                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9435                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9436                                    && disabledSysParentPs.isPrivileged()) {
9437                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9438                                    allowed = true;
9439                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9440                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9441                                    for (int i = 0; i < count; i++) {
9442                                        PackageParser.Package disabledSysChildPkg =
9443                                                disabledSysParentPs.pkg.childPackages.get(i);
9444                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9445                                                perm)) {
9446                                            allowed = true;
9447                                            break;
9448                                        }
9449                                    }
9450                                }
9451                            }
9452                        }
9453                    }
9454                } else {
9455                    allowed = isPrivilegedApp(pkg);
9456                }
9457            }
9458        }
9459        if (!allowed) {
9460            if (!allowed && (bp.protectionLevel
9461                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9462                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9463                // If this was a previously normal/dangerous permission that got moved
9464                // to a system permission as part of the runtime permission redesign, then
9465                // we still want to blindly grant it to old apps.
9466                allowed = true;
9467            }
9468            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9469                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9470                // If this permission is to be granted to the system installer and
9471                // this app is an installer, then it gets the permission.
9472                allowed = true;
9473            }
9474            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9475                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9476                // If this permission is to be granted to the system verifier and
9477                // this app is a verifier, then it gets the permission.
9478                allowed = true;
9479            }
9480            if (!allowed && (bp.protectionLevel
9481                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9482                    && isSystemApp(pkg)) {
9483                // Any pre-installed system app is allowed to get this permission.
9484                allowed = true;
9485            }
9486            if (!allowed && (bp.protectionLevel
9487                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9488                // For development permissions, a development permission
9489                // is granted only if it was already granted.
9490                allowed = origPermissions.hasInstallPermission(perm);
9491            }
9492        }
9493        return allowed;
9494    }
9495
9496    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9497        final int permCount = pkg.requestedPermissions.size();
9498        for (int j = 0; j < permCount; j++) {
9499            String requestedPermission = pkg.requestedPermissions.get(j);
9500            if (permission.equals(requestedPermission)) {
9501                return true;
9502            }
9503        }
9504        return false;
9505    }
9506
9507    final class ActivityIntentResolver
9508            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9510                boolean defaultOnly, int userId) {
9511            if (!sUserManager.exists(userId)) return null;
9512            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9513            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9514        }
9515
9516        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9517                int userId) {
9518            if (!sUserManager.exists(userId)) return null;
9519            mFlags = flags;
9520            return super.queryIntent(intent, resolvedType,
9521                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9522        }
9523
9524        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9525                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9526            if (!sUserManager.exists(userId)) return null;
9527            if (packageActivities == null) {
9528                return null;
9529            }
9530            mFlags = flags;
9531            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9532            final int N = packageActivities.size();
9533            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9534                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9535
9536            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9537            for (int i = 0; i < N; ++i) {
9538                intentFilters = packageActivities.get(i).intents;
9539                if (intentFilters != null && intentFilters.size() > 0) {
9540                    PackageParser.ActivityIntentInfo[] array =
9541                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9542                    intentFilters.toArray(array);
9543                    listCut.add(array);
9544                }
9545            }
9546            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9547        }
9548
9549        public final void addActivity(PackageParser.Activity a, String type) {
9550            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9551            mActivities.put(a.getComponentName(), a);
9552            if (DEBUG_SHOW_INFO)
9553                Log.v(
9554                TAG, "  " + type + " " +
9555                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9556            if (DEBUG_SHOW_INFO)
9557                Log.v(TAG, "    Class=" + a.info.name);
9558            final int NI = a.intents.size();
9559            for (int j=0; j<NI; j++) {
9560                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9561                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9562                    intent.setPriority(0);
9563                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9564                            + a.className + " with priority > 0, forcing to 0");
9565                }
9566                if (DEBUG_SHOW_INFO) {
9567                    Log.v(TAG, "    IntentFilter:");
9568                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9569                }
9570                if (!intent.debugCheck()) {
9571                    Log.w(TAG, "==> For Activity " + a.info.name);
9572                }
9573                addFilter(intent);
9574            }
9575        }
9576
9577        public final void removeActivity(PackageParser.Activity a, String type) {
9578            mActivities.remove(a.getComponentName());
9579            if (DEBUG_SHOW_INFO) {
9580                Log.v(TAG, "  " + type + " "
9581                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9582                                : a.info.name) + ":");
9583                Log.v(TAG, "    Class=" + a.info.name);
9584            }
9585            final int NI = a.intents.size();
9586            for (int j=0; j<NI; j++) {
9587                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9588                if (DEBUG_SHOW_INFO) {
9589                    Log.v(TAG, "    IntentFilter:");
9590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9591                }
9592                removeFilter(intent);
9593            }
9594        }
9595
9596        @Override
9597        protected boolean allowFilterResult(
9598                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9599            ActivityInfo filterAi = filter.activity.info;
9600            for (int i=dest.size()-1; i>=0; i--) {
9601                ActivityInfo destAi = dest.get(i).activityInfo;
9602                if (destAi.name == filterAi.name
9603                        && destAi.packageName == filterAi.packageName) {
9604                    return false;
9605                }
9606            }
9607            return true;
9608        }
9609
9610        @Override
9611        protected ActivityIntentInfo[] newArray(int size) {
9612            return new ActivityIntentInfo[size];
9613        }
9614
9615        @Override
9616        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9617            if (!sUserManager.exists(userId)) return true;
9618            PackageParser.Package p = filter.activity.owner;
9619            if (p != null) {
9620                PackageSetting ps = (PackageSetting)p.mExtras;
9621                if (ps != null) {
9622                    // System apps are never considered stopped for purposes of
9623                    // filtering, because there may be no way for the user to
9624                    // actually re-launch them.
9625                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9626                            && ps.getStopped(userId);
9627                }
9628            }
9629            return false;
9630        }
9631
9632        @Override
9633        protected boolean isPackageForFilter(String packageName,
9634                PackageParser.ActivityIntentInfo info) {
9635            return packageName.equals(info.activity.owner.packageName);
9636        }
9637
9638        @Override
9639        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9640                int match, int userId) {
9641            if (!sUserManager.exists(userId)) return null;
9642            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9643                return null;
9644            }
9645            final PackageParser.Activity activity = info.activity;
9646            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9647            if (ps == null) {
9648                return null;
9649            }
9650            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9651                    ps.readUserState(userId), userId);
9652            if (ai == null) {
9653                return null;
9654            }
9655            final ResolveInfo res = new ResolveInfo();
9656            res.activityInfo = ai;
9657            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9658                res.filter = info;
9659            }
9660            if (info != null) {
9661                res.handleAllWebDataURI = info.handleAllWebDataURI();
9662            }
9663            res.priority = info.getPriority();
9664            res.preferredOrder = activity.owner.mPreferredOrder;
9665            //System.out.println("Result: " + res.activityInfo.className +
9666            //                   " = " + res.priority);
9667            res.match = match;
9668            res.isDefault = info.hasDefault;
9669            res.labelRes = info.labelRes;
9670            res.nonLocalizedLabel = info.nonLocalizedLabel;
9671            if (userNeedsBadging(userId)) {
9672                res.noResourceId = true;
9673            } else {
9674                res.icon = info.icon;
9675            }
9676            res.iconResourceId = info.icon;
9677            res.system = res.activityInfo.applicationInfo.isSystemApp();
9678            return res;
9679        }
9680
9681        @Override
9682        protected void sortResults(List<ResolveInfo> results) {
9683            Collections.sort(results, mResolvePrioritySorter);
9684        }
9685
9686        @Override
9687        protected void dumpFilter(PrintWriter out, String prefix,
9688                PackageParser.ActivityIntentInfo filter) {
9689            out.print(prefix); out.print(
9690                    Integer.toHexString(System.identityHashCode(filter.activity)));
9691                    out.print(' ');
9692                    filter.activity.printComponentShortName(out);
9693                    out.print(" filter ");
9694                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9695        }
9696
9697        @Override
9698        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9699            return filter.activity;
9700        }
9701
9702        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9703            PackageParser.Activity activity = (PackageParser.Activity)label;
9704            out.print(prefix); out.print(
9705                    Integer.toHexString(System.identityHashCode(activity)));
9706                    out.print(' ');
9707                    activity.printComponentShortName(out);
9708            if (count > 1) {
9709                out.print(" ("); out.print(count); out.print(" filters)");
9710            }
9711            out.println();
9712        }
9713
9714//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9715//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9716//            final List<ResolveInfo> retList = Lists.newArrayList();
9717//            while (i.hasNext()) {
9718//                final ResolveInfo resolveInfo = i.next();
9719//                if (isEnabledLP(resolveInfo.activityInfo)) {
9720//                    retList.add(resolveInfo);
9721//                }
9722//            }
9723//            return retList;
9724//        }
9725
9726        // Keys are String (activity class name), values are Activity.
9727        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9728                = new ArrayMap<ComponentName, PackageParser.Activity>();
9729        private int mFlags;
9730    }
9731
9732    private final class ServiceIntentResolver
9733            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9734        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9735                boolean defaultOnly, int userId) {
9736            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9737            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9738        }
9739
9740        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9741                int userId) {
9742            if (!sUserManager.exists(userId)) return null;
9743            mFlags = flags;
9744            return super.queryIntent(intent, resolvedType,
9745                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9746        }
9747
9748        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9749                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9750            if (!sUserManager.exists(userId)) return null;
9751            if (packageServices == null) {
9752                return null;
9753            }
9754            mFlags = flags;
9755            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9756            final int N = packageServices.size();
9757            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9758                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9759
9760            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9761            for (int i = 0; i < N; ++i) {
9762                intentFilters = packageServices.get(i).intents;
9763                if (intentFilters != null && intentFilters.size() > 0) {
9764                    PackageParser.ServiceIntentInfo[] array =
9765                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9766                    intentFilters.toArray(array);
9767                    listCut.add(array);
9768                }
9769            }
9770            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9771        }
9772
9773        public final void addService(PackageParser.Service s) {
9774            mServices.put(s.getComponentName(), s);
9775            if (DEBUG_SHOW_INFO) {
9776                Log.v(TAG, "  "
9777                        + (s.info.nonLocalizedLabel != null
9778                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9779                Log.v(TAG, "    Class=" + s.info.name);
9780            }
9781            final int NI = s.intents.size();
9782            int j;
9783            for (j=0; j<NI; j++) {
9784                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9785                if (DEBUG_SHOW_INFO) {
9786                    Log.v(TAG, "    IntentFilter:");
9787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9788                }
9789                if (!intent.debugCheck()) {
9790                    Log.w(TAG, "==> For Service " + s.info.name);
9791                }
9792                addFilter(intent);
9793            }
9794        }
9795
9796        public final void removeService(PackageParser.Service s) {
9797            mServices.remove(s.getComponentName());
9798            if (DEBUG_SHOW_INFO) {
9799                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9800                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9801                Log.v(TAG, "    Class=" + s.info.name);
9802            }
9803            final int NI = s.intents.size();
9804            int j;
9805            for (j=0; j<NI; j++) {
9806                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9807                if (DEBUG_SHOW_INFO) {
9808                    Log.v(TAG, "    IntentFilter:");
9809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9810                }
9811                removeFilter(intent);
9812            }
9813        }
9814
9815        @Override
9816        protected boolean allowFilterResult(
9817                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9818            ServiceInfo filterSi = filter.service.info;
9819            for (int i=dest.size()-1; i>=0; i--) {
9820                ServiceInfo destAi = dest.get(i).serviceInfo;
9821                if (destAi.name == filterSi.name
9822                        && destAi.packageName == filterSi.packageName) {
9823                    return false;
9824                }
9825            }
9826            return true;
9827        }
9828
9829        @Override
9830        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9831            return new PackageParser.ServiceIntentInfo[size];
9832        }
9833
9834        @Override
9835        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9836            if (!sUserManager.exists(userId)) return true;
9837            PackageParser.Package p = filter.service.owner;
9838            if (p != null) {
9839                PackageSetting ps = (PackageSetting)p.mExtras;
9840                if (ps != null) {
9841                    // System apps are never considered stopped for purposes of
9842                    // filtering, because there may be no way for the user to
9843                    // actually re-launch them.
9844                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9845                            && ps.getStopped(userId);
9846                }
9847            }
9848            return false;
9849        }
9850
9851        @Override
9852        protected boolean isPackageForFilter(String packageName,
9853                PackageParser.ServiceIntentInfo info) {
9854            return packageName.equals(info.service.owner.packageName);
9855        }
9856
9857        @Override
9858        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9859                int match, int userId) {
9860            if (!sUserManager.exists(userId)) return null;
9861            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9862            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9863                return null;
9864            }
9865            final PackageParser.Service service = info.service;
9866            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9867            if (ps == null) {
9868                return null;
9869            }
9870            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9871                    ps.readUserState(userId), userId);
9872            if (si == null) {
9873                return null;
9874            }
9875            final ResolveInfo res = new ResolveInfo();
9876            res.serviceInfo = si;
9877            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9878                res.filter = filter;
9879            }
9880            res.priority = info.getPriority();
9881            res.preferredOrder = service.owner.mPreferredOrder;
9882            res.match = match;
9883            res.isDefault = info.hasDefault;
9884            res.labelRes = info.labelRes;
9885            res.nonLocalizedLabel = info.nonLocalizedLabel;
9886            res.icon = info.icon;
9887            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9888            return res;
9889        }
9890
9891        @Override
9892        protected void sortResults(List<ResolveInfo> results) {
9893            Collections.sort(results, mResolvePrioritySorter);
9894        }
9895
9896        @Override
9897        protected void dumpFilter(PrintWriter out, String prefix,
9898                PackageParser.ServiceIntentInfo filter) {
9899            out.print(prefix); out.print(
9900                    Integer.toHexString(System.identityHashCode(filter.service)));
9901                    out.print(' ');
9902                    filter.service.printComponentShortName(out);
9903                    out.print(" filter ");
9904                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9905        }
9906
9907        @Override
9908        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9909            return filter.service;
9910        }
9911
9912        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9913            PackageParser.Service service = (PackageParser.Service)label;
9914            out.print(prefix); out.print(
9915                    Integer.toHexString(System.identityHashCode(service)));
9916                    out.print(' ');
9917                    service.printComponentShortName(out);
9918            if (count > 1) {
9919                out.print(" ("); out.print(count); out.print(" filters)");
9920            }
9921            out.println();
9922        }
9923
9924//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9925//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9926//            final List<ResolveInfo> retList = Lists.newArrayList();
9927//            while (i.hasNext()) {
9928//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9929//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9930//                    retList.add(resolveInfo);
9931//                }
9932//            }
9933//            return retList;
9934//        }
9935
9936        // Keys are String (activity class name), values are Activity.
9937        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9938                = new ArrayMap<ComponentName, PackageParser.Service>();
9939        private int mFlags;
9940    };
9941
9942    private final class ProviderIntentResolver
9943            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9944        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9945                boolean defaultOnly, int userId) {
9946            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9947            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9948        }
9949
9950        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9951                int userId) {
9952            if (!sUserManager.exists(userId))
9953                return null;
9954            mFlags = flags;
9955            return super.queryIntent(intent, resolvedType,
9956                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9957        }
9958
9959        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9960                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9961            if (!sUserManager.exists(userId))
9962                return null;
9963            if (packageProviders == null) {
9964                return null;
9965            }
9966            mFlags = flags;
9967            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9968            final int N = packageProviders.size();
9969            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9970                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9971
9972            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9973            for (int i = 0; i < N; ++i) {
9974                intentFilters = packageProviders.get(i).intents;
9975                if (intentFilters != null && intentFilters.size() > 0) {
9976                    PackageParser.ProviderIntentInfo[] array =
9977                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9978                    intentFilters.toArray(array);
9979                    listCut.add(array);
9980                }
9981            }
9982            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9983        }
9984
9985        public final void addProvider(PackageParser.Provider p) {
9986            if (mProviders.containsKey(p.getComponentName())) {
9987                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9988                return;
9989            }
9990
9991            mProviders.put(p.getComponentName(), p);
9992            if (DEBUG_SHOW_INFO) {
9993                Log.v(TAG, "  "
9994                        + (p.info.nonLocalizedLabel != null
9995                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9996                Log.v(TAG, "    Class=" + p.info.name);
9997            }
9998            final int NI = p.intents.size();
9999            int j;
10000            for (j = 0; j < NI; j++) {
10001                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10002                if (DEBUG_SHOW_INFO) {
10003                    Log.v(TAG, "    IntentFilter:");
10004                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10005                }
10006                if (!intent.debugCheck()) {
10007                    Log.w(TAG, "==> For Provider " + p.info.name);
10008                }
10009                addFilter(intent);
10010            }
10011        }
10012
10013        public final void removeProvider(PackageParser.Provider p) {
10014            mProviders.remove(p.getComponentName());
10015            if (DEBUG_SHOW_INFO) {
10016                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10017                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10018                Log.v(TAG, "    Class=" + p.info.name);
10019            }
10020            final int NI = p.intents.size();
10021            int j;
10022            for (j = 0; j < NI; j++) {
10023                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10024                if (DEBUG_SHOW_INFO) {
10025                    Log.v(TAG, "    IntentFilter:");
10026                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10027                }
10028                removeFilter(intent);
10029            }
10030        }
10031
10032        @Override
10033        protected boolean allowFilterResult(
10034                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10035            ProviderInfo filterPi = filter.provider.info;
10036            for (int i = dest.size() - 1; i >= 0; i--) {
10037                ProviderInfo destPi = dest.get(i).providerInfo;
10038                if (destPi.name == filterPi.name
10039                        && destPi.packageName == filterPi.packageName) {
10040                    return false;
10041                }
10042            }
10043            return true;
10044        }
10045
10046        @Override
10047        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10048            return new PackageParser.ProviderIntentInfo[size];
10049        }
10050
10051        @Override
10052        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10053            if (!sUserManager.exists(userId))
10054                return true;
10055            PackageParser.Package p = filter.provider.owner;
10056            if (p != null) {
10057                PackageSetting ps = (PackageSetting) p.mExtras;
10058                if (ps != null) {
10059                    // System apps are never considered stopped for purposes of
10060                    // filtering, because there may be no way for the user to
10061                    // actually re-launch them.
10062                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10063                            && ps.getStopped(userId);
10064                }
10065            }
10066            return false;
10067        }
10068
10069        @Override
10070        protected boolean isPackageForFilter(String packageName,
10071                PackageParser.ProviderIntentInfo info) {
10072            return packageName.equals(info.provider.owner.packageName);
10073        }
10074
10075        @Override
10076        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10077                int match, int userId) {
10078            if (!sUserManager.exists(userId))
10079                return null;
10080            final PackageParser.ProviderIntentInfo info = filter;
10081            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10082                return null;
10083            }
10084            final PackageParser.Provider provider = info.provider;
10085            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10086            if (ps == null) {
10087                return null;
10088            }
10089            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10090                    ps.readUserState(userId), userId);
10091            if (pi == null) {
10092                return null;
10093            }
10094            final ResolveInfo res = new ResolveInfo();
10095            res.providerInfo = pi;
10096            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10097                res.filter = filter;
10098            }
10099            res.priority = info.getPriority();
10100            res.preferredOrder = provider.owner.mPreferredOrder;
10101            res.match = match;
10102            res.isDefault = info.hasDefault;
10103            res.labelRes = info.labelRes;
10104            res.nonLocalizedLabel = info.nonLocalizedLabel;
10105            res.icon = info.icon;
10106            res.system = res.providerInfo.applicationInfo.isSystemApp();
10107            return res;
10108        }
10109
10110        @Override
10111        protected void sortResults(List<ResolveInfo> results) {
10112            Collections.sort(results, mResolvePrioritySorter);
10113        }
10114
10115        @Override
10116        protected void dumpFilter(PrintWriter out, String prefix,
10117                PackageParser.ProviderIntentInfo filter) {
10118            out.print(prefix);
10119            out.print(
10120                    Integer.toHexString(System.identityHashCode(filter.provider)));
10121            out.print(' ');
10122            filter.provider.printComponentShortName(out);
10123            out.print(" filter ");
10124            out.println(Integer.toHexString(System.identityHashCode(filter)));
10125        }
10126
10127        @Override
10128        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10129            return filter.provider;
10130        }
10131
10132        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10133            PackageParser.Provider provider = (PackageParser.Provider)label;
10134            out.print(prefix); out.print(
10135                    Integer.toHexString(System.identityHashCode(provider)));
10136                    out.print(' ');
10137                    provider.printComponentShortName(out);
10138            if (count > 1) {
10139                out.print(" ("); out.print(count); out.print(" filters)");
10140            }
10141            out.println();
10142        }
10143
10144        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10145                = new ArrayMap<ComponentName, PackageParser.Provider>();
10146        private int mFlags;
10147    }
10148
10149    private static final class EphemeralIntentResolver
10150            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10151        @Override
10152        protected EphemeralResolveIntentInfo[] newArray(int size) {
10153            return new EphemeralResolveIntentInfo[size];
10154        }
10155
10156        @Override
10157        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10158            return true;
10159        }
10160
10161        @Override
10162        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10163                int userId) {
10164            if (!sUserManager.exists(userId)) {
10165                return null;
10166            }
10167            return info.getEphemeralResolveInfo();
10168        }
10169    }
10170
10171    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10172            new Comparator<ResolveInfo>() {
10173        public int compare(ResolveInfo r1, ResolveInfo r2) {
10174            int v1 = r1.priority;
10175            int v2 = r2.priority;
10176            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10177            if (v1 != v2) {
10178                return (v1 > v2) ? -1 : 1;
10179            }
10180            v1 = r1.preferredOrder;
10181            v2 = r2.preferredOrder;
10182            if (v1 != v2) {
10183                return (v1 > v2) ? -1 : 1;
10184            }
10185            if (r1.isDefault != r2.isDefault) {
10186                return r1.isDefault ? -1 : 1;
10187            }
10188            v1 = r1.match;
10189            v2 = r2.match;
10190            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10191            if (v1 != v2) {
10192                return (v1 > v2) ? -1 : 1;
10193            }
10194            if (r1.system != r2.system) {
10195                return r1.system ? -1 : 1;
10196            }
10197            if (r1.activityInfo != null) {
10198                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10199            }
10200            if (r1.serviceInfo != null) {
10201                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10202            }
10203            if (r1.providerInfo != null) {
10204                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10205            }
10206            return 0;
10207        }
10208    };
10209
10210    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10211            new Comparator<ProviderInfo>() {
10212        public int compare(ProviderInfo p1, ProviderInfo p2) {
10213            final int v1 = p1.initOrder;
10214            final int v2 = p2.initOrder;
10215            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10216        }
10217    };
10218
10219    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10220            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10221            final int[] userIds) {
10222        mHandler.post(new Runnable() {
10223            @Override
10224            public void run() {
10225                try {
10226                    final IActivityManager am = ActivityManagerNative.getDefault();
10227                    if (am == null) return;
10228                    final int[] resolvedUserIds;
10229                    if (userIds == null) {
10230                        resolvedUserIds = am.getRunningUserIds();
10231                    } else {
10232                        resolvedUserIds = userIds;
10233                    }
10234                    for (int id : resolvedUserIds) {
10235                        final Intent intent = new Intent(action,
10236                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10237                        if (extras != null) {
10238                            intent.putExtras(extras);
10239                        }
10240                        if (targetPkg != null) {
10241                            intent.setPackage(targetPkg);
10242                        }
10243                        // Modify the UID when posting to other users
10244                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10245                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10246                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10247                            intent.putExtra(Intent.EXTRA_UID, uid);
10248                        }
10249                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10250                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10251                        if (DEBUG_BROADCASTS) {
10252                            RuntimeException here = new RuntimeException("here");
10253                            here.fillInStackTrace();
10254                            Slog.d(TAG, "Sending to user " + id + ": "
10255                                    + intent.toShortString(false, true, false, false)
10256                                    + " " + intent.getExtras(), here);
10257                        }
10258                        am.broadcastIntent(null, intent, null, finishedReceiver,
10259                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10260                                null, finishedReceiver != null, false, id);
10261                    }
10262                } catch (RemoteException ex) {
10263                }
10264            }
10265        });
10266    }
10267
10268    /**
10269     * Check if the external storage media is available. This is true if there
10270     * is a mounted external storage medium or if the external storage is
10271     * emulated.
10272     */
10273    private boolean isExternalMediaAvailable() {
10274        return mMediaMounted || Environment.isExternalStorageEmulated();
10275    }
10276
10277    @Override
10278    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10279        // writer
10280        synchronized (mPackages) {
10281            if (!isExternalMediaAvailable()) {
10282                // If the external storage is no longer mounted at this point,
10283                // the caller may not have been able to delete all of this
10284                // packages files and can not delete any more.  Bail.
10285                return null;
10286            }
10287            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10288            if (lastPackage != null) {
10289                pkgs.remove(lastPackage);
10290            }
10291            if (pkgs.size() > 0) {
10292                return pkgs.get(0);
10293            }
10294        }
10295        return null;
10296    }
10297
10298    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10299        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10300                userId, andCode ? 1 : 0, packageName);
10301        if (mSystemReady) {
10302            msg.sendToTarget();
10303        } else {
10304            if (mPostSystemReadyMessages == null) {
10305                mPostSystemReadyMessages = new ArrayList<>();
10306            }
10307            mPostSystemReadyMessages.add(msg);
10308        }
10309    }
10310
10311    void startCleaningPackages() {
10312        // reader
10313        synchronized (mPackages) {
10314            if (!isExternalMediaAvailable()) {
10315                return;
10316            }
10317            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10318                return;
10319            }
10320        }
10321        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10322        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10323        IActivityManager am = ActivityManagerNative.getDefault();
10324        if (am != null) {
10325            try {
10326                am.startService(null, intent, null, mContext.getOpPackageName(),
10327                        UserHandle.USER_SYSTEM);
10328            } catch (RemoteException e) {
10329            }
10330        }
10331    }
10332
10333    @Override
10334    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10335            int installFlags, String installerPackageName, VerificationParams verificationParams,
10336            String packageAbiOverride) {
10337        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10338                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10339    }
10340
10341    @Override
10342    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10343            int installFlags, String installerPackageName, VerificationParams verificationParams,
10344            String packageAbiOverride, int userId) {
10345        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10346
10347        final int callingUid = Binder.getCallingUid();
10348        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10349
10350        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10351            try {
10352                if (observer != null) {
10353                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10354                }
10355            } catch (RemoteException re) {
10356            }
10357            return;
10358        }
10359
10360        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10361            installFlags |= PackageManager.INSTALL_FROM_ADB;
10362
10363        } else {
10364            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10365            // about installerPackageName.
10366
10367            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10368            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10369        }
10370
10371        UserHandle user;
10372        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10373            user = UserHandle.ALL;
10374        } else {
10375            user = new UserHandle(userId);
10376        }
10377
10378        // Only system components can circumvent runtime permissions when installing.
10379        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10380                && mContext.checkCallingOrSelfPermission(Manifest.permission
10381                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10382            throw new SecurityException("You need the "
10383                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10384                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10385        }
10386
10387        verificationParams.setInstallerUid(callingUid);
10388
10389        final File originFile = new File(originPath);
10390        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10391
10392        final Message msg = mHandler.obtainMessage(INIT_COPY);
10393        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10394                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10395        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10396        msg.obj = params;
10397
10398        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10399                System.identityHashCode(msg.obj));
10400        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10401                System.identityHashCode(msg.obj));
10402
10403        mHandler.sendMessage(msg);
10404    }
10405
10406    void installStage(String packageName, File stagedDir, String stagedCid,
10407            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10408            String installerPackageName, int installerUid, UserHandle user) {
10409        if (DEBUG_EPHEMERAL) {
10410            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10411                Slog.d(TAG, "Ephemeral install of " + packageName);
10412            }
10413        }
10414        final VerificationParams verifParams = new VerificationParams(
10415                null, sessionParams.originatingUri, sessionParams.referrerUri,
10416                sessionParams.originatingUid);
10417        verifParams.setInstallerUid(installerUid);
10418
10419        final OriginInfo origin;
10420        if (stagedDir != null) {
10421            origin = OriginInfo.fromStagedFile(stagedDir);
10422        } else {
10423            origin = OriginInfo.fromStagedContainer(stagedCid);
10424        }
10425
10426        final Message msg = mHandler.obtainMessage(INIT_COPY);
10427        final InstallParams params = new InstallParams(origin, null, observer,
10428                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10429                verifParams, user, sessionParams.abiOverride,
10430                sessionParams.grantedRuntimePermissions);
10431        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10432        msg.obj = params;
10433
10434        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10435                System.identityHashCode(msg.obj));
10436        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10437                System.identityHashCode(msg.obj));
10438
10439        mHandler.sendMessage(msg);
10440    }
10441
10442    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10443        Bundle extras = new Bundle(1);
10444        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10445
10446        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10447                packageName, extras, 0, null, null, new int[] {userId});
10448        try {
10449            IActivityManager am = ActivityManagerNative.getDefault();
10450            final boolean isSystem =
10451                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10452            if (isSystem && am.isUserRunning(userId, 0)) {
10453                // The just-installed/enabled app is bundled on the system, so presumed
10454                // to be able to run automatically without needing an explicit launch.
10455                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10456                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10457                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10458                        .setPackage(packageName);
10459                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10460                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10461            }
10462        } catch (RemoteException e) {
10463            // shouldn't happen
10464            Slog.w(TAG, "Unable to bootstrap installed package", e);
10465        }
10466    }
10467
10468    @Override
10469    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10470            int userId) {
10471        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10472        PackageSetting pkgSetting;
10473        final int uid = Binder.getCallingUid();
10474        enforceCrossUserPermission(uid, userId, true, true,
10475                "setApplicationHiddenSetting for user " + userId);
10476
10477        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10478            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10479            return false;
10480        }
10481
10482        long callingId = Binder.clearCallingIdentity();
10483        try {
10484            boolean sendAdded = false;
10485            boolean sendRemoved = false;
10486            // writer
10487            synchronized (mPackages) {
10488                pkgSetting = mSettings.mPackages.get(packageName);
10489                if (pkgSetting == null) {
10490                    return false;
10491                }
10492                if (pkgSetting.getHidden(userId) != hidden) {
10493                    pkgSetting.setHidden(hidden, userId);
10494                    mSettings.writePackageRestrictionsLPr(userId);
10495                    if (hidden) {
10496                        sendRemoved = true;
10497                    } else {
10498                        sendAdded = true;
10499                    }
10500                }
10501            }
10502            if (sendAdded) {
10503                sendPackageAddedForUser(packageName, pkgSetting, userId);
10504                return true;
10505            }
10506            if (sendRemoved) {
10507                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10508                        "hiding pkg");
10509                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10510                return true;
10511            }
10512        } finally {
10513            Binder.restoreCallingIdentity(callingId);
10514        }
10515        return false;
10516    }
10517
10518    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10519            int userId) {
10520        final PackageRemovedInfo info = new PackageRemovedInfo();
10521        info.removedPackage = packageName;
10522        info.removedUsers = new int[] {userId};
10523        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10524        info.sendBroadcast(false, false, false);
10525    }
10526
10527    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10528        if (pkgList.length > 0) {
10529            Bundle extras = new Bundle(1);
10530            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10531
10532            sendPackageBroadcast(
10533                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10534                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10535                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10536                    new int[] {userId});
10537        }
10538    }
10539
10540    /**
10541     * Returns true if application is not found or there was an error. Otherwise it returns
10542     * the hidden state of the package for the given user.
10543     */
10544    @Override
10545    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10546        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10547        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10548                false, "getApplicationHidden for user " + userId);
10549        PackageSetting pkgSetting;
10550        long callingId = Binder.clearCallingIdentity();
10551        try {
10552            // writer
10553            synchronized (mPackages) {
10554                pkgSetting = mSettings.mPackages.get(packageName);
10555                if (pkgSetting == null) {
10556                    return true;
10557                }
10558                return pkgSetting.getHidden(userId);
10559            }
10560        } finally {
10561            Binder.restoreCallingIdentity(callingId);
10562        }
10563    }
10564
10565    /**
10566     * @hide
10567     */
10568    @Override
10569    public int installExistingPackageAsUser(String packageName, int userId) {
10570        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10571                null);
10572        PackageSetting pkgSetting;
10573        final int uid = Binder.getCallingUid();
10574        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10575                + userId);
10576        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10577            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10578        }
10579
10580        long callingId = Binder.clearCallingIdentity();
10581        try {
10582            boolean installed = false;
10583
10584            // writer
10585            synchronized (mPackages) {
10586                pkgSetting = mSettings.mPackages.get(packageName);
10587                if (pkgSetting == null) {
10588                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10589                }
10590                if (!pkgSetting.getInstalled(userId)) {
10591                    pkgSetting.setInstalled(true, userId);
10592                    pkgSetting.setHidden(false, userId);
10593                    mSettings.writePackageRestrictionsLPr(userId);
10594                    if (pkgSetting.pkg != null) {
10595                        prepareAppDataAfterInstall(pkgSetting.pkg);
10596                    }
10597                    installed = true;
10598                }
10599            }
10600
10601            if (installed) {
10602                sendPackageAddedForUser(packageName, pkgSetting, userId);
10603            }
10604        } finally {
10605            Binder.restoreCallingIdentity(callingId);
10606        }
10607
10608        return PackageManager.INSTALL_SUCCEEDED;
10609    }
10610
10611    boolean isUserRestricted(int userId, String restrictionKey) {
10612        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10613        if (restrictions.getBoolean(restrictionKey, false)) {
10614            Log.w(TAG, "User is restricted: " + restrictionKey);
10615            return true;
10616        }
10617        return false;
10618    }
10619
10620    @Override
10621    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10622        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10623        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10624                "setPackageSuspended for user " + userId);
10625
10626        // TODO: investigate and add more restrictions for suspending crucial packages.
10627        if (isPackageDeviceAdmin(packageName, userId)) {
10628            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10629                    + "\": has active device admin");
10630            return false;
10631        }
10632
10633        long callingId = Binder.clearCallingIdentity();
10634        try {
10635            boolean changed = false;
10636            boolean success = false;
10637            int appId = -1;
10638            synchronized (mPackages) {
10639                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10640                if (pkgSetting != null) {
10641                    if (pkgSetting.getSuspended(userId) != suspended) {
10642                        pkgSetting.setSuspended(suspended, userId);
10643                        mSettings.writePackageRestrictionsLPr(userId);
10644                        appId = pkgSetting.appId;
10645                        changed = true;
10646                    }
10647                    success = true;
10648                }
10649            }
10650
10651            if (changed) {
10652                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10653                if (suspended) {
10654                    killApplication(packageName, UserHandle.getUid(userId, appId),
10655                            "suspending package");
10656                }
10657            }
10658            return success;
10659        } finally {
10660            Binder.restoreCallingIdentity(callingId);
10661        }
10662    }
10663
10664    @Override
10665    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10666        mContext.enforceCallingOrSelfPermission(
10667                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10668                "Only package verification agents can verify applications");
10669
10670        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10671        final PackageVerificationResponse response = new PackageVerificationResponse(
10672                verificationCode, Binder.getCallingUid());
10673        msg.arg1 = id;
10674        msg.obj = response;
10675        mHandler.sendMessage(msg);
10676    }
10677
10678    @Override
10679    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10680            long millisecondsToDelay) {
10681        mContext.enforceCallingOrSelfPermission(
10682                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10683                "Only package verification agents can extend verification timeouts");
10684
10685        final PackageVerificationState state = mPendingVerification.get(id);
10686        final PackageVerificationResponse response = new PackageVerificationResponse(
10687                verificationCodeAtTimeout, Binder.getCallingUid());
10688
10689        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10690            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10691        }
10692        if (millisecondsToDelay < 0) {
10693            millisecondsToDelay = 0;
10694        }
10695        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10696                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10697            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10698        }
10699
10700        if ((state != null) && !state.timeoutExtended()) {
10701            state.extendTimeout();
10702
10703            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10704            msg.arg1 = id;
10705            msg.obj = response;
10706            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10707        }
10708    }
10709
10710    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10711            int verificationCode, UserHandle user) {
10712        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10713        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10714        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10715        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10716        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10717
10718        mContext.sendBroadcastAsUser(intent, user,
10719                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10720    }
10721
10722    private ComponentName matchComponentForVerifier(String packageName,
10723            List<ResolveInfo> receivers) {
10724        ActivityInfo targetReceiver = null;
10725
10726        final int NR = receivers.size();
10727        for (int i = 0; i < NR; i++) {
10728            final ResolveInfo info = receivers.get(i);
10729            if (info.activityInfo == null) {
10730                continue;
10731            }
10732
10733            if (packageName.equals(info.activityInfo.packageName)) {
10734                targetReceiver = info.activityInfo;
10735                break;
10736            }
10737        }
10738
10739        if (targetReceiver == null) {
10740            return null;
10741        }
10742
10743        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10744    }
10745
10746    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10747            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10748        if (pkgInfo.verifiers.length == 0) {
10749            return null;
10750        }
10751
10752        final int N = pkgInfo.verifiers.length;
10753        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10754        for (int i = 0; i < N; i++) {
10755            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10756
10757            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10758                    receivers);
10759            if (comp == null) {
10760                continue;
10761            }
10762
10763            final int verifierUid = getUidForVerifier(verifierInfo);
10764            if (verifierUid == -1) {
10765                continue;
10766            }
10767
10768            if (DEBUG_VERIFY) {
10769                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10770                        + " with the correct signature");
10771            }
10772            sufficientVerifiers.add(comp);
10773            verificationState.addSufficientVerifier(verifierUid);
10774        }
10775
10776        return sufficientVerifiers;
10777    }
10778
10779    private int getUidForVerifier(VerifierInfo verifierInfo) {
10780        synchronized (mPackages) {
10781            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10782            if (pkg == null) {
10783                return -1;
10784            } else if (pkg.mSignatures.length != 1) {
10785                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10786                        + " has more than one signature; ignoring");
10787                return -1;
10788            }
10789
10790            /*
10791             * If the public key of the package's signature does not match
10792             * our expected public key, then this is a different package and
10793             * we should skip.
10794             */
10795
10796            final byte[] expectedPublicKey;
10797            try {
10798                final Signature verifierSig = pkg.mSignatures[0];
10799                final PublicKey publicKey = verifierSig.getPublicKey();
10800                expectedPublicKey = publicKey.getEncoded();
10801            } catch (CertificateException e) {
10802                return -1;
10803            }
10804
10805            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10806
10807            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10808                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10809                        + " does not have the expected public key; ignoring");
10810                return -1;
10811            }
10812
10813            return pkg.applicationInfo.uid;
10814        }
10815    }
10816
10817    @Override
10818    public void finishPackageInstall(int token) {
10819        enforceSystemOrRoot("Only the system is allowed to finish installs");
10820
10821        if (DEBUG_INSTALL) {
10822            Slog.v(TAG, "BM finishing package install for " + token);
10823        }
10824        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10825
10826        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10827        mHandler.sendMessage(msg);
10828    }
10829
10830    /**
10831     * Get the verification agent timeout.
10832     *
10833     * @return verification timeout in milliseconds
10834     */
10835    private long getVerificationTimeout() {
10836        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10837                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10838                DEFAULT_VERIFICATION_TIMEOUT);
10839    }
10840
10841    /**
10842     * Get the default verification agent response code.
10843     *
10844     * @return default verification response code
10845     */
10846    private int getDefaultVerificationResponse() {
10847        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10848                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10849                DEFAULT_VERIFICATION_RESPONSE);
10850    }
10851
10852    /**
10853     * Check whether or not package verification has been enabled.
10854     *
10855     * @return true if verification should be performed
10856     */
10857    private boolean isVerificationEnabled(int userId, int installFlags) {
10858        if (!DEFAULT_VERIFY_ENABLE) {
10859            return false;
10860        }
10861        // Ephemeral apps don't get the full verification treatment
10862        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10863            if (DEBUG_EPHEMERAL) {
10864                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10865            }
10866            return false;
10867        }
10868
10869        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10870
10871        // Check if installing from ADB
10872        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10873            // Do not run verification in a test harness environment
10874            if (ActivityManager.isRunningInTestHarness()) {
10875                return false;
10876            }
10877            if (ensureVerifyAppsEnabled) {
10878                return true;
10879            }
10880            // Check if the developer does not want package verification for ADB installs
10881            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10882                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10883                return false;
10884            }
10885        }
10886
10887        if (ensureVerifyAppsEnabled) {
10888            return true;
10889        }
10890
10891        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10892                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10893    }
10894
10895    @Override
10896    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10897            throws RemoteException {
10898        mContext.enforceCallingOrSelfPermission(
10899                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10900                "Only intentfilter verification agents can verify applications");
10901
10902        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10903        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10904                Binder.getCallingUid(), verificationCode, failedDomains);
10905        msg.arg1 = id;
10906        msg.obj = response;
10907        mHandler.sendMessage(msg);
10908    }
10909
10910    @Override
10911    public int getIntentVerificationStatus(String packageName, int userId) {
10912        synchronized (mPackages) {
10913            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10914        }
10915    }
10916
10917    @Override
10918    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10919        mContext.enforceCallingOrSelfPermission(
10920                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10921
10922        boolean result = false;
10923        synchronized (mPackages) {
10924            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10925        }
10926        if (result) {
10927            scheduleWritePackageRestrictionsLocked(userId);
10928        }
10929        return result;
10930    }
10931
10932    @Override
10933    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10934        synchronized (mPackages) {
10935            return mSettings.getIntentFilterVerificationsLPr(packageName);
10936        }
10937    }
10938
10939    @Override
10940    public List<IntentFilter> getAllIntentFilters(String packageName) {
10941        if (TextUtils.isEmpty(packageName)) {
10942            return Collections.<IntentFilter>emptyList();
10943        }
10944        synchronized (mPackages) {
10945            PackageParser.Package pkg = mPackages.get(packageName);
10946            if (pkg == null || pkg.activities == null) {
10947                return Collections.<IntentFilter>emptyList();
10948            }
10949            final int count = pkg.activities.size();
10950            ArrayList<IntentFilter> result = new ArrayList<>();
10951            for (int n=0; n<count; n++) {
10952                PackageParser.Activity activity = pkg.activities.get(n);
10953                if (activity.intents != null && activity.intents.size() > 0) {
10954                    result.addAll(activity.intents);
10955                }
10956            }
10957            return result;
10958        }
10959    }
10960
10961    @Override
10962    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10963        mContext.enforceCallingOrSelfPermission(
10964                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10965
10966        synchronized (mPackages) {
10967            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10968            if (packageName != null) {
10969                result |= updateIntentVerificationStatus(packageName,
10970                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10971                        userId);
10972                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10973                        packageName, userId);
10974            }
10975            return result;
10976        }
10977    }
10978
10979    @Override
10980    public String getDefaultBrowserPackageName(int userId) {
10981        synchronized (mPackages) {
10982            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10983        }
10984    }
10985
10986    /**
10987     * Get the "allow unknown sources" setting.
10988     *
10989     * @return the current "allow unknown sources" setting
10990     */
10991    private int getUnknownSourcesSettings() {
10992        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10993                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10994                -1);
10995    }
10996
10997    @Override
10998    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10999        final int uid = Binder.getCallingUid();
11000        // writer
11001        synchronized (mPackages) {
11002            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11003            if (targetPackageSetting == null) {
11004                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11005            }
11006
11007            PackageSetting installerPackageSetting;
11008            if (installerPackageName != null) {
11009                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11010                if (installerPackageSetting == null) {
11011                    throw new IllegalArgumentException("Unknown installer package: "
11012                            + installerPackageName);
11013                }
11014            } else {
11015                installerPackageSetting = null;
11016            }
11017
11018            Signature[] callerSignature;
11019            Object obj = mSettings.getUserIdLPr(uid);
11020            if (obj != null) {
11021                if (obj instanceof SharedUserSetting) {
11022                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11023                } else if (obj instanceof PackageSetting) {
11024                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11025                } else {
11026                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11027                }
11028            } else {
11029                throw new SecurityException("Unknown calling UID: " + uid);
11030            }
11031
11032            // Verify: can't set installerPackageName to a package that is
11033            // not signed with the same cert as the caller.
11034            if (installerPackageSetting != null) {
11035                if (compareSignatures(callerSignature,
11036                        installerPackageSetting.signatures.mSignatures)
11037                        != PackageManager.SIGNATURE_MATCH) {
11038                    throw new SecurityException(
11039                            "Caller does not have same cert as new installer package "
11040                            + installerPackageName);
11041                }
11042            }
11043
11044            // Verify: if target already has an installer package, it must
11045            // be signed with the same cert as the caller.
11046            if (targetPackageSetting.installerPackageName != null) {
11047                PackageSetting setting = mSettings.mPackages.get(
11048                        targetPackageSetting.installerPackageName);
11049                // If the currently set package isn't valid, then it's always
11050                // okay to change it.
11051                if (setting != null) {
11052                    if (compareSignatures(callerSignature,
11053                            setting.signatures.mSignatures)
11054                            != PackageManager.SIGNATURE_MATCH) {
11055                        throw new SecurityException(
11056                                "Caller does not have same cert as old installer package "
11057                                + targetPackageSetting.installerPackageName);
11058                    }
11059                }
11060            }
11061
11062            // Okay!
11063            targetPackageSetting.installerPackageName = installerPackageName;
11064            scheduleWriteSettingsLocked();
11065        }
11066    }
11067
11068    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11069        // Queue up an async operation since the package installation may take a little while.
11070        mHandler.post(new Runnable() {
11071            public void run() {
11072                mHandler.removeCallbacks(this);
11073                 // Result object to be returned
11074                PackageInstalledInfo res = new PackageInstalledInfo();
11075                res.returnCode = currentStatus;
11076                res.uid = -1;
11077                res.pkg = null;
11078                res.removedInfo = new PackageRemovedInfo();
11079                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11080                    args.doPreInstall(res.returnCode);
11081                    synchronized (mInstallLock) {
11082                        installPackageTracedLI(args, res);
11083                    }
11084                    args.doPostInstall(res.returnCode, res.uid);
11085                }
11086
11087                // A restore should be performed at this point if (a) the install
11088                // succeeded, (b) the operation is not an update, and (c) the new
11089                // package has not opted out of backup participation.
11090                final boolean update = res.removedInfo.removedPackage != null;
11091                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11092                boolean doRestore = !update
11093                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11094
11095                // Set up the post-install work request bookkeeping.  This will be used
11096                // and cleaned up by the post-install event handling regardless of whether
11097                // there's a restore pass performed.  Token values are >= 1.
11098                int token;
11099                if (mNextInstallToken < 0) mNextInstallToken = 1;
11100                token = mNextInstallToken++;
11101
11102                PostInstallData data = new PostInstallData(args, res);
11103                mRunningInstalls.put(token, data);
11104                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11105
11106                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11107                    // Pass responsibility to the Backup Manager.  It will perform a
11108                    // restore if appropriate, then pass responsibility back to the
11109                    // Package Manager to run the post-install observer callbacks
11110                    // and broadcasts.
11111                    IBackupManager bm = IBackupManager.Stub.asInterface(
11112                            ServiceManager.getService(Context.BACKUP_SERVICE));
11113                    if (bm != null) {
11114                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11115                                + " to BM for possible restore");
11116                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11117                        try {
11118                            // TODO: http://b/22388012
11119                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11120                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11121                            } else {
11122                                doRestore = false;
11123                            }
11124                        } catch (RemoteException e) {
11125                            // can't happen; the backup manager is local
11126                        } catch (Exception e) {
11127                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11128                            doRestore = false;
11129                        }
11130                    } else {
11131                        Slog.e(TAG, "Backup Manager not found!");
11132                        doRestore = false;
11133                    }
11134                }
11135
11136                if (!doRestore) {
11137                    // No restore possible, or the Backup Manager was mysteriously not
11138                    // available -- just fire the post-install work request directly.
11139                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11140
11141                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11142
11143                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11144                    mHandler.sendMessage(msg);
11145                }
11146            }
11147        });
11148    }
11149
11150    private abstract class HandlerParams {
11151        private static final int MAX_RETRIES = 4;
11152
11153        /**
11154         * Number of times startCopy() has been attempted and had a non-fatal
11155         * error.
11156         */
11157        private int mRetries = 0;
11158
11159        /** User handle for the user requesting the information or installation. */
11160        private final UserHandle mUser;
11161        String traceMethod;
11162        int traceCookie;
11163
11164        HandlerParams(UserHandle user) {
11165            mUser = user;
11166        }
11167
11168        UserHandle getUser() {
11169            return mUser;
11170        }
11171
11172        HandlerParams setTraceMethod(String traceMethod) {
11173            this.traceMethod = traceMethod;
11174            return this;
11175        }
11176
11177        HandlerParams setTraceCookie(int traceCookie) {
11178            this.traceCookie = traceCookie;
11179            return this;
11180        }
11181
11182        final boolean startCopy() {
11183            boolean res;
11184            try {
11185                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11186
11187                if (++mRetries > MAX_RETRIES) {
11188                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11189                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11190                    handleServiceError();
11191                    return false;
11192                } else {
11193                    handleStartCopy();
11194                    res = true;
11195                }
11196            } catch (RemoteException e) {
11197                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11198                mHandler.sendEmptyMessage(MCS_RECONNECT);
11199                res = false;
11200            }
11201            handleReturnCode();
11202            return res;
11203        }
11204
11205        final void serviceError() {
11206            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11207            handleServiceError();
11208            handleReturnCode();
11209        }
11210
11211        abstract void handleStartCopy() throws RemoteException;
11212        abstract void handleServiceError();
11213        abstract void handleReturnCode();
11214    }
11215
11216    class MeasureParams extends HandlerParams {
11217        private final PackageStats mStats;
11218        private boolean mSuccess;
11219
11220        private final IPackageStatsObserver mObserver;
11221
11222        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11223            super(new UserHandle(stats.userHandle));
11224            mObserver = observer;
11225            mStats = stats;
11226        }
11227
11228        @Override
11229        public String toString() {
11230            return "MeasureParams{"
11231                + Integer.toHexString(System.identityHashCode(this))
11232                + " " + mStats.packageName + "}";
11233        }
11234
11235        @Override
11236        void handleStartCopy() throws RemoteException {
11237            synchronized (mInstallLock) {
11238                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11239            }
11240
11241            if (mSuccess) {
11242                final boolean mounted;
11243                if (Environment.isExternalStorageEmulated()) {
11244                    mounted = true;
11245                } else {
11246                    final String status = Environment.getExternalStorageState();
11247                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11248                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11249                }
11250
11251                if (mounted) {
11252                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11253
11254                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11255                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11256
11257                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11258                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11259
11260                    // Always subtract cache size, since it's a subdirectory
11261                    mStats.externalDataSize -= mStats.externalCacheSize;
11262
11263                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11264                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11265
11266                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11267                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11268                }
11269            }
11270        }
11271
11272        @Override
11273        void handleReturnCode() {
11274            if (mObserver != null) {
11275                try {
11276                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11277                } catch (RemoteException e) {
11278                    Slog.i(TAG, "Observer no longer exists.");
11279                }
11280            }
11281        }
11282
11283        @Override
11284        void handleServiceError() {
11285            Slog.e(TAG, "Could not measure application " + mStats.packageName
11286                            + " external storage");
11287        }
11288    }
11289
11290    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11291            throws RemoteException {
11292        long result = 0;
11293        for (File path : paths) {
11294            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11295        }
11296        return result;
11297    }
11298
11299    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11300        for (File path : paths) {
11301            try {
11302                mcs.clearDirectory(path.getAbsolutePath());
11303            } catch (RemoteException e) {
11304            }
11305        }
11306    }
11307
11308    static class OriginInfo {
11309        /**
11310         * Location where install is coming from, before it has been
11311         * copied/renamed into place. This could be a single monolithic APK
11312         * file, or a cluster directory. This location may be untrusted.
11313         */
11314        final File file;
11315        final String cid;
11316
11317        /**
11318         * Flag indicating that {@link #file} or {@link #cid} has already been
11319         * staged, meaning downstream users don't need to defensively copy the
11320         * contents.
11321         */
11322        final boolean staged;
11323
11324        /**
11325         * Flag indicating that {@link #file} or {@link #cid} is an already
11326         * installed app that is being moved.
11327         */
11328        final boolean existing;
11329
11330        final String resolvedPath;
11331        final File resolvedFile;
11332
11333        static OriginInfo fromNothing() {
11334            return new OriginInfo(null, null, false, false);
11335        }
11336
11337        static OriginInfo fromUntrustedFile(File file) {
11338            return new OriginInfo(file, null, false, false);
11339        }
11340
11341        static OriginInfo fromExistingFile(File file) {
11342            return new OriginInfo(file, null, false, true);
11343        }
11344
11345        static OriginInfo fromStagedFile(File file) {
11346            return new OriginInfo(file, null, true, false);
11347        }
11348
11349        static OriginInfo fromStagedContainer(String cid) {
11350            return new OriginInfo(null, cid, true, false);
11351        }
11352
11353        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11354            this.file = file;
11355            this.cid = cid;
11356            this.staged = staged;
11357            this.existing = existing;
11358
11359            if (cid != null) {
11360                resolvedPath = PackageHelper.getSdDir(cid);
11361                resolvedFile = new File(resolvedPath);
11362            } else if (file != null) {
11363                resolvedPath = file.getAbsolutePath();
11364                resolvedFile = file;
11365            } else {
11366                resolvedPath = null;
11367                resolvedFile = null;
11368            }
11369        }
11370    }
11371
11372    static class MoveInfo {
11373        final int moveId;
11374        final String fromUuid;
11375        final String toUuid;
11376        final String packageName;
11377        final String dataAppName;
11378        final int appId;
11379        final String seinfo;
11380        final int targetSdkVersion;
11381
11382        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11383                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11384            this.moveId = moveId;
11385            this.fromUuid = fromUuid;
11386            this.toUuid = toUuid;
11387            this.packageName = packageName;
11388            this.dataAppName = dataAppName;
11389            this.appId = appId;
11390            this.seinfo = seinfo;
11391            this.targetSdkVersion = targetSdkVersion;
11392        }
11393    }
11394
11395    class InstallParams extends HandlerParams {
11396        final OriginInfo origin;
11397        final MoveInfo move;
11398        final IPackageInstallObserver2 observer;
11399        int installFlags;
11400        final String installerPackageName;
11401        final String volumeUuid;
11402        final VerificationParams verificationParams;
11403        private InstallArgs mArgs;
11404        private int mRet;
11405        final String packageAbiOverride;
11406        final String[] grantedRuntimePermissions;
11407
11408        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11409                int installFlags, String installerPackageName, String volumeUuid,
11410                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11411                String[] grantedPermissions) {
11412            super(user);
11413            this.origin = origin;
11414            this.move = move;
11415            this.observer = observer;
11416            this.installFlags = installFlags;
11417            this.installerPackageName = installerPackageName;
11418            this.volumeUuid = volumeUuid;
11419            this.verificationParams = verificationParams;
11420            this.packageAbiOverride = packageAbiOverride;
11421            this.grantedRuntimePermissions = grantedPermissions;
11422        }
11423
11424        @Override
11425        public String toString() {
11426            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11427                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11428        }
11429
11430        private int installLocationPolicy(PackageInfoLite pkgLite) {
11431            String packageName = pkgLite.packageName;
11432            int installLocation = pkgLite.installLocation;
11433            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11434            // reader
11435            synchronized (mPackages) {
11436                PackageParser.Package pkg = mPackages.get(packageName);
11437                if (pkg != null) {
11438                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11439                        // Check for downgrading.
11440                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11441                            try {
11442                                checkDowngrade(pkg, pkgLite);
11443                            } catch (PackageManagerException e) {
11444                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11445                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11446                            }
11447                        }
11448                        // Check for updated system application.
11449                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11450                            if (onSd) {
11451                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11452                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11453                            }
11454                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11455                        } else {
11456                            if (onSd) {
11457                                // Install flag overrides everything.
11458                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11459                            }
11460                            // If current upgrade specifies particular preference
11461                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11462                                // Application explicitly specified internal.
11463                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11464                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11465                                // App explictly prefers external. Let policy decide
11466                            } else {
11467                                // Prefer previous location
11468                                if (isExternal(pkg)) {
11469                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11470                                }
11471                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11472                            }
11473                        }
11474                    } else {
11475                        // Invalid install. Return error code
11476                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11477                    }
11478                }
11479            }
11480            // All the special cases have been taken care of.
11481            // Return result based on recommended install location.
11482            if (onSd) {
11483                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11484            }
11485            return pkgLite.recommendedInstallLocation;
11486        }
11487
11488        /*
11489         * Invoke remote method to get package information and install
11490         * location values. Override install location based on default
11491         * policy if needed and then create install arguments based
11492         * on the install location.
11493         */
11494        public void handleStartCopy() throws RemoteException {
11495            int ret = PackageManager.INSTALL_SUCCEEDED;
11496
11497            // If we're already staged, we've firmly committed to an install location
11498            if (origin.staged) {
11499                if (origin.file != null) {
11500                    installFlags |= PackageManager.INSTALL_INTERNAL;
11501                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11502                } else if (origin.cid != null) {
11503                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11504                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11505                } else {
11506                    throw new IllegalStateException("Invalid stage location");
11507                }
11508            }
11509
11510            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11511            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11512            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11513            PackageInfoLite pkgLite = null;
11514
11515            if (onInt && onSd) {
11516                // Check if both bits are set.
11517                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11518                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11519            } else if (onSd && ephemeral) {
11520                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11521                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11522            } else {
11523                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11524                        packageAbiOverride);
11525
11526                if (DEBUG_EPHEMERAL && ephemeral) {
11527                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11528                }
11529
11530                /*
11531                 * If we have too little free space, try to free cache
11532                 * before giving up.
11533                 */
11534                if (!origin.staged && pkgLite.recommendedInstallLocation
11535                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11536                    // TODO: focus freeing disk space on the target device
11537                    final StorageManager storage = StorageManager.from(mContext);
11538                    final long lowThreshold = storage.getStorageLowBytes(
11539                            Environment.getDataDirectory());
11540
11541                    final long sizeBytes = mContainerService.calculateInstalledSize(
11542                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11543
11544                    try {
11545                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11546                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11547                                installFlags, packageAbiOverride);
11548                    } catch (InstallerException e) {
11549                        Slog.w(TAG, "Failed to free cache", e);
11550                    }
11551
11552                    /*
11553                     * The cache free must have deleted the file we
11554                     * downloaded to install.
11555                     *
11556                     * TODO: fix the "freeCache" call to not delete
11557                     *       the file we care about.
11558                     */
11559                    if (pkgLite.recommendedInstallLocation
11560                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11561                        pkgLite.recommendedInstallLocation
11562                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11563                    }
11564                }
11565            }
11566
11567            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11568                int loc = pkgLite.recommendedInstallLocation;
11569                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11570                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11571                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11572                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11573                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11574                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11575                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11576                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11577                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11578                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11579                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11580                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11581                } else {
11582                    // Override with defaults if needed.
11583                    loc = installLocationPolicy(pkgLite);
11584                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11585                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11586                    } else if (!onSd && !onInt) {
11587                        // Override install location with flags
11588                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11589                            // Set the flag to install on external media.
11590                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11591                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11592                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11593                            if (DEBUG_EPHEMERAL) {
11594                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11595                            }
11596                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11597                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11598                                    |PackageManager.INSTALL_INTERNAL);
11599                        } else {
11600                            // Make sure the flag for installing on external
11601                            // media is unset
11602                            installFlags |= PackageManager.INSTALL_INTERNAL;
11603                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11604                        }
11605                    }
11606                }
11607            }
11608
11609            final InstallArgs args = createInstallArgs(this);
11610            mArgs = args;
11611
11612            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11613                // TODO: http://b/22976637
11614                // Apps installed for "all" users use the device owner to verify the app
11615                UserHandle verifierUser = getUser();
11616                if (verifierUser == UserHandle.ALL) {
11617                    verifierUser = UserHandle.SYSTEM;
11618                }
11619
11620                /*
11621                 * Determine if we have any installed package verifiers. If we
11622                 * do, then we'll defer to them to verify the packages.
11623                 */
11624                final int requiredUid = mRequiredVerifierPackage == null ? -1
11625                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11626                                verifierUser.getIdentifier());
11627                if (!origin.existing && requiredUid != -1
11628                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11629                    final Intent verification = new Intent(
11630                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11631                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11632                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11633                            PACKAGE_MIME_TYPE);
11634                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11635
11636                    // Query all live verifiers based on current user state
11637                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11638                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11639
11640                    if (DEBUG_VERIFY) {
11641                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11642                                + verification.toString() + " with " + pkgLite.verifiers.length
11643                                + " optional verifiers");
11644                    }
11645
11646                    final int verificationId = mPendingVerificationToken++;
11647
11648                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11649
11650                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11651                            installerPackageName);
11652
11653                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11654                            installFlags);
11655
11656                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11657                            pkgLite.packageName);
11658
11659                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11660                            pkgLite.versionCode);
11661
11662                    if (verificationParams != null) {
11663                        if (verificationParams.getVerificationURI() != null) {
11664                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11665                                 verificationParams.getVerificationURI());
11666                        }
11667                        if (verificationParams.getOriginatingURI() != null) {
11668                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11669                                  verificationParams.getOriginatingURI());
11670                        }
11671                        if (verificationParams.getReferrer() != null) {
11672                            verification.putExtra(Intent.EXTRA_REFERRER,
11673                                  verificationParams.getReferrer());
11674                        }
11675                        if (verificationParams.getOriginatingUid() >= 0) {
11676                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11677                                  verificationParams.getOriginatingUid());
11678                        }
11679                        if (verificationParams.getInstallerUid() >= 0) {
11680                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11681                                  verificationParams.getInstallerUid());
11682                        }
11683                    }
11684
11685                    final PackageVerificationState verificationState = new PackageVerificationState(
11686                            requiredUid, args);
11687
11688                    mPendingVerification.append(verificationId, verificationState);
11689
11690                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11691                            receivers, verificationState);
11692
11693                    /*
11694                     * If any sufficient verifiers were listed in the package
11695                     * manifest, attempt to ask them.
11696                     */
11697                    if (sufficientVerifiers != null) {
11698                        final int N = sufficientVerifiers.size();
11699                        if (N == 0) {
11700                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11701                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11702                        } else {
11703                            for (int i = 0; i < N; i++) {
11704                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11705
11706                                final Intent sufficientIntent = new Intent(verification);
11707                                sufficientIntent.setComponent(verifierComponent);
11708                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11709                            }
11710                        }
11711                    }
11712
11713                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11714                            mRequiredVerifierPackage, receivers);
11715                    if (ret == PackageManager.INSTALL_SUCCEEDED
11716                            && mRequiredVerifierPackage != null) {
11717                        Trace.asyncTraceBegin(
11718                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11719                        /*
11720                         * Send the intent to the required verification agent,
11721                         * but only start the verification timeout after the
11722                         * target BroadcastReceivers have run.
11723                         */
11724                        verification.setComponent(requiredVerifierComponent);
11725                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11726                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11727                                new BroadcastReceiver() {
11728                                    @Override
11729                                    public void onReceive(Context context, Intent intent) {
11730                                        final Message msg = mHandler
11731                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11732                                        msg.arg1 = verificationId;
11733                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11734                                    }
11735                                }, null, 0, null, null);
11736
11737                        /*
11738                         * We don't want the copy to proceed until verification
11739                         * succeeds, so null out this field.
11740                         */
11741                        mArgs = null;
11742                    }
11743                } else {
11744                    /*
11745                     * No package verification is enabled, so immediately start
11746                     * the remote call to initiate copy using temporary file.
11747                     */
11748                    ret = args.copyApk(mContainerService, true);
11749                }
11750            }
11751
11752            mRet = ret;
11753        }
11754
11755        @Override
11756        void handleReturnCode() {
11757            // If mArgs is null, then MCS couldn't be reached. When it
11758            // reconnects, it will try again to install. At that point, this
11759            // will succeed.
11760            if (mArgs != null) {
11761                processPendingInstall(mArgs, mRet);
11762            }
11763        }
11764
11765        @Override
11766        void handleServiceError() {
11767            mArgs = createInstallArgs(this);
11768            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11769        }
11770
11771        public boolean isForwardLocked() {
11772            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11773        }
11774    }
11775
11776    /**
11777     * Used during creation of InstallArgs
11778     *
11779     * @param installFlags package installation flags
11780     * @return true if should be installed on external storage
11781     */
11782    private static boolean installOnExternalAsec(int installFlags) {
11783        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11784            return false;
11785        }
11786        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11787            return true;
11788        }
11789        return false;
11790    }
11791
11792    /**
11793     * Used during creation of InstallArgs
11794     *
11795     * @param installFlags package installation flags
11796     * @return true if should be installed as forward locked
11797     */
11798    private static boolean installForwardLocked(int installFlags) {
11799        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11800    }
11801
11802    private InstallArgs createInstallArgs(InstallParams params) {
11803        if (params.move != null) {
11804            return new MoveInstallArgs(params);
11805        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11806            return new AsecInstallArgs(params);
11807        } else {
11808            return new FileInstallArgs(params);
11809        }
11810    }
11811
11812    /**
11813     * Create args that describe an existing installed package. Typically used
11814     * when cleaning up old installs, or used as a move source.
11815     */
11816    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11817            String resourcePath, String[] instructionSets) {
11818        final boolean isInAsec;
11819        if (installOnExternalAsec(installFlags)) {
11820            /* Apps on SD card are always in ASEC containers. */
11821            isInAsec = true;
11822        } else if (installForwardLocked(installFlags)
11823                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11824            /*
11825             * Forward-locked apps are only in ASEC containers if they're the
11826             * new style
11827             */
11828            isInAsec = true;
11829        } else {
11830            isInAsec = false;
11831        }
11832
11833        if (isInAsec) {
11834            return new AsecInstallArgs(codePath, instructionSets,
11835                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11836        } else {
11837            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11838        }
11839    }
11840
11841    static abstract class InstallArgs {
11842        /** @see InstallParams#origin */
11843        final OriginInfo origin;
11844        /** @see InstallParams#move */
11845        final MoveInfo move;
11846
11847        final IPackageInstallObserver2 observer;
11848        // Always refers to PackageManager flags only
11849        final int installFlags;
11850        final String installerPackageName;
11851        final String volumeUuid;
11852        final UserHandle user;
11853        final String abiOverride;
11854        final String[] installGrantPermissions;
11855        /** If non-null, drop an async trace when the install completes */
11856        final String traceMethod;
11857        final int traceCookie;
11858
11859        // The list of instruction sets supported by this app. This is currently
11860        // only used during the rmdex() phase to clean up resources. We can get rid of this
11861        // if we move dex files under the common app path.
11862        /* nullable */ String[] instructionSets;
11863
11864        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11865                int installFlags, String installerPackageName, String volumeUuid,
11866                UserHandle user, String[] instructionSets,
11867                String abiOverride, String[] installGrantPermissions,
11868                String traceMethod, int traceCookie) {
11869            this.origin = origin;
11870            this.move = move;
11871            this.installFlags = installFlags;
11872            this.observer = observer;
11873            this.installerPackageName = installerPackageName;
11874            this.volumeUuid = volumeUuid;
11875            this.user = user;
11876            this.instructionSets = instructionSets;
11877            this.abiOverride = abiOverride;
11878            this.installGrantPermissions = installGrantPermissions;
11879            this.traceMethod = traceMethod;
11880            this.traceCookie = traceCookie;
11881        }
11882
11883        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11884        abstract int doPreInstall(int status);
11885
11886        /**
11887         * Rename package into final resting place. All paths on the given
11888         * scanned package should be updated to reflect the rename.
11889         */
11890        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11891        abstract int doPostInstall(int status, int uid);
11892
11893        /** @see PackageSettingBase#codePathString */
11894        abstract String getCodePath();
11895        /** @see PackageSettingBase#resourcePathString */
11896        abstract String getResourcePath();
11897
11898        // Need installer lock especially for dex file removal.
11899        abstract void cleanUpResourcesLI();
11900        abstract boolean doPostDeleteLI(boolean delete);
11901
11902        /**
11903         * Called before the source arguments are copied. This is used mostly
11904         * for MoveParams when it needs to read the source file to put it in the
11905         * destination.
11906         */
11907        int doPreCopy() {
11908            return PackageManager.INSTALL_SUCCEEDED;
11909        }
11910
11911        /**
11912         * Called after the source arguments are copied. This is used mostly for
11913         * MoveParams when it needs to read the source file to put it in the
11914         * destination.
11915         *
11916         * @return
11917         */
11918        int doPostCopy(int uid) {
11919            return PackageManager.INSTALL_SUCCEEDED;
11920        }
11921
11922        protected boolean isFwdLocked() {
11923            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11924        }
11925
11926        protected boolean isExternalAsec() {
11927            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11928        }
11929
11930        protected boolean isEphemeral() {
11931            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11932        }
11933
11934        UserHandle getUser() {
11935            return user;
11936        }
11937    }
11938
11939    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11940        if (!allCodePaths.isEmpty()) {
11941            if (instructionSets == null) {
11942                throw new IllegalStateException("instructionSet == null");
11943            }
11944            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11945            for (String codePath : allCodePaths) {
11946                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11947                    try {
11948                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11949                    } catch (InstallerException ignored) {
11950                    }
11951                }
11952            }
11953        }
11954    }
11955
11956    /**
11957     * Logic to handle installation of non-ASEC applications, including copying
11958     * and renaming logic.
11959     */
11960    class FileInstallArgs extends InstallArgs {
11961        private File codeFile;
11962        private File resourceFile;
11963
11964        // Example topology:
11965        // /data/app/com.example/base.apk
11966        // /data/app/com.example/split_foo.apk
11967        // /data/app/com.example/lib/arm/libfoo.so
11968        // /data/app/com.example/lib/arm64/libfoo.so
11969        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11970
11971        /** New install */
11972        FileInstallArgs(InstallParams params) {
11973            super(params.origin, params.move, params.observer, params.installFlags,
11974                    params.installerPackageName, params.volumeUuid,
11975                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11976                    params.grantedRuntimePermissions,
11977                    params.traceMethod, params.traceCookie);
11978            if (isFwdLocked()) {
11979                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11980            }
11981        }
11982
11983        /** Existing install */
11984        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11985            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11986                    null, null, null, 0);
11987            this.codeFile = (codePath != null) ? new File(codePath) : null;
11988            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11989        }
11990
11991        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11992            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11993            try {
11994                return doCopyApk(imcs, temp);
11995            } finally {
11996                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11997            }
11998        }
11999
12000        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12001            if (origin.staged) {
12002                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12003                codeFile = origin.file;
12004                resourceFile = origin.file;
12005                return PackageManager.INSTALL_SUCCEEDED;
12006            }
12007
12008            try {
12009                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12010                final File tempDir =
12011                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12012                codeFile = tempDir;
12013                resourceFile = tempDir;
12014            } catch (IOException e) {
12015                Slog.w(TAG, "Failed to create copy file: " + e);
12016                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12017            }
12018
12019            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12020                @Override
12021                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12022                    if (!FileUtils.isValidExtFilename(name)) {
12023                        throw new IllegalArgumentException("Invalid filename: " + name);
12024                    }
12025                    try {
12026                        final File file = new File(codeFile, name);
12027                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12028                                O_RDWR | O_CREAT, 0644);
12029                        Os.chmod(file.getAbsolutePath(), 0644);
12030                        return new ParcelFileDescriptor(fd);
12031                    } catch (ErrnoException e) {
12032                        throw new RemoteException("Failed to open: " + e.getMessage());
12033                    }
12034                }
12035            };
12036
12037            int ret = PackageManager.INSTALL_SUCCEEDED;
12038            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12039            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12040                Slog.e(TAG, "Failed to copy package");
12041                return ret;
12042            }
12043
12044            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12045            NativeLibraryHelper.Handle handle = null;
12046            try {
12047                handle = NativeLibraryHelper.Handle.create(codeFile);
12048                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12049                        abiOverride);
12050            } catch (IOException e) {
12051                Slog.e(TAG, "Copying native libraries failed", e);
12052                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12053            } finally {
12054                IoUtils.closeQuietly(handle);
12055            }
12056
12057            return ret;
12058        }
12059
12060        int doPreInstall(int status) {
12061            if (status != PackageManager.INSTALL_SUCCEEDED) {
12062                cleanUp();
12063            }
12064            return status;
12065        }
12066
12067        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12068            if (status != PackageManager.INSTALL_SUCCEEDED) {
12069                cleanUp();
12070                return false;
12071            }
12072
12073            final File targetDir = codeFile.getParentFile();
12074            final File beforeCodeFile = codeFile;
12075            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12076
12077            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12078            try {
12079                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12080            } catch (ErrnoException e) {
12081                Slog.w(TAG, "Failed to rename", e);
12082                return false;
12083            }
12084
12085            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12086                Slog.w(TAG, "Failed to restorecon");
12087                return false;
12088            }
12089
12090            // Reflect the rename internally
12091            codeFile = afterCodeFile;
12092            resourceFile = afterCodeFile;
12093
12094            // Reflect the rename in scanned details
12095            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12096            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12097                    afterCodeFile, pkg.baseCodePath));
12098            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12099                    afterCodeFile, pkg.splitCodePaths));
12100
12101            // Reflect the rename in app info
12102            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12103            pkg.setApplicationInfoCodePath(pkg.codePath);
12104            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12105            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12106            pkg.setApplicationInfoResourcePath(pkg.codePath);
12107            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12108            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12109
12110            return true;
12111        }
12112
12113        int doPostInstall(int status, int uid) {
12114            if (status != PackageManager.INSTALL_SUCCEEDED) {
12115                cleanUp();
12116            }
12117            return status;
12118        }
12119
12120        @Override
12121        String getCodePath() {
12122            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12123        }
12124
12125        @Override
12126        String getResourcePath() {
12127            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12128        }
12129
12130        private boolean cleanUp() {
12131            if (codeFile == null || !codeFile.exists()) {
12132                return false;
12133            }
12134
12135            removeCodePathLI(codeFile);
12136
12137            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12138                resourceFile.delete();
12139            }
12140
12141            return true;
12142        }
12143
12144        void cleanUpResourcesLI() {
12145            // Try enumerating all code paths before deleting
12146            List<String> allCodePaths = Collections.EMPTY_LIST;
12147            if (codeFile != null && codeFile.exists()) {
12148                try {
12149                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12150                    allCodePaths = pkg.getAllCodePaths();
12151                } catch (PackageParserException e) {
12152                    // Ignored; we tried our best
12153                }
12154            }
12155
12156            cleanUp();
12157            removeDexFiles(allCodePaths, instructionSets);
12158        }
12159
12160        boolean doPostDeleteLI(boolean delete) {
12161            // XXX err, shouldn't we respect the delete flag?
12162            cleanUpResourcesLI();
12163            return true;
12164        }
12165    }
12166
12167    private boolean isAsecExternal(String cid) {
12168        final String asecPath = PackageHelper.getSdFilesystem(cid);
12169        return !asecPath.startsWith(mAsecInternalPath);
12170    }
12171
12172    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12173            PackageManagerException {
12174        if (copyRet < 0) {
12175            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12176                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12177                throw new PackageManagerException(copyRet, message);
12178            }
12179        }
12180    }
12181
12182    /**
12183     * Extract the MountService "container ID" from the full code path of an
12184     * .apk.
12185     */
12186    static String cidFromCodePath(String fullCodePath) {
12187        int eidx = fullCodePath.lastIndexOf("/");
12188        String subStr1 = fullCodePath.substring(0, eidx);
12189        int sidx = subStr1.lastIndexOf("/");
12190        return subStr1.substring(sidx+1, eidx);
12191    }
12192
12193    /**
12194     * Logic to handle installation of ASEC applications, including copying and
12195     * renaming logic.
12196     */
12197    class AsecInstallArgs extends InstallArgs {
12198        static final String RES_FILE_NAME = "pkg.apk";
12199        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12200
12201        String cid;
12202        String packagePath;
12203        String resourcePath;
12204
12205        /** New install */
12206        AsecInstallArgs(InstallParams params) {
12207            super(params.origin, params.move, params.observer, params.installFlags,
12208                    params.installerPackageName, params.volumeUuid,
12209                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12210                    params.grantedRuntimePermissions,
12211                    params.traceMethod, params.traceCookie);
12212        }
12213
12214        /** Existing install */
12215        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12216                        boolean isExternal, boolean isForwardLocked) {
12217            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12218                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12219                    instructionSets, null, null, null, 0);
12220            // Hackily pretend we're still looking at a full code path
12221            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12222                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12223            }
12224
12225            // Extract cid from fullCodePath
12226            int eidx = fullCodePath.lastIndexOf("/");
12227            String subStr1 = fullCodePath.substring(0, eidx);
12228            int sidx = subStr1.lastIndexOf("/");
12229            cid = subStr1.substring(sidx+1, eidx);
12230            setMountPath(subStr1);
12231        }
12232
12233        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12234            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12235                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12236                    instructionSets, null, null, null, 0);
12237            this.cid = cid;
12238            setMountPath(PackageHelper.getSdDir(cid));
12239        }
12240
12241        void createCopyFile() {
12242            cid = mInstallerService.allocateExternalStageCidLegacy();
12243        }
12244
12245        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12246            if (origin.staged && origin.cid != null) {
12247                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12248                cid = origin.cid;
12249                setMountPath(PackageHelper.getSdDir(cid));
12250                return PackageManager.INSTALL_SUCCEEDED;
12251            }
12252
12253            if (temp) {
12254                createCopyFile();
12255            } else {
12256                /*
12257                 * Pre-emptively destroy the container since it's destroyed if
12258                 * copying fails due to it existing anyway.
12259                 */
12260                PackageHelper.destroySdDir(cid);
12261            }
12262
12263            final String newMountPath = imcs.copyPackageToContainer(
12264                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12265                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12266
12267            if (newMountPath != null) {
12268                setMountPath(newMountPath);
12269                return PackageManager.INSTALL_SUCCEEDED;
12270            } else {
12271                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12272            }
12273        }
12274
12275        @Override
12276        String getCodePath() {
12277            return packagePath;
12278        }
12279
12280        @Override
12281        String getResourcePath() {
12282            return resourcePath;
12283        }
12284
12285        int doPreInstall(int status) {
12286            if (status != PackageManager.INSTALL_SUCCEEDED) {
12287                // Destroy container
12288                PackageHelper.destroySdDir(cid);
12289            } else {
12290                boolean mounted = PackageHelper.isContainerMounted(cid);
12291                if (!mounted) {
12292                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12293                            Process.SYSTEM_UID);
12294                    if (newMountPath != null) {
12295                        setMountPath(newMountPath);
12296                    } else {
12297                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12298                    }
12299                }
12300            }
12301            return status;
12302        }
12303
12304        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12305            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12306            String newMountPath = null;
12307            if (PackageHelper.isContainerMounted(cid)) {
12308                // Unmount the container
12309                if (!PackageHelper.unMountSdDir(cid)) {
12310                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12311                    return false;
12312                }
12313            }
12314            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12315                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12316                        " which might be stale. Will try to clean up.");
12317                // Clean up the stale container and proceed to recreate.
12318                if (!PackageHelper.destroySdDir(newCacheId)) {
12319                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12320                    return false;
12321                }
12322                // Successfully cleaned up stale container. Try to rename again.
12323                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12324                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12325                            + " inspite of cleaning it up.");
12326                    return false;
12327                }
12328            }
12329            if (!PackageHelper.isContainerMounted(newCacheId)) {
12330                Slog.w(TAG, "Mounting container " + newCacheId);
12331                newMountPath = PackageHelper.mountSdDir(newCacheId,
12332                        getEncryptKey(), Process.SYSTEM_UID);
12333            } else {
12334                newMountPath = PackageHelper.getSdDir(newCacheId);
12335            }
12336            if (newMountPath == null) {
12337                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12338                return false;
12339            }
12340            Log.i(TAG, "Succesfully renamed " + cid +
12341                    " to " + newCacheId +
12342                    " at new path: " + newMountPath);
12343            cid = newCacheId;
12344
12345            final File beforeCodeFile = new File(packagePath);
12346            setMountPath(newMountPath);
12347            final File afterCodeFile = new File(packagePath);
12348
12349            // Reflect the rename in scanned details
12350            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12351            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12352                    afterCodeFile, pkg.baseCodePath));
12353            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12354                    afterCodeFile, pkg.splitCodePaths));
12355
12356            // Reflect the rename in app info
12357            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12358            pkg.setApplicationInfoCodePath(pkg.codePath);
12359            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12360            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12361            pkg.setApplicationInfoResourcePath(pkg.codePath);
12362            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12363            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12364
12365            return true;
12366        }
12367
12368        private void setMountPath(String mountPath) {
12369            final File mountFile = new File(mountPath);
12370
12371            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12372            if (monolithicFile.exists()) {
12373                packagePath = monolithicFile.getAbsolutePath();
12374                if (isFwdLocked()) {
12375                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12376                } else {
12377                    resourcePath = packagePath;
12378                }
12379            } else {
12380                packagePath = mountFile.getAbsolutePath();
12381                resourcePath = packagePath;
12382            }
12383        }
12384
12385        int doPostInstall(int status, int uid) {
12386            if (status != PackageManager.INSTALL_SUCCEEDED) {
12387                cleanUp();
12388            } else {
12389                final int groupOwner;
12390                final String protectedFile;
12391                if (isFwdLocked()) {
12392                    groupOwner = UserHandle.getSharedAppGid(uid);
12393                    protectedFile = RES_FILE_NAME;
12394                } else {
12395                    groupOwner = -1;
12396                    protectedFile = null;
12397                }
12398
12399                if (uid < Process.FIRST_APPLICATION_UID
12400                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12401                    Slog.e(TAG, "Failed to finalize " + cid);
12402                    PackageHelper.destroySdDir(cid);
12403                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12404                }
12405
12406                boolean mounted = PackageHelper.isContainerMounted(cid);
12407                if (!mounted) {
12408                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12409                }
12410            }
12411            return status;
12412        }
12413
12414        private void cleanUp() {
12415            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12416
12417            // Destroy secure container
12418            PackageHelper.destroySdDir(cid);
12419        }
12420
12421        private List<String> getAllCodePaths() {
12422            final File codeFile = new File(getCodePath());
12423            if (codeFile != null && codeFile.exists()) {
12424                try {
12425                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12426                    return pkg.getAllCodePaths();
12427                } catch (PackageParserException e) {
12428                    // Ignored; we tried our best
12429                }
12430            }
12431            return Collections.EMPTY_LIST;
12432        }
12433
12434        void cleanUpResourcesLI() {
12435            // Enumerate all code paths before deleting
12436            cleanUpResourcesLI(getAllCodePaths());
12437        }
12438
12439        private void cleanUpResourcesLI(List<String> allCodePaths) {
12440            cleanUp();
12441            removeDexFiles(allCodePaths, instructionSets);
12442        }
12443
12444        String getPackageName() {
12445            return getAsecPackageName(cid);
12446        }
12447
12448        boolean doPostDeleteLI(boolean delete) {
12449            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12450            final List<String> allCodePaths = getAllCodePaths();
12451            boolean mounted = PackageHelper.isContainerMounted(cid);
12452            if (mounted) {
12453                // Unmount first
12454                if (PackageHelper.unMountSdDir(cid)) {
12455                    mounted = false;
12456                }
12457            }
12458            if (!mounted && delete) {
12459                cleanUpResourcesLI(allCodePaths);
12460            }
12461            return !mounted;
12462        }
12463
12464        @Override
12465        int doPreCopy() {
12466            if (isFwdLocked()) {
12467                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12468                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12469                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12470                }
12471            }
12472
12473            return PackageManager.INSTALL_SUCCEEDED;
12474        }
12475
12476        @Override
12477        int doPostCopy(int uid) {
12478            if (isFwdLocked()) {
12479                if (uid < Process.FIRST_APPLICATION_UID
12480                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12481                                RES_FILE_NAME)) {
12482                    Slog.e(TAG, "Failed to finalize " + cid);
12483                    PackageHelper.destroySdDir(cid);
12484                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12485                }
12486            }
12487
12488            return PackageManager.INSTALL_SUCCEEDED;
12489        }
12490    }
12491
12492    /**
12493     * Logic to handle movement of existing installed applications.
12494     */
12495    class MoveInstallArgs extends InstallArgs {
12496        private File codeFile;
12497        private File resourceFile;
12498
12499        /** New install */
12500        MoveInstallArgs(InstallParams params) {
12501            super(params.origin, params.move, params.observer, params.installFlags,
12502                    params.installerPackageName, params.volumeUuid,
12503                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12504                    params.grantedRuntimePermissions,
12505                    params.traceMethod, params.traceCookie);
12506        }
12507
12508        int copyApk(IMediaContainerService imcs, boolean temp) {
12509            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12510                    + move.fromUuid + " to " + move.toUuid);
12511            synchronized (mInstaller) {
12512                try {
12513                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12514                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12515                } catch (InstallerException e) {
12516                    Slog.w(TAG, "Failed to move app", e);
12517                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12518                }
12519            }
12520
12521            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12522            resourceFile = codeFile;
12523            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12524
12525            return PackageManager.INSTALL_SUCCEEDED;
12526        }
12527
12528        int doPreInstall(int status) {
12529            if (status != PackageManager.INSTALL_SUCCEEDED) {
12530                cleanUp(move.toUuid);
12531            }
12532            return status;
12533        }
12534
12535        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12536            if (status != PackageManager.INSTALL_SUCCEEDED) {
12537                cleanUp(move.toUuid);
12538                return false;
12539            }
12540
12541            // Reflect the move in app info
12542            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12543            pkg.setApplicationInfoCodePath(pkg.codePath);
12544            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12545            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12546            pkg.setApplicationInfoResourcePath(pkg.codePath);
12547            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12548            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12549
12550            return true;
12551        }
12552
12553        int doPostInstall(int status, int uid) {
12554            if (status == PackageManager.INSTALL_SUCCEEDED) {
12555                cleanUp(move.fromUuid);
12556            } else {
12557                cleanUp(move.toUuid);
12558            }
12559            return status;
12560        }
12561
12562        @Override
12563        String getCodePath() {
12564            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12565        }
12566
12567        @Override
12568        String getResourcePath() {
12569            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12570        }
12571
12572        private boolean cleanUp(String volumeUuid) {
12573            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12574                    move.dataAppName);
12575            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12576            synchronized (mInstallLock) {
12577                // Clean up both app data and code
12578                removeDataDirsLI(volumeUuid, move.packageName);
12579                removeCodePathLI(codeFile);
12580            }
12581            return true;
12582        }
12583
12584        void cleanUpResourcesLI() {
12585            throw new UnsupportedOperationException();
12586        }
12587
12588        boolean doPostDeleteLI(boolean delete) {
12589            throw new UnsupportedOperationException();
12590        }
12591    }
12592
12593    static String getAsecPackageName(String packageCid) {
12594        int idx = packageCid.lastIndexOf("-");
12595        if (idx == -1) {
12596            return packageCid;
12597        }
12598        return packageCid.substring(0, idx);
12599    }
12600
12601    // Utility method used to create code paths based on package name and available index.
12602    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12603        String idxStr = "";
12604        int idx = 1;
12605        // Fall back to default value of idx=1 if prefix is not
12606        // part of oldCodePath
12607        if (oldCodePath != null) {
12608            String subStr = oldCodePath;
12609            // Drop the suffix right away
12610            if (suffix != null && subStr.endsWith(suffix)) {
12611                subStr = subStr.substring(0, subStr.length() - suffix.length());
12612            }
12613            // If oldCodePath already contains prefix find out the
12614            // ending index to either increment or decrement.
12615            int sidx = subStr.lastIndexOf(prefix);
12616            if (sidx != -1) {
12617                subStr = subStr.substring(sidx + prefix.length());
12618                if (subStr != null) {
12619                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12620                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12621                    }
12622                    try {
12623                        idx = Integer.parseInt(subStr);
12624                        if (idx <= 1) {
12625                            idx++;
12626                        } else {
12627                            idx--;
12628                        }
12629                    } catch(NumberFormatException e) {
12630                    }
12631                }
12632            }
12633        }
12634        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12635        return prefix + idxStr;
12636    }
12637
12638    private File getNextCodePath(File targetDir, String packageName) {
12639        int suffix = 1;
12640        File result;
12641        do {
12642            result = new File(targetDir, packageName + "-" + suffix);
12643            suffix++;
12644        } while (result.exists());
12645        return result;
12646    }
12647
12648    // Utility method that returns the relative package path with respect
12649    // to the installation directory. Like say for /data/data/com.test-1.apk
12650    // string com.test-1 is returned.
12651    static String deriveCodePathName(String codePath) {
12652        if (codePath == null) {
12653            return null;
12654        }
12655        final File codeFile = new File(codePath);
12656        final String name = codeFile.getName();
12657        if (codeFile.isDirectory()) {
12658            return name;
12659        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12660            final int lastDot = name.lastIndexOf('.');
12661            return name.substring(0, lastDot);
12662        } else {
12663            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12664            return null;
12665        }
12666    }
12667
12668    static class PackageInstalledInfo {
12669        String name;
12670        int uid;
12671        // The set of users that originally had this package installed.
12672        int[] origUsers;
12673        // The set of users that now have this package installed.
12674        int[] newUsers;
12675        PackageParser.Package pkg;
12676        int returnCode;
12677        String returnMsg;
12678        PackageRemovedInfo removedInfo;
12679
12680        public void setError(int code, String msg) {
12681            returnCode = code;
12682            returnMsg = msg;
12683            Slog.w(TAG, msg);
12684        }
12685
12686        public void setError(String msg, PackageParserException e) {
12687            returnCode = e.error;
12688            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12689            Slog.w(TAG, msg, e);
12690        }
12691
12692        public void setError(String msg, PackageManagerException e) {
12693            returnCode = e.error;
12694            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12695            Slog.w(TAG, msg, e);
12696        }
12697
12698        // In some error cases we want to convey more info back to the observer
12699        String origPackage;
12700        String origPermission;
12701    }
12702
12703    /*
12704     * Install a non-existing package.
12705     */
12706    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12707            UserHandle user, String installerPackageName, String volumeUuid,
12708            PackageInstalledInfo res) {
12709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12710
12711        // Remember this for later, in case we need to rollback this install
12712        String pkgName = pkg.packageName;
12713
12714        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12715        // TODO: b/23350563
12716        final boolean dataDirExists = Environment
12717                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12718
12719        synchronized(mPackages) {
12720            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12721                // A package with the same name is already installed, though
12722                // it has been renamed to an older name.  The package we
12723                // are trying to install should be installed as an update to
12724                // the existing one, but that has not been requested, so bail.
12725                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12726                        + " without first uninstalling package running as "
12727                        + mSettings.mRenamedPackages.get(pkgName));
12728                return;
12729            }
12730            if (mPackages.containsKey(pkgName)) {
12731                // Don't allow installation over an existing package with the same name.
12732                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12733                        + " without first uninstalling.");
12734                return;
12735            }
12736        }
12737
12738        try {
12739            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12740                    System.currentTimeMillis(), user);
12741
12742            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
12743            prepareAppDataAfterInstall(newPackage);
12744
12745            // delete the partially installed application. the data directory will have to be
12746            // restored if it was already existing
12747            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12748                // remove package from internal structures.  Note that we want deletePackageX to
12749                // delete the package data and cache directories that it created in
12750                // scanPackageLocked, unless those directories existed before we even tried to
12751                // install.
12752                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12753                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12754                                res.removedInfo, true, null);
12755            }
12756
12757        } catch (PackageManagerException e) {
12758            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12759        }
12760
12761        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12762    }
12763
12764    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12765        // Can't rotate keys during boot or if sharedUser.
12766        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12767                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12768            return false;
12769        }
12770        // app is using upgradeKeySets; make sure all are valid
12771        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12772        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12773        for (int i = 0; i < upgradeKeySets.length; i++) {
12774            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12775                Slog.wtf(TAG, "Package "
12776                         + (oldPs.name != null ? oldPs.name : "<null>")
12777                         + " contains upgrade-key-set reference to unknown key-set: "
12778                         + upgradeKeySets[i]
12779                         + " reverting to signatures check.");
12780                return false;
12781            }
12782        }
12783        return true;
12784    }
12785
12786    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12787        // Upgrade keysets are being used.  Determine if new package has a superset of the
12788        // required keys.
12789        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12790        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12791        for (int i = 0; i < upgradeKeySets.length; i++) {
12792            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12793            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12794                return true;
12795            }
12796        }
12797        return false;
12798    }
12799
12800    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12801            UserHandle user, String installerPackageName, String volumeUuid,
12802            PackageInstalledInfo res) {
12803        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12804
12805        final PackageParser.Package oldPackage;
12806        final String pkgName = pkg.packageName;
12807        final int[] allUsers;
12808        final boolean[] perUserInstalled;
12809
12810        // First find the old package info and check signatures
12811        synchronized(mPackages) {
12812            oldPackage = mPackages.get(pkgName);
12813            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12814            if (isEphemeral && !oldIsEphemeral) {
12815                // can't downgrade from full to ephemeral
12816                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12817                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12818                return;
12819            }
12820            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12821            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12822            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12823                if (!checkUpgradeKeySetLP(ps, pkg)) {
12824                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12825                            "New package not signed by keys specified by upgrade-keysets: "
12826                                    + pkgName);
12827                    return;
12828                }
12829            } else {
12830                // default to original signature matching
12831                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12832                        != PackageManager.SIGNATURE_MATCH) {
12833                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12834                            "New package has a different signature: " + pkgName);
12835                    return;
12836                }
12837            }
12838
12839            // In case of rollback, remember per-user/profile install state
12840            allUsers = sUserManager.getUserIds();
12841            perUserInstalled = new boolean[allUsers.length];
12842            for (int i = 0; i < allUsers.length; i++) {
12843                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12844            }
12845        }
12846
12847        boolean sysPkg = (isSystemApp(oldPackage));
12848        if (sysPkg) {
12849            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12850                    user, allUsers, perUserInstalled, installerPackageName, res);
12851        } else {
12852            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12853                    user, allUsers, perUserInstalled, installerPackageName, res);
12854        }
12855    }
12856
12857    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12858            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12859            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12860            PackageInstalledInfo res) {
12861        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12862                + deletedPackage);
12863
12864        String pkgName = deletedPackage.packageName;
12865        boolean deletedPkg = true;
12866        boolean addedPkg = false;
12867
12868        final long origUpdateTime = (pkg.mExtras != null)
12869                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
12870
12871        // First delete the existing package while retaining the data directory
12872        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12873                res.removedInfo, true, pkg)) {
12874            // If the existing package wasn't successfully deleted
12875            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12876            deletedPkg = false;
12877        } else {
12878            // Successfully deleted the old package; proceed with replace.
12879
12880            // If deleted package lived in a container, give users a chance to
12881            // relinquish resources before killing.
12882            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12883                if (DEBUG_INSTALL) {
12884                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12885                }
12886                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12887                final ArrayList<String> pkgList = new ArrayList<String>(1);
12888                pkgList.add(deletedPackage.applicationInfo.packageName);
12889                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12890            }
12891
12892            deleteCodeCacheDirsLI(pkg);
12893
12894            try {
12895                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12896                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12897                updateSettingsLI(newPackage, installerPackageName, allUsers,
12898                        perUserInstalled, res, user);
12899                prepareAppDataAfterInstall(newPackage);
12900                addedPkg = true;
12901            } catch (PackageManagerException e) {
12902                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12903            }
12904        }
12905
12906        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12907            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12908
12909            // Revert all internal state mutations and added folders for the failed install
12910            if (addedPkg) {
12911                deletePackageLI(pkgName, null, true, allUsers, perUserInstalled,
12912                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12913            }
12914
12915            // Restore the old package
12916            if (deletedPkg) {
12917                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12918                File restoreFile = new File(deletedPackage.codePath);
12919                // Parse old package
12920                boolean oldExternal = isExternal(deletedPackage);
12921                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12922                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12923                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12924                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12925                try {
12926                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12927                            null);
12928                } catch (PackageManagerException e) {
12929                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12930                            + e.getMessage());
12931                    return;
12932                }
12933
12934                synchronized (mPackages) {
12935                    // Ensure the installer package name up to date
12936                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
12937
12938                    // Update permissions for restored package
12939                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
12940
12941                    mSettings.writeLPr();
12942                }
12943
12944                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12945            }
12946        }
12947    }
12948
12949    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12950            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12951            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12952            PackageInstalledInfo res) {
12953        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12954                + ", old=" + deletedPackage);
12955
12956        final boolean disabledSystem;
12957
12958        // Set the system/privileged flags as needed
12959        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12960        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12961                != 0) {
12962            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12963        }
12964
12965        // Kill package processes including services, providers, etc.
12966        killPackage(deletedPackage, "replace sys pkg");
12967
12968        // Report the result for the parent package only
12969        res.removedInfo.uid = deletedPackage.applicationInfo.uid;
12970        res.removedInfo.removedPackage = deletedPackage.packageName;
12971
12972        // Remove existing system package
12973        removePackageSettingLI(deletedPackage, true);
12974
12975        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
12976        if (!disabledSystem) {
12977            // We didn't need to disable the .apk as a current system package,
12978            // which means we are replacing another update that is already
12979            // installed.  We need to make sure to delete the older one's .apk.
12980            res.removedInfo.args = createInstallArgsForExisting(0,
12981                    deletedPackage.applicationInfo.getCodePath(),
12982                    deletedPackage.applicationInfo.getResourcePath(),
12983                    getAppDexInstructionSets(deletedPackage.applicationInfo));
12984        } else {
12985            res.removedInfo.args = null;
12986        }
12987
12988        // Successfully disabled the old package. Now proceed with re-installation
12989        deleteCodeCacheDirsLI(pkg);
12990
12991        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12992        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
12993                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
12994
12995        PackageParser.Package newPackage = null;
12996        try {
12997            // Add the package to the internal data structures
12998            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12999
13000            // Set the update and install times
13001            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13002            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13003                    System.currentTimeMillis());
13004
13005            // Check for shared user id changes
13006            String invalidPackageName = getParentOrChildPackageChangedSharedUser(deletedPackage, newPackage);
13007            if (invalidPackageName != null) {
13008                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13009                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13010                                + " to " + invalidPackageName);
13011            }
13012
13013            // Update the package dynamic state if succeeded
13014            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13015                // Now that the install succeeded make sure we remove data
13016                // directories for any child package the update removed.
13017                final int deletedChildCount = (deletedPackage.childPackages != null)
13018                        ? deletedPackage.childPackages.size() : 0;
13019                final int newChildCount = (newPackage.childPackages != null)
13020                        ? newPackage.childPackages.size() : 0;
13021                for (int i = 0; i < deletedChildCount; i++) {
13022                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13023                    boolean childPackageDeleted = true;
13024                    for (int j = 0; j < newChildCount; j++) {
13025                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13026                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13027                            childPackageDeleted = false;
13028                            break;
13029                        }
13030                    }
13031                    if (childPackageDeleted) {
13032                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13033                                deletedChildPkg.packageName);
13034                        if (ps != null) {
13035                            removePackageDataLI(ps, allUsers, perUserInstalled, null, 0, false);
13036                        }
13037                    }
13038                }
13039
13040                updateSettingsLI(newPackage, installerPackageName, allUsers,
13041                        perUserInstalled, res, user);
13042                prepareAppDataAfterInstall(newPackage);
13043            }
13044        } catch (PackageManagerException e) {
13045            res.returnCode = INSTALL_FAILED_INTERNAL_ERROR;
13046            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13047        }
13048
13049        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13050            // Re installation failed. Restore old information
13051            // Remove new pkg information
13052            if (newPackage != null) {
13053                removeInstalledPackageLI(newPackage, true);
13054            }
13055            // Add back the old system package
13056            try {
13057                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13058            } catch (PackageManagerException e) {
13059                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13060            }
13061
13062            synchronized (mPackages) {
13063                if (disabledSystem) {
13064                    enableSystemPackageLPw(deletedPackage);
13065                }
13066
13067                // Ensure the installer package name up to date
13068                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13069
13070                // Update permissions for restored package
13071                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13072
13073                mSettings.writeLPr();
13074            }
13075
13076            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13077                    + " after failed upgrade");
13078        }
13079    }
13080
13081    /**
13082     * Checks whether the parent or any of the child packages have a change shared
13083     * user. For a package to be a valid update the shred users of the parent and
13084     * the children should match. We may later support changing child shared users.
13085     * @param oldPkg The updated package.
13086     * @param newPkg The update package.
13087     * @return The shared user that change between the versions.
13088     */
13089    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13090            PackageParser.Package newPkg) {
13091        // Check parent shared user
13092        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13093            return newPkg.packageName;
13094        }
13095        // Check child shared users
13096        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13097        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13098        for (int i = 0; i < newChildCount; i++) {
13099            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13100            // If this child was present, did it have the same shared user?
13101            for (int j = 0; j < oldChildCount; j++) {
13102                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13103                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13104                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13105                    return newChildPkg.packageName;
13106                }
13107            }
13108        }
13109        return null;
13110    }
13111
13112    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13113        // Remove the lib path for the parent package
13114        PackageSetting ps = (PackageSetting) pkg.mExtras;
13115        if (ps != null) {
13116            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13117        }
13118        // Remove the lib path for the child packages
13119        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13120        for (int i = 0; i < childCount; i++) {
13121            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13122            if (ps != null) {
13123                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13124            }
13125        }
13126    }
13127
13128    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13129        // Enable the parent package
13130        mSettings.enableSystemPackageLPw(pkg.packageName);
13131        // Enable the child packages
13132        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13133        for (int i = 0; i < childCount; i++) {
13134            PackageParser.Package childPkg = pkg.childPackages.get(i);
13135            mSettings.enableSystemPackageLPw(childPkg.packageName);
13136        }
13137    }
13138
13139    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13140            PackageParser.Package newPkg) {
13141        // Disable the parent package (parent always replaced)
13142        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13143        // Disable the child packages
13144        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13145        for (int i = 0; i < childCount; i++) {
13146            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13147            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13148            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13149        }
13150        return disabled;
13151    }
13152
13153    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13154            String installerPackageName) {
13155        // Enable the parent package
13156        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13157        // Enable the child packages
13158        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13159        for (int i = 0; i < childCount; i++) {
13160            PackageParser.Package childPkg = pkg.childPackages.get(i);
13161            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13162        }
13163    }
13164
13165    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13166        // Collect all used permissions in the UID
13167        ArraySet<String> usedPermissions = new ArraySet<>();
13168        final int packageCount = su.packages.size();
13169        for (int i = 0; i < packageCount; i++) {
13170            PackageSetting ps = su.packages.valueAt(i);
13171            if (ps.pkg == null) {
13172                continue;
13173            }
13174            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13175            for (int j = 0; j < requestedPermCount; j++) {
13176                String permission = ps.pkg.requestedPermissions.get(j);
13177                BasePermission bp = mSettings.mPermissions.get(permission);
13178                if (bp != null) {
13179                    usedPermissions.add(permission);
13180                }
13181            }
13182        }
13183
13184        PermissionsState permissionsState = su.getPermissionsState();
13185        // Prune install permissions
13186        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13187        final int installPermCount = installPermStates.size();
13188        for (int i = installPermCount - 1; i >= 0;  i--) {
13189            PermissionState permissionState = installPermStates.get(i);
13190            if (!usedPermissions.contains(permissionState.getName())) {
13191                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13192                if (bp != null) {
13193                    permissionsState.revokeInstallPermission(bp);
13194                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13195                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13196                }
13197            }
13198        }
13199
13200        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13201
13202        // Prune runtime permissions
13203        for (int userId : allUserIds) {
13204            List<PermissionState> runtimePermStates = permissionsState
13205                    .getRuntimePermissionStates(userId);
13206            final int runtimePermCount = runtimePermStates.size();
13207            for (int i = runtimePermCount - 1; i >= 0; i--) {
13208                PermissionState permissionState = runtimePermStates.get(i);
13209                if (!usedPermissions.contains(permissionState.getName())) {
13210                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13211                    if (bp != null) {
13212                        permissionsState.revokeRuntimePermission(bp, userId);
13213                        permissionsState.updatePermissionFlags(bp, userId,
13214                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13215                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13216                                runtimePermissionChangedUserIds, userId);
13217                    }
13218                }
13219            }
13220        }
13221
13222        return runtimePermissionChangedUserIds;
13223    }
13224
13225    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13226            int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, UserHandle user) {
13227        // Update the parent package setting
13228        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, perUserInstalled,
13229                res, user);
13230        // Update the child packages setting
13231        final int childCount = (newPackage.childPackages != null)
13232                ? newPackage.childPackages.size() : 0;
13233        for (int i = 0; i < childCount; i++) {
13234            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13235            updateSettingsInternalLI(childPackage, installerPackageName, allUsers, perUserInstalled,
13236                    res, user);
13237        }
13238    }
13239
13240    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13241            String installerPackageName, int[] allUsers, boolean[] perUserInstalled,
13242            PackageInstalledInfo res, UserHandle user) {
13243        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13244
13245        String pkgName = newPackage.packageName;
13246        synchronized (mPackages) {
13247            //write settings. the installStatus will be incomplete at this stage.
13248            //note that the new package setting would have already been
13249            //added to mPackages. It hasn't been persisted yet.
13250            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13251            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13252            mSettings.writeLPr();
13253            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13254        }
13255
13256        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13257        synchronized (mPackages) {
13258            updatePermissionsLPw(newPackage.packageName, newPackage,
13259                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13260                            ? UPDATE_PERMISSIONS_ALL : 0));
13261            // For system-bundled packages, we assume that installing an upgraded version
13262            // of the package implies that the user actually wants to run that new code,
13263            // so we enable the package.
13264            PackageSetting ps = mSettings.mPackages.get(pkgName);
13265            if (ps != null) {
13266                if (isSystemApp(newPackage)) {
13267                    // NB: implicit assumption that system package upgrades apply to all users
13268                    if (DEBUG_INSTALL) {
13269                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13270                    }
13271                    if (res.origUsers != null) {
13272                        for (int userHandle : res.origUsers) {
13273                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13274                                    userHandle, installerPackageName);
13275                        }
13276                    }
13277                    // Also convey the prior install/uninstall state
13278                    if (allUsers != null && perUserInstalled != null) {
13279                        for (int i = 0; i < allUsers.length; i++) {
13280                            if (DEBUG_INSTALL) {
13281                                Slog.d(TAG, "    user " + allUsers[i]
13282                                        + " => " + perUserInstalled[i]);
13283                            }
13284                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
13285                        }
13286                        // these install state changes will be persisted in the
13287                        // upcoming call to mSettings.writeLPr().
13288                    }
13289                }
13290                // It's implied that when a user requests installation, they want the app to be
13291                // installed and enabled.
13292                int userId = user.getIdentifier();
13293                if (userId != UserHandle.USER_ALL) {
13294                    ps.setInstalled(true, userId);
13295                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13296                }
13297            }
13298            res.name = pkgName;
13299            res.uid = newPackage.applicationInfo.uid;
13300            res.pkg = newPackage;
13301            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13302            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13303            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13304            //to update install status
13305            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13306            mSettings.writeLPr();
13307            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13308        }
13309
13310        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13311    }
13312
13313    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13314        try {
13315            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13316            installPackageLI(args, res);
13317        } finally {
13318            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13319        }
13320    }
13321
13322    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13323        final int installFlags = args.installFlags;
13324        final String installerPackageName = args.installerPackageName;
13325        final String volumeUuid = args.volumeUuid;
13326        final File tmpPackageFile = new File(args.getCodePath());
13327        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13328        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13329                || (args.volumeUuid != null));
13330        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13331        boolean replace = false;
13332        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13333        if (args.move != null) {
13334            // moving a complete application; perfom an initial scan on the new install location
13335            scanFlags |= SCAN_INITIAL;
13336        }
13337        // Result object to be returned
13338        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13339
13340        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13341
13342        // Sanity check
13343        if (ephemeral && (forwardLocked || onExternal)) {
13344            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13345                    + " external=" + onExternal);
13346            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
13347            return;
13348        }
13349
13350        // Retrieve PackageSettings and parse package
13351        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13352                | PackageParser.PARSE_ENFORCE_CODE
13353                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13354                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13355                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13356        PackageParser pp = new PackageParser();
13357        pp.setSeparateProcesses(mSeparateProcesses);
13358        pp.setDisplayMetrics(mMetrics);
13359
13360        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13361        final PackageParser.Package pkg;
13362        try {
13363            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13364        } catch (PackageParserException e) {
13365            res.setError("Failed parse during installPackageLI", e);
13366            return;
13367        } finally {
13368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13369        }
13370
13371        // If package doesn't declare API override, mark that we have an install
13372        // time CPU ABI override.
13373        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13374            pkg.cpuAbiOverride = args.abiOverride;
13375        }
13376
13377        String pkgName = res.name = pkg.packageName;
13378        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13379            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13380                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13381                return;
13382            }
13383        }
13384
13385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13386        try {
13387            PackageParser.collectCertificates(pkg, parseFlags);
13388        } catch (PackageParserException e) {
13389            res.setError("Failed collect during installPackageLI", e);
13390            return;
13391        } finally {
13392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13393        }
13394
13395        // Get rid of all references to package scan path via parser.
13396        pp = null;
13397        String oldCodePath = null;
13398        boolean systemApp = false;
13399        synchronized (mPackages) {
13400            // Check if installing already existing package
13401            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13402                String oldName = mSettings.mRenamedPackages.get(pkgName);
13403                if (pkg.mOriginalPackages != null
13404                        && pkg.mOriginalPackages.contains(oldName)
13405                        && mPackages.containsKey(oldName)) {
13406                    // This package is derived from an original package,
13407                    // and this device has been updating from that original
13408                    // name.  We must continue using the original name, so
13409                    // rename the new package here.
13410                    pkg.setPackageName(oldName);
13411                    pkgName = pkg.packageName;
13412                    replace = true;
13413                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13414                            + oldName + " pkgName=" + pkgName);
13415                } else if (mPackages.containsKey(pkgName)) {
13416                    // This package, under its official name, already exists
13417                    // on the device; we should replace it.
13418                    replace = true;
13419                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13420                }
13421
13422                // Child packages are installed through the parent package
13423                if (pkg.parentPackage != null) {
13424                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13425                            "Package " + pkg.packageName + " is child of package "
13426                                    + pkg.parentPackage.parentPackage + ". Child packages "
13427                                    + "can be updated only through the parent package.");
13428                    return;
13429                }
13430
13431                if (replace) {
13432                    // Prevent apps opting out from runtime permissions
13433                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13434                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13435                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13436                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13437                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13438                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13439                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13440                                        + " doesn't support runtime permissions but the old"
13441                                        + " target SDK " + oldTargetSdk + " does.");
13442                        return;
13443                    }
13444
13445                    // Prevent installing of child packages
13446                    if (oldPackage.parentPackage != null) {
13447                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13448                                "Package " + pkg.packageName + " is child of package "
13449                                        + oldPackage.parentPackage + ". Child packages "
13450                                        + "can be updated only through the parent package.");
13451                        return;
13452                    }
13453                }
13454            }
13455
13456            PackageSetting ps = mSettings.mPackages.get(pkgName);
13457            if (ps != null) {
13458                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13459
13460                // Quick sanity check that we're signed correctly if updating;
13461                // we'll check this again later when scanning, but we want to
13462                // bail early here before tripping over redefined permissions.
13463                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13464                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13465                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13466                                + pkg.packageName + " upgrade keys do not match the "
13467                                + "previously installed version");
13468                        return;
13469                    }
13470                } else {
13471                    try {
13472                        verifySignaturesLP(ps, pkg);
13473                    } catch (PackageManagerException e) {
13474                        res.setError(e.error, e.getMessage());
13475                        return;
13476                    }
13477                }
13478
13479                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13480                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13481                    systemApp = (ps.pkg.applicationInfo.flags &
13482                            ApplicationInfo.FLAG_SYSTEM) != 0;
13483                }
13484                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13485            }
13486
13487            // Check whether the newly-scanned package wants to define an already-defined perm
13488            int N = pkg.permissions.size();
13489            for (int i = N-1; i >= 0; i--) {
13490                PackageParser.Permission perm = pkg.permissions.get(i);
13491                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13492                if (bp != null) {
13493                    // If the defining package is signed with our cert, it's okay.  This
13494                    // also includes the "updating the same package" case, of course.
13495                    // "updating same package" could also involve key-rotation.
13496                    final boolean sigsOk;
13497                    if (bp.sourcePackage.equals(pkg.packageName)
13498                            && (bp.packageSetting instanceof PackageSetting)
13499                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13500                                    scanFlags))) {
13501                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13502                    } else {
13503                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13504                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13505                    }
13506                    if (!sigsOk) {
13507                        // If the owning package is the system itself, we log but allow
13508                        // install to proceed; we fail the install on all other permission
13509                        // redefinitions.
13510                        if (!bp.sourcePackage.equals("android")) {
13511                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13512                                    + pkg.packageName + " attempting to redeclare permission "
13513                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13514                            res.origPermission = perm.info.name;
13515                            res.origPackage = bp.sourcePackage;
13516                            return;
13517                        } else {
13518                            Slog.w(TAG, "Package " + pkg.packageName
13519                                    + " attempting to redeclare system permission "
13520                                    + perm.info.name + "; ignoring new declaration");
13521                            pkg.permissions.remove(i);
13522                        }
13523                    }
13524                }
13525            }
13526        }
13527
13528        if (systemApp) {
13529            if (onExternal) {
13530                // Abort update; system app can't be replaced with app on sdcard
13531                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13532                        "Cannot install updates to system apps on sdcard");
13533                return;
13534            } else if (ephemeral) {
13535                // Abort update; system app can't be replaced with an ephemeral app
13536                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13537                        "Cannot update a system app with an ephemeral app");
13538                return;
13539            }
13540        }
13541
13542        if (args.move != null) {
13543            // We did an in-place move, so dex is ready to roll
13544            scanFlags |= SCAN_NO_DEX;
13545            scanFlags |= SCAN_MOVE;
13546
13547            synchronized (mPackages) {
13548                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13549                if (ps == null) {
13550                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13551                            "Missing settings for moved package " + pkgName);
13552                }
13553
13554                // We moved the entire application as-is, so bring over the
13555                // previously derived ABI information.
13556                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13557                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13558            }
13559
13560        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13561            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13562            scanFlags |= SCAN_NO_DEX;
13563
13564            try {
13565                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13566                    args.abiOverride : pkg.cpuAbiOverride);
13567                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13568                        true /* extract libs */);
13569            } catch (PackageManagerException pme) {
13570                Slog.e(TAG, "Error deriving application ABI", pme);
13571                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13572                return;
13573            }
13574
13575            // Extract package to save the VM unzipping the APK in memory during
13576            // launch. Only do this if profile-guided compilation is enabled because
13577            // otherwise BackgroundDexOptService will not dexopt the package later.
13578            if (mUseJitProfiles) {
13579                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13580                // Do not run PackageDexOptimizer through the local performDexOpt
13581                // method because `pkg` is not in `mPackages` yet.
13582                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13583                        false /* useProfiles */, true /* extractOnly */);
13584                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13585                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13586                    String msg = "Extracking package failed for " + pkgName;
13587                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13588                    return;
13589                }
13590            }
13591        }
13592
13593        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13594            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13595            return;
13596        }
13597
13598        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13599
13600        if (replace) {
13601            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13602                    installerPackageName, volumeUuid, res);
13603        } else {
13604            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13605                    args.user, installerPackageName, volumeUuid, res);
13606        }
13607        synchronized (mPackages) {
13608            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13609            if (ps != null) {
13610                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13611            }
13612        }
13613    }
13614
13615    private void startIntentFilterVerifications(int userId, boolean replacing,
13616            PackageParser.Package pkg) {
13617        if (mIntentFilterVerifierComponent == null) {
13618            Slog.w(TAG, "No IntentFilter verification will not be done as "
13619                    + "there is no IntentFilterVerifier available!");
13620            return;
13621        }
13622
13623        final int verifierUid = getPackageUid(
13624                mIntentFilterVerifierComponent.getPackageName(),
13625                MATCH_DEBUG_TRIAGED_MISSING,
13626                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13627
13628        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13629        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13630        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13631        mHandler.sendMessage(msg);
13632    }
13633
13634    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13635            PackageParser.Package pkg) {
13636        int size = pkg.activities.size();
13637        if (size == 0) {
13638            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13639                    "No activity, so no need to verify any IntentFilter!");
13640            return;
13641        }
13642
13643        final boolean hasDomainURLs = hasDomainURLs(pkg);
13644        if (!hasDomainURLs) {
13645            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13646                    "No domain URLs, so no need to verify any IntentFilter!");
13647            return;
13648        }
13649
13650        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13651                + " if any IntentFilter from the " + size
13652                + " Activities needs verification ...");
13653
13654        int count = 0;
13655        final String packageName = pkg.packageName;
13656
13657        synchronized (mPackages) {
13658            // If this is a new install and we see that we've already run verification for this
13659            // package, we have nothing to do: it means the state was restored from backup.
13660            if (!replacing) {
13661                IntentFilterVerificationInfo ivi =
13662                        mSettings.getIntentFilterVerificationLPr(packageName);
13663                if (ivi != null) {
13664                    if (DEBUG_DOMAIN_VERIFICATION) {
13665                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13666                                + ivi.getStatusString());
13667                    }
13668                    return;
13669                }
13670            }
13671
13672            // If any filters need to be verified, then all need to be.
13673            boolean needToVerify = false;
13674            for (PackageParser.Activity a : pkg.activities) {
13675                for (ActivityIntentInfo filter : a.intents) {
13676                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13677                        if (DEBUG_DOMAIN_VERIFICATION) {
13678                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13679                        }
13680                        needToVerify = true;
13681                        break;
13682                    }
13683                }
13684            }
13685
13686            if (needToVerify) {
13687                final int verificationId = mIntentFilterVerificationToken++;
13688                for (PackageParser.Activity a : pkg.activities) {
13689                    for (ActivityIntentInfo filter : a.intents) {
13690                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13691                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13692                                    "Verification needed for IntentFilter:" + filter.toString());
13693                            mIntentFilterVerifier.addOneIntentFilterVerification(
13694                                    verifierUid, userId, verificationId, filter, packageName);
13695                            count++;
13696                        }
13697                    }
13698                }
13699            }
13700        }
13701
13702        if (count > 0) {
13703            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13704                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13705                    +  " for userId:" + userId);
13706            mIntentFilterVerifier.startVerifications(userId);
13707        } else {
13708            if (DEBUG_DOMAIN_VERIFICATION) {
13709                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13710            }
13711        }
13712    }
13713
13714    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13715        final ComponentName cn  = filter.activity.getComponentName();
13716        final String packageName = cn.getPackageName();
13717
13718        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13719                packageName);
13720        if (ivi == null) {
13721            return true;
13722        }
13723        int status = ivi.getStatus();
13724        switch (status) {
13725            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13726            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13727                return true;
13728
13729            default:
13730                // Nothing to do
13731                return false;
13732        }
13733    }
13734
13735    private static boolean isMultiArch(ApplicationInfo info) {
13736        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13737    }
13738
13739    private static boolean isExternal(PackageParser.Package pkg) {
13740        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13741    }
13742
13743    private static boolean isExternal(PackageSetting ps) {
13744        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13745    }
13746
13747    private static boolean isEphemeral(PackageParser.Package pkg) {
13748        return pkg.applicationInfo.isEphemeralApp();
13749    }
13750
13751    private static boolean isEphemeral(PackageSetting ps) {
13752        return ps.pkg != null && isEphemeral(ps.pkg);
13753    }
13754
13755    private static boolean isSystemApp(PackageParser.Package pkg) {
13756        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13757    }
13758
13759    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13760        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13761    }
13762
13763    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13764        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13765    }
13766
13767    private static boolean isSystemApp(PackageSetting ps) {
13768        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13769    }
13770
13771    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13772        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13773    }
13774
13775    private int packageFlagsToInstallFlags(PackageSetting ps) {
13776        int installFlags = 0;
13777        if (isEphemeral(ps)) {
13778            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13779        }
13780        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13781            // This existing package was an external ASEC install when we have
13782            // the external flag without a UUID
13783            installFlags |= PackageManager.INSTALL_EXTERNAL;
13784        }
13785        if (ps.isForwardLocked()) {
13786            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13787        }
13788        return installFlags;
13789    }
13790
13791    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13792        if (isExternal(pkg)) {
13793            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13794                return StorageManager.UUID_PRIMARY_PHYSICAL;
13795            } else {
13796                return pkg.volumeUuid;
13797            }
13798        } else {
13799            return StorageManager.UUID_PRIVATE_INTERNAL;
13800        }
13801    }
13802
13803    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13804        if (isExternal(pkg)) {
13805            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13806                return mSettings.getExternalVersion();
13807            } else {
13808                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13809            }
13810        } else {
13811            return mSettings.getInternalVersion();
13812        }
13813    }
13814
13815    private void deleteTempPackageFiles() {
13816        final FilenameFilter filter = new FilenameFilter() {
13817            public boolean accept(File dir, String name) {
13818                return name.startsWith("vmdl") && name.endsWith(".tmp");
13819            }
13820        };
13821        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13822            file.delete();
13823        }
13824    }
13825
13826    @Override
13827    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13828            int flags) {
13829        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13830                flags);
13831    }
13832
13833    @Override
13834    public void deletePackage(final String packageName,
13835            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13836        mContext.enforceCallingOrSelfPermission(
13837                android.Manifest.permission.DELETE_PACKAGES, null);
13838        Preconditions.checkNotNull(packageName);
13839        Preconditions.checkNotNull(observer);
13840        final int uid = Binder.getCallingUid();
13841        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13842        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13843        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13844            mContext.enforceCallingOrSelfPermission(
13845                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13846                    "deletePackage for user " + userId);
13847        }
13848
13849        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13850            try {
13851                observer.onPackageDeleted(packageName,
13852                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13853            } catch (RemoteException re) {
13854            }
13855            return;
13856        }
13857
13858        for (int currentUserId : users) {
13859            if (getBlockUninstallForUser(packageName, currentUserId)) {
13860                try {
13861                    observer.onPackageDeleted(packageName,
13862                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13863                } catch (RemoteException re) {
13864                }
13865                return;
13866            }
13867        }
13868
13869        if (DEBUG_REMOVE) {
13870            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13871        }
13872        // Queue up an async operation since the package deletion may take a little while.
13873        mHandler.post(new Runnable() {
13874            public void run() {
13875                mHandler.removeCallbacks(this);
13876                final int returnCode = deletePackageX(packageName, userId, flags);
13877                try {
13878                    observer.onPackageDeleted(packageName, returnCode, null);
13879                } catch (RemoteException e) {
13880                    Log.i(TAG, "Observer no longer exists.");
13881                } //end catch
13882            } //end run
13883        });
13884    }
13885
13886    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13887        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13888                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13889        try {
13890            if (dpm != null) {
13891                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13892                        /* callingUserOnly =*/ false);
13893                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13894                        : deviceOwnerComponentName.getPackageName();
13895                // Does the package contains the device owner?
13896                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13897                // this check is probably not needed, since DO should be registered as a device
13898                // admin on some user too. (Original bug for this: b/17657954)
13899                if (packageName.equals(deviceOwnerPackageName)) {
13900                    return true;
13901                }
13902                // Does it contain a device admin for any user?
13903                int[] users;
13904                if (userId == UserHandle.USER_ALL) {
13905                    users = sUserManager.getUserIds();
13906                } else {
13907                    users = new int[]{userId};
13908                }
13909                for (int i = 0; i < users.length; ++i) {
13910                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13911                        return true;
13912                    }
13913                }
13914            }
13915        } catch (RemoteException e) {
13916        }
13917        return false;
13918    }
13919
13920    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13921        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13922    }
13923
13924    /**
13925     *  This method is an internal method that could be get invoked either
13926     *  to delete an installed package or to clean up a failed installation.
13927     *  After deleting an installed package, a broadcast is sent to notify any
13928     *  listeners that the package has been installed. For cleaning up a failed
13929     *  installation, the broadcast is not necessary since the package's
13930     *  installation wouldn't have sent the initial broadcast either
13931     *  The key steps in deleting a package are
13932     *  deleting the package information in internal structures like mPackages,
13933     *  deleting the packages base directories through installd
13934     *  updating mSettings to reflect current status
13935     *  persisting settings for later use
13936     *  sending a broadcast if necessary
13937     */
13938    private int deletePackageX(String packageName, int userId, int flags) {
13939        final PackageRemovedInfo info = new PackageRemovedInfo();
13940        final boolean res;
13941
13942        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13943                ? UserHandle.ALL : new UserHandle(userId);
13944
13945        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13946            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13947            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13948        }
13949
13950        boolean removedForAllUsers = false;
13951        boolean systemUpdate = false;
13952
13953        PackageParser.Package uninstalledPkg;
13954
13955        // for the uninstall-updates case and restricted profiles, remember the per-
13956        // userhandle installed state
13957        int[] allUsers;
13958        boolean[] perUserInstalled;
13959        synchronized (mPackages) {
13960            uninstalledPkg = mPackages.get(packageName);
13961            PackageSetting ps = mSettings.mPackages.get(packageName);
13962            allUsers = sUserManager.getUserIds();
13963            perUserInstalled = new boolean[allUsers.length];
13964            for (int i = 0; i < allUsers.length; i++) {
13965                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13966            }
13967        }
13968
13969        synchronized (mInstallLock) {
13970            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13971            res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled,
13972                    flags | REMOVE_CHATTY, info, true, null);
13973            systemUpdate = info.isRemovedPackageSystemUpdate;
13974            synchronized (mPackages) {
13975                if (res) {
13976                    if (!systemUpdate && mPackages.get(packageName) == null) {
13977                        removedForAllUsers = true;
13978                    }
13979                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13980                }
13981            }
13982            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13983                    + " removedForAllUsers=" + removedForAllUsers);
13984        }
13985
13986        if (res) {
13987            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13988
13989            // If the removed package was a system update, the old system package
13990            // was re-enabled; we need to broadcast this information
13991            if (systemUpdate) {
13992                Bundle extras = new Bundle(1);
13993                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13994                        ? info.removedAppId : info.uid);
13995                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13996
13997                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13998                        extras, 0, null, null, null);
13999                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
14000                        extras, 0, null, null, null);
14001                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14002                        null, 0, packageName, null, null);
14003            }
14004        }
14005        // Force a gc here.
14006        Runtime.getRuntime().gc();
14007        // Delete the resources here after sending the broadcast to let
14008        // other processes clean up before deleting resources.
14009        if (info.args != null) {
14010            synchronized (mInstallLock) {
14011                info.args.doPostDeleteLI(true);
14012            }
14013        }
14014
14015        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14016    }
14017
14018    class PackageRemovedInfo {
14019        String removedPackage;
14020        int uid = -1;
14021        int removedAppId = -1;
14022        int[] removedUsers = null;
14023        boolean isRemovedPackageSystemUpdate = false;
14024        // Clean up resources deleted packages.
14025        InstallArgs args = null;
14026
14027        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
14028            Bundle extras = new Bundle(1);
14029            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14030            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
14031            if (replacing) {
14032                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14033            }
14034            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14035            if (removedPackage != null) {
14036                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14037                        extras, 0, null, null, removedUsers);
14038                if (fullRemove && !replacing) {
14039                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
14040                            extras, 0, null, null, removedUsers);
14041                }
14042            }
14043            if (removedAppId >= 0) {
14044                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14045                        removedUsers);
14046            }
14047        }
14048    }
14049
14050    /*
14051     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14052     * flag is not set, the data directory is removed as well.
14053     * make sure this flag is set for partially installed apps. If not its meaningless to
14054     * delete a partially installed application.
14055     */
14056    private void removePackageDataLI(PackageSetting ps,
14057            int[] allUserHandles, boolean[] perUserInstalled,
14058            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14059        String packageName = ps.name;
14060        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14061        removePackageSettingLI(ps, (flags&REMOVE_CHATTY) != 0);
14062        // Retrieve object to delete permissions for shared user later on
14063        final PackageSetting deletedPs;
14064        // reader
14065        synchronized (mPackages) {
14066            deletedPs = mSettings.mPackages.get(packageName);
14067            if (outInfo != null) {
14068                outInfo.removedPackage = packageName;
14069                outInfo.removedUsers = deletedPs != null
14070                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14071                        : null;
14072            }
14073        }
14074        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14075            removeDataDirsLI(ps.volumeUuid, packageName);
14076            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14077        }
14078        // writer
14079        synchronized (mPackages) {
14080            if (deletedPs != null) {
14081                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14082                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14083                    clearDefaultBrowserIfNeeded(packageName);
14084                    if (outInfo != null) {
14085                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14086                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14087                    }
14088                    updatePermissionsLPw(deletedPs.name, null, 0);
14089                    if (deletedPs.sharedUser != null) {
14090                        // Remove permissions associated with package. Since runtime
14091                        // permissions are per user we have to kill the removed package
14092                        // or packages running under the shared user of the removed
14093                        // package if revoking the permissions requested only by the removed
14094                        // package is successful and this causes a change in gids.
14095                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14096                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14097                                    userId);
14098                            if (userIdToKill == UserHandle.USER_ALL
14099                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14100                                // If gids changed for this user, kill all affected packages.
14101                                mHandler.post(new Runnable() {
14102                                    @Override
14103                                    public void run() {
14104                                        // This has to happen with no lock held.
14105                                        killApplication(deletedPs.name, deletedPs.appId,
14106                                                KILL_APP_REASON_GIDS_CHANGED);
14107                                    }
14108                                });
14109                                break;
14110                            }
14111                        }
14112                    }
14113                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14114                }
14115                // make sure to preserve per-user disabled state if this removal was just
14116                // a downgrade of a system app to the factory package
14117                if (allUserHandles != null && perUserInstalled != null) {
14118                    if (DEBUG_REMOVE) {
14119                        Slog.d(TAG, "Propagating install state across downgrade");
14120                    }
14121                    for (int i = 0; i < allUserHandles.length; i++) {
14122                        if (DEBUG_REMOVE) {
14123                            Slog.d(TAG, "    user " + allUserHandles[i]
14124                                    + " => " + perUserInstalled[i]);
14125                        }
14126                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14127                    }
14128                }
14129            }
14130            // can downgrade to reader
14131            if (writeSettings) {
14132                // Save settings now
14133                mSettings.writeLPr();
14134            }
14135        }
14136        if (outInfo != null) {
14137            // A user ID was deleted here. Go through all users and remove it
14138            // from KeyStore.
14139            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14140        }
14141    }
14142
14143    static boolean locationIsPrivileged(File path) {
14144        try {
14145            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14146                    .getCanonicalPath();
14147            return path.getCanonicalPath().startsWith(privilegedAppDir);
14148        } catch (IOException e) {
14149            Slog.e(TAG, "Unable to access code path " + path);
14150        }
14151        return false;
14152    }
14153
14154    /*
14155     * Tries to delete system package.
14156     */
14157    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14158            PackageSetting deletedPs, int[] allUserHandles, boolean[] perUserInstalled,
14159            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14160            PackageParser.Package replacingPackage) {
14161        if (deletedPkg.parentPackage != null) {
14162            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14163            return false;
14164        }
14165
14166        final boolean applyUserRestrictions
14167                = (allUserHandles != null) && (perUserInstalled != null);
14168        final PackageSetting disabledPs;
14169        // Confirm if the system package has been updated
14170        // An updated system app can be deleted. This will also have to restore
14171        // the system pkg from system partition
14172        // reader
14173        synchronized (mPackages) {
14174            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14175        }
14176
14177        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14178                + " disabledPs=" + disabledPs);
14179
14180        if (disabledPs == null) {
14181            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14182            return false;
14183        } else if (DEBUG_REMOVE) {
14184            Slog.d(TAG, "Deleting system pkg from data partition");
14185        }
14186
14187        if (DEBUG_REMOVE) {
14188            if (applyUserRestrictions) {
14189                Slog.d(TAG, "Remembering install states:");
14190                for (int i = 0; i < allUserHandles.length; i++) {
14191                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
14192                }
14193            }
14194        }
14195
14196        // Delete the updated package
14197        outInfo.isRemovedPackageSystemUpdate = true;
14198        if (disabledPs.versionCode < deletedPs.versionCode) {
14199            // Delete data for downgrades
14200            flags &= ~PackageManager.DELETE_KEEP_DATA;
14201        } else {
14202            // Preserve data by setting flag
14203            flags |= PackageManager.DELETE_KEEP_DATA;
14204        }
14205        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14206                perUserInstalled, outInfo, writeSettings, replacingPackage);
14207        if (!ret) {
14208            return false;
14209        }
14210
14211        // writer
14212        synchronized (mPackages) {
14213            // Reinstate the old system package
14214            enableSystemPackageLPw(disabledPs.pkg);
14215            // Remove any native libraries from the upgraded package.
14216            removeNativeBinariesLI(deletedPkg);
14217        }
14218
14219        // Install the system package
14220        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14221        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14222        if (locationIsPrivileged(disabledPs.codePath)) {
14223            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14224        }
14225
14226        final PackageParser.Package newPkg;
14227        try {
14228            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14229        } catch (PackageManagerException e) {
14230            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14231                    + e.getMessage());
14232            return false;
14233        }
14234
14235        prepareAppDataAfterInstall(newPkg);
14236
14237        // writer
14238        synchronized (mPackages) {
14239            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14240
14241            // Propagate the permissions state as we do not want to drop on the floor
14242            // runtime permissions. The update permissions method below will take
14243            // care of removing obsolete permissions and grant install permissions.
14244            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14245            updatePermissionsLPw(newPkg.packageName, newPkg,
14246                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14247
14248            if (applyUserRestrictions) {
14249                if (DEBUG_REMOVE) {
14250                    Slog.d(TAG, "Propagating install state across reinstall");
14251                }
14252                for (int i = 0; i < allUserHandles.length; i++) {
14253                    if (DEBUG_REMOVE) {
14254                        Slog.d(TAG, "    user " + allUserHandles[i]
14255                                + " => " + perUserInstalled[i]);
14256                    }
14257                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14258
14259                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
14260                }
14261                // Regardless of writeSettings we need to ensure that this restriction
14262                // state propagation is persisted
14263                mSettings.writeAllUsersPackageRestrictionsLPr();
14264            }
14265            // can downgrade to reader here
14266            if (writeSettings) {
14267                mSettings.writeLPr();
14268            }
14269        }
14270        return true;
14271    }
14272
14273    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14274            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14275            boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings,
14276            PackageParser.Package replacingPackage) {
14277        PackageSetting ps = null;
14278
14279        synchronized (mPackages) {
14280            pkg = mPackages.get(pkg.packageName);
14281            if (pkg == null) {
14282                return false;
14283            }
14284
14285            ps = mSettings.mPackages.get(pkg.packageName);
14286            if (ps == null) {
14287                return false;
14288            }
14289
14290            if (outInfo != null) {
14291                outInfo.uid = ps.appId;
14292            }
14293        }
14294
14295        // Delete package data from internal structures and also remove data if flag is set
14296        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags,
14297                    writeSettings);
14298
14299        // Delete the child packages data
14300        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14301        for (int i = 0; i < childCount; i++) {
14302            PackageSetting childPs;
14303            synchronized (mPackages) {
14304                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14305            }
14306            if (childPs != null) {
14307                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14308                        && (replacingPackage != null
14309                        && !replacingPackage.hasChildPackage(childPs.name))
14310                        ? flags & ~DELETE_KEEP_DATA : flags;
14311                removePackageDataLI(childPs, allUserHandles, perUserInstalled, outInfo,
14312                        deleteFlags, writeSettings);
14313            }
14314        }
14315
14316        // Delete application code and resources only for parent packages
14317        if (ps.pkg.parentPackage == null) {
14318                if (deleteCodeAndResources && (outInfo != null)) {
14319                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14320                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14321                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14322            }
14323        }
14324
14325        return true;
14326    }
14327
14328    @Override
14329    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14330            int userId) {
14331        mContext.enforceCallingOrSelfPermission(
14332                android.Manifest.permission.DELETE_PACKAGES, null);
14333        synchronized (mPackages) {
14334            PackageSetting ps = mSettings.mPackages.get(packageName);
14335            if (ps == null) {
14336                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14337                return false;
14338            }
14339            if (!ps.getInstalled(userId)) {
14340                // Can't block uninstall for an app that is not installed or enabled.
14341                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14342                return false;
14343            }
14344            ps.setBlockUninstall(blockUninstall, userId);
14345            mSettings.writePackageRestrictionsLPr(userId);
14346        }
14347        return true;
14348    }
14349
14350    @Override
14351    public boolean getBlockUninstallForUser(String packageName, int userId) {
14352        synchronized (mPackages) {
14353            PackageSetting ps = mSettings.mPackages.get(packageName);
14354            if (ps == null) {
14355                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14356                return false;
14357            }
14358            return ps.getBlockUninstall(userId);
14359        }
14360    }
14361
14362    @Override
14363    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14364        int callingUid = Binder.getCallingUid();
14365        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14366            throw new SecurityException(
14367                    "setRequiredForSystemUser can only be run by the system or root");
14368        }
14369        synchronized (mPackages) {
14370            PackageSetting ps = mSettings.mPackages.get(packageName);
14371            if (ps == null) {
14372                Log.w(TAG, "Package doesn't exist: " + packageName);
14373                return false;
14374            }
14375            if (systemUserApp) {
14376                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14377            } else {
14378                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14379            }
14380            mSettings.writeLPr();
14381        }
14382        return true;
14383    }
14384
14385    /*
14386     * This method handles package deletion in general
14387     */
14388    private boolean deletePackageLI(String packageName, UserHandle user,
14389            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
14390            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14391            PackageParser.Package replacingPackage) {
14392        if (packageName == null) {
14393            Slog.w(TAG, "Attempt to delete null packageName.");
14394            return false;
14395        }
14396
14397        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14398
14399        PackageSetting ps;
14400
14401        synchronized (mPackages) {
14402            ps = mSettings.mPackages.get(packageName);
14403            if (ps == null) {
14404                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14405                return false;
14406            }
14407
14408            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14409                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14410                if (DEBUG_REMOVE) {
14411                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14412                            + ((user == null) ? UserHandle.USER_ALL : user));
14413                }
14414                final int removedUserId = (user != null) ? user.getIdentifier()
14415                        : UserHandle.USER_ALL;
14416                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14417                    return false;
14418                }
14419                markPackageUninstalledForUserLPw(ps, user);
14420                scheduleWritePackageRestrictionsLocked(user);
14421                return true;
14422            }
14423        }
14424
14425        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14426                && user.getIdentifier() != UserHandle.USER_ALL)) {
14427            // The caller is asking that the package only be deleted for a single
14428            // user.  To do this, we just mark its uninstalled state and delete
14429            // its data. If this is a system app, we only allow this to happen if
14430            // they have set the special DELETE_SYSTEM_APP which requests different
14431            // semantics than normal for uninstalling system apps.
14432            markPackageUninstalledForUserLPw(ps, user);
14433
14434            if (!isSystemApp(ps)) {
14435                // Do not uninstall the APK if an app should be cached
14436                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14437                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14438                    // Other user still have this package installed, so all
14439                    // we need to do is clear this user's data and save that
14440                    // it is uninstalled.
14441                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14442                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14443                        return false;
14444                    }
14445                    scheduleWritePackageRestrictionsLocked(user);
14446                    return true;
14447                } else {
14448                    // We need to set it back to 'installed' so the uninstall
14449                    // broadcasts will be sent correctly.
14450                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14451                    ps.setInstalled(true, user.getIdentifier());
14452                }
14453            } else {
14454                // This is a system app, so we assume that the
14455                // other users still have this package installed, so all
14456                // we need to do is clear this user's data and save that
14457                // it is uninstalled.
14458                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14459                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14460                    return false;
14461                }
14462                scheduleWritePackageRestrictionsLocked(user);
14463                return true;
14464            }
14465        }
14466
14467        boolean ret = false;
14468        if (isSystemApp(ps)) {
14469            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14470            // When an updated system application is deleted we delete the existing resources as well and
14471            // fall back to existing code in system partition
14472            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, perUserInstalled,
14473                    flags, outInfo, writeSettings, replacingPackage);
14474        } else {
14475            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14476            // Kill application pre-emptively especially for apps on sd.
14477            killApplication(packageName, ps.appId, "uninstall pkg");
14478            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14479                    perUserInstalled, outInfo, writeSettings, replacingPackage);
14480        }
14481
14482        return ret;
14483    }
14484
14485    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14486        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14487                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14488        for (int nextUserId : userIds) {
14489            if (DEBUG_REMOVE) {
14490                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14491            }
14492            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14493                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14494                    false /*hidden*/, false /*suspended*/, null, null, null,
14495                    false /*blockUninstall*/,
14496                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14497        }
14498    }
14499
14500    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14501            PackageRemovedInfo outInfo) {
14502        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14503                : new int[] {userId};
14504        for (int nextUserId : userIds) {
14505            if (DEBUG_REMOVE) {
14506                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14507                        + nextUserId);
14508            }
14509            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14510            try {
14511                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14512            } catch (InstallerException e) {
14513                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14514                return false;
14515            }
14516            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14517            schedulePackageCleaning(ps.name, nextUserId, false);
14518            synchronized (mPackages) {
14519                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14520                    scheduleWritePackageRestrictionsLocked(nextUserId);
14521                }
14522                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14523            }
14524        }
14525
14526        if (outInfo != null) {
14527            outInfo.removedPackage = ps.name;
14528            outInfo.removedAppId = ps.appId;
14529            outInfo.removedUsers = userIds;
14530        }
14531
14532        return true;
14533    }
14534
14535    private final class ClearStorageConnection implements ServiceConnection {
14536        IMediaContainerService mContainerService;
14537
14538        @Override
14539        public void onServiceConnected(ComponentName name, IBinder service) {
14540            synchronized (this) {
14541                mContainerService = IMediaContainerService.Stub.asInterface(service);
14542                notifyAll();
14543            }
14544        }
14545
14546        @Override
14547        public void onServiceDisconnected(ComponentName name) {
14548        }
14549    }
14550
14551    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14552        final boolean mounted;
14553        if (Environment.isExternalStorageEmulated()) {
14554            mounted = true;
14555        } else {
14556            final String status = Environment.getExternalStorageState();
14557
14558            mounted = status.equals(Environment.MEDIA_MOUNTED)
14559                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14560        }
14561
14562        if (!mounted) {
14563            return;
14564        }
14565
14566        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14567        int[] users;
14568        if (userId == UserHandle.USER_ALL) {
14569            users = sUserManager.getUserIds();
14570        } else {
14571            users = new int[] { userId };
14572        }
14573        final ClearStorageConnection conn = new ClearStorageConnection();
14574        if (mContext.bindServiceAsUser(
14575                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14576            try {
14577                for (int curUser : users) {
14578                    long timeout = SystemClock.uptimeMillis() + 5000;
14579                    synchronized (conn) {
14580                        long now = SystemClock.uptimeMillis();
14581                        while (conn.mContainerService == null && now < timeout) {
14582                            try {
14583                                conn.wait(timeout - now);
14584                            } catch (InterruptedException e) {
14585                            }
14586                        }
14587                    }
14588                    if (conn.mContainerService == null) {
14589                        return;
14590                    }
14591
14592                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14593                    clearDirectory(conn.mContainerService,
14594                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14595                    if (allData) {
14596                        clearDirectory(conn.mContainerService,
14597                                userEnv.buildExternalStorageAppDataDirs(packageName));
14598                        clearDirectory(conn.mContainerService,
14599                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14600                    }
14601                }
14602            } finally {
14603                mContext.unbindService(conn);
14604            }
14605        }
14606    }
14607
14608    @Override
14609    public void clearApplicationUserData(final String packageName,
14610            final IPackageDataObserver observer, final int userId) {
14611        mContext.enforceCallingOrSelfPermission(
14612                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14613        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14614        // Queue up an async operation since the package deletion may take a little while.
14615        mHandler.post(new Runnable() {
14616            public void run() {
14617                mHandler.removeCallbacks(this);
14618                final boolean succeeded;
14619                synchronized (mInstallLock) {
14620                    succeeded = clearApplicationUserDataLI(packageName, userId);
14621                }
14622                clearExternalStorageDataSync(packageName, userId, true);
14623                if (succeeded) {
14624                    // invoke DeviceStorageMonitor's update method to clear any notifications
14625                    DeviceStorageMonitorInternal
14626                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14627                    if (dsm != null) {
14628                        dsm.checkMemory();
14629                    }
14630                }
14631                if(observer != null) {
14632                    try {
14633                        observer.onRemoveCompleted(packageName, succeeded);
14634                    } catch (RemoteException e) {
14635                        Log.i(TAG, "Observer no longer exists.");
14636                    }
14637                } //end if observer
14638            } //end run
14639        });
14640    }
14641
14642    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14643        if (packageName == null) {
14644            Slog.w(TAG, "Attempt to delete null packageName.");
14645            return false;
14646        }
14647
14648        // Try finding details about the requested package
14649        PackageParser.Package pkg;
14650        synchronized (mPackages) {
14651            pkg = mPackages.get(packageName);
14652            if (pkg == null) {
14653                final PackageSetting ps = mSettings.mPackages.get(packageName);
14654                if (ps != null) {
14655                    pkg = ps.pkg;
14656                }
14657            }
14658
14659            if (pkg == null) {
14660                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14661                return false;
14662            }
14663
14664            PackageSetting ps = (PackageSetting) pkg.mExtras;
14665            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14666        }
14667
14668        // Always delete data directories for package, even if we found no other
14669        // record of app. This helps users recover from UID mismatches without
14670        // resorting to a full data wipe.
14671        // TODO: triage flags as part of 26466827
14672        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14673        try {
14674            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14675        } catch (InstallerException e) {
14676            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14677            return false;
14678        }
14679
14680        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14681        removeKeystoreDataIfNeeded(userId, appId);
14682
14683        // Create a native library symlink only if we have native libraries
14684        // and if the native libraries are 32 bit libraries. We do not provide
14685        // this symlink for 64 bit libraries.
14686        if (pkg.applicationInfo.primaryCpuAbi != null &&
14687                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14688            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14689            try {
14690                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14691                        nativeLibPath, userId);
14692            } catch (InstallerException e) {
14693                Slog.w(TAG, "Failed linking native library dir", e);
14694                return false;
14695            }
14696        }
14697
14698        return true;
14699    }
14700
14701    /**
14702     * Reverts user permission state changes (permissions and flags) in
14703     * all packages for a given user.
14704     *
14705     * @param userId The device user for which to do a reset.
14706     */
14707    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14708        final int packageCount = mPackages.size();
14709        for (int i = 0; i < packageCount; i++) {
14710            PackageParser.Package pkg = mPackages.valueAt(i);
14711            PackageSetting ps = (PackageSetting) pkg.mExtras;
14712            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14713        }
14714    }
14715
14716    /**
14717     * Reverts user permission state changes (permissions and flags).
14718     *
14719     * @param ps The package for which to reset.
14720     * @param userId The device user for which to do a reset.
14721     */
14722    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14723            final PackageSetting ps, final int userId) {
14724        if (ps.pkg == null) {
14725            return;
14726        }
14727
14728        // These are flags that can change base on user actions.
14729        final int userSettableMask = FLAG_PERMISSION_USER_SET
14730                | FLAG_PERMISSION_USER_FIXED
14731                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14732                | FLAG_PERMISSION_REVIEW_REQUIRED;
14733
14734        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14735                | FLAG_PERMISSION_POLICY_FIXED;
14736
14737        boolean writeInstallPermissions = false;
14738        boolean writeRuntimePermissions = false;
14739
14740        final int permissionCount = ps.pkg.requestedPermissions.size();
14741        for (int i = 0; i < permissionCount; i++) {
14742            String permission = ps.pkg.requestedPermissions.get(i);
14743
14744            BasePermission bp = mSettings.mPermissions.get(permission);
14745            if (bp == null) {
14746                continue;
14747            }
14748
14749            // If shared user we just reset the state to which only this app contributed.
14750            if (ps.sharedUser != null) {
14751                boolean used = false;
14752                final int packageCount = ps.sharedUser.packages.size();
14753                for (int j = 0; j < packageCount; j++) {
14754                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14755                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14756                            && pkg.pkg.requestedPermissions.contains(permission)) {
14757                        used = true;
14758                        break;
14759                    }
14760                }
14761                if (used) {
14762                    continue;
14763                }
14764            }
14765
14766            PermissionsState permissionsState = ps.getPermissionsState();
14767
14768            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14769
14770            // Always clear the user settable flags.
14771            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14772                    bp.name) != null;
14773            // If permission review is enabled and this is a legacy app, mark the
14774            // permission as requiring a review as this is the initial state.
14775            int flags = 0;
14776            if (Build.PERMISSIONS_REVIEW_REQUIRED
14777                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14778                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14779            }
14780            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14781                if (hasInstallState) {
14782                    writeInstallPermissions = true;
14783                } else {
14784                    writeRuntimePermissions = true;
14785                }
14786            }
14787
14788            // Below is only runtime permission handling.
14789            if (!bp.isRuntime()) {
14790                continue;
14791            }
14792
14793            // Never clobber system or policy.
14794            if ((oldFlags & policyOrSystemFlags) != 0) {
14795                continue;
14796            }
14797
14798            // If this permission was granted by default, make sure it is.
14799            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14800                if (permissionsState.grantRuntimePermission(bp, userId)
14801                        != PERMISSION_OPERATION_FAILURE) {
14802                    writeRuntimePermissions = true;
14803                }
14804            // If permission review is enabled the permissions for a legacy apps
14805            // are represented as constantly granted runtime ones, so don't revoke.
14806            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14807                // Otherwise, reset the permission.
14808                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14809                switch (revokeResult) {
14810                    case PERMISSION_OPERATION_SUCCESS: {
14811                        writeRuntimePermissions = true;
14812                    } break;
14813
14814                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14815                        writeRuntimePermissions = true;
14816                        final int appId = ps.appId;
14817                        mHandler.post(new Runnable() {
14818                            @Override
14819                            public void run() {
14820                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14821                            }
14822                        });
14823                    } break;
14824                }
14825            }
14826        }
14827
14828        // Synchronously write as we are taking permissions away.
14829        if (writeRuntimePermissions) {
14830            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14831        }
14832
14833        // Synchronously write as we are taking permissions away.
14834        if (writeInstallPermissions) {
14835            mSettings.writeLPr();
14836        }
14837    }
14838
14839    /**
14840     * Remove entries from the keystore daemon. Will only remove it if the
14841     * {@code appId} is valid.
14842     */
14843    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14844        if (appId < 0) {
14845            return;
14846        }
14847
14848        final KeyStore keyStore = KeyStore.getInstance();
14849        if (keyStore != null) {
14850            if (userId == UserHandle.USER_ALL) {
14851                for (final int individual : sUserManager.getUserIds()) {
14852                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14853                }
14854            } else {
14855                keyStore.clearUid(UserHandle.getUid(userId, appId));
14856            }
14857        } else {
14858            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14859        }
14860    }
14861
14862    @Override
14863    public void deleteApplicationCacheFiles(final String packageName,
14864            final IPackageDataObserver observer) {
14865        mContext.enforceCallingOrSelfPermission(
14866                android.Manifest.permission.DELETE_CACHE_FILES, null);
14867        // Queue up an async operation since the package deletion may take a little while.
14868        final int userId = UserHandle.getCallingUserId();
14869        mHandler.post(new Runnable() {
14870            public void run() {
14871                mHandler.removeCallbacks(this);
14872                final boolean succeded;
14873                synchronized (mInstallLock) {
14874                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14875                }
14876                clearExternalStorageDataSync(packageName, userId, false);
14877                if (observer != null) {
14878                    try {
14879                        observer.onRemoveCompleted(packageName, succeded);
14880                    } catch (RemoteException e) {
14881                        Log.i(TAG, "Observer no longer exists.");
14882                    }
14883                } //end if observer
14884            } //end run
14885        });
14886    }
14887
14888    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14889        if (packageName == null) {
14890            Slog.w(TAG, "Attempt to delete null packageName.");
14891            return false;
14892        }
14893        PackageParser.Package p;
14894        synchronized (mPackages) {
14895            p = mPackages.get(packageName);
14896        }
14897        if (p == null) {
14898            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14899            return false;
14900        }
14901        final ApplicationInfo applicationInfo = p.applicationInfo;
14902        if (applicationInfo == null) {
14903            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14904            return false;
14905        }
14906        // TODO: triage flags as part of 26466827
14907        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14908        try {
14909            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14910                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14911        } catch (InstallerException e) {
14912            Slog.w(TAG, "Couldn't remove cache files for package "
14913                    + packageName + " u" + userId, e);
14914            return false;
14915        }
14916        return true;
14917    }
14918
14919    @Override
14920    public void getPackageSizeInfo(final String packageName, int userHandle,
14921            final IPackageStatsObserver observer) {
14922        mContext.enforceCallingOrSelfPermission(
14923                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14924        if (packageName == null) {
14925            throw new IllegalArgumentException("Attempt to get size of null packageName");
14926        }
14927
14928        PackageStats stats = new PackageStats(packageName, userHandle);
14929
14930        /*
14931         * Queue up an async operation since the package measurement may take a
14932         * little while.
14933         */
14934        Message msg = mHandler.obtainMessage(INIT_COPY);
14935        msg.obj = new MeasureParams(stats, observer);
14936        mHandler.sendMessage(msg);
14937    }
14938
14939    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14940            PackageStats pStats) {
14941        if (packageName == null) {
14942            Slog.w(TAG, "Attempt to get size of null packageName.");
14943            return false;
14944        }
14945        PackageParser.Package p;
14946        boolean dataOnly = false;
14947        String libDirRoot = null;
14948        String asecPath = null;
14949        PackageSetting ps = null;
14950        synchronized (mPackages) {
14951            p = mPackages.get(packageName);
14952            ps = mSettings.mPackages.get(packageName);
14953            if(p == null) {
14954                dataOnly = true;
14955                if((ps == null) || (ps.pkg == null)) {
14956                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14957                    return false;
14958                }
14959                p = ps.pkg;
14960            }
14961            if (ps != null) {
14962                libDirRoot = ps.legacyNativeLibraryPathString;
14963            }
14964            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14965                final long token = Binder.clearCallingIdentity();
14966                try {
14967                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14968                    if (secureContainerId != null) {
14969                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14970                    }
14971                } finally {
14972                    Binder.restoreCallingIdentity(token);
14973                }
14974            }
14975        }
14976        String publicSrcDir = null;
14977        if(!dataOnly) {
14978            final ApplicationInfo applicationInfo = p.applicationInfo;
14979            if (applicationInfo == null) {
14980                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14981                return false;
14982            }
14983            if (p.isForwardLocked()) {
14984                publicSrcDir = applicationInfo.getBaseResourcePath();
14985            }
14986        }
14987        // TODO: extend to measure size of split APKs
14988        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14989        // not just the first level.
14990        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14991        // just the primary.
14992        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14993
14994        String apkPath;
14995        File packageDir = new File(p.codePath);
14996
14997        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14998            apkPath = packageDir.getAbsolutePath();
14999            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15000            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15001                libDirRoot = null;
15002            }
15003        } else {
15004            apkPath = p.baseCodePath;
15005        }
15006
15007        // TODO: triage flags as part of 26466827
15008        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15009        try {
15010            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15011                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15012        } catch (InstallerException e) {
15013            return false;
15014        }
15015
15016        // Fix-up for forward-locked applications in ASEC containers.
15017        if (!isExternal(p)) {
15018            pStats.codeSize += pStats.externalCodeSize;
15019            pStats.externalCodeSize = 0L;
15020        }
15021
15022        return true;
15023    }
15024
15025
15026    @Override
15027    public void addPackageToPreferred(String packageName) {
15028        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15029    }
15030
15031    @Override
15032    public void removePackageFromPreferred(String packageName) {
15033        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15034    }
15035
15036    @Override
15037    public List<PackageInfo> getPreferredPackages(int flags) {
15038        return new ArrayList<PackageInfo>();
15039    }
15040
15041    private int getUidTargetSdkVersionLockedLPr(int uid) {
15042        Object obj = mSettings.getUserIdLPr(uid);
15043        if (obj instanceof SharedUserSetting) {
15044            final SharedUserSetting sus = (SharedUserSetting) obj;
15045            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15046            final Iterator<PackageSetting> it = sus.packages.iterator();
15047            while (it.hasNext()) {
15048                final PackageSetting ps = it.next();
15049                if (ps.pkg != null) {
15050                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15051                    if (v < vers) vers = v;
15052                }
15053            }
15054            return vers;
15055        } else if (obj instanceof PackageSetting) {
15056            final PackageSetting ps = (PackageSetting) obj;
15057            if (ps.pkg != null) {
15058                return ps.pkg.applicationInfo.targetSdkVersion;
15059            }
15060        }
15061        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15062    }
15063
15064    @Override
15065    public void addPreferredActivity(IntentFilter filter, int match,
15066            ComponentName[] set, ComponentName activity, int userId) {
15067        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15068                "Adding preferred");
15069    }
15070
15071    private void addPreferredActivityInternal(IntentFilter filter, int match,
15072            ComponentName[] set, ComponentName activity, boolean always, int userId,
15073            String opname) {
15074        // writer
15075        int callingUid = Binder.getCallingUid();
15076        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15077        if (filter.countActions() == 0) {
15078            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15079            return;
15080        }
15081        synchronized (mPackages) {
15082            if (mContext.checkCallingOrSelfPermission(
15083                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15084                    != PackageManager.PERMISSION_GRANTED) {
15085                if (getUidTargetSdkVersionLockedLPr(callingUid)
15086                        < Build.VERSION_CODES.FROYO) {
15087                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15088                            + callingUid);
15089                    return;
15090                }
15091                mContext.enforceCallingOrSelfPermission(
15092                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15093            }
15094
15095            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15096            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15097                    + userId + ":");
15098            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15099            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15100            scheduleWritePackageRestrictionsLocked(userId);
15101        }
15102    }
15103
15104    @Override
15105    public void replacePreferredActivity(IntentFilter filter, int match,
15106            ComponentName[] set, ComponentName activity, int userId) {
15107        if (filter.countActions() != 1) {
15108            throw new IllegalArgumentException(
15109                    "replacePreferredActivity expects filter to have only 1 action.");
15110        }
15111        if (filter.countDataAuthorities() != 0
15112                || filter.countDataPaths() != 0
15113                || filter.countDataSchemes() > 1
15114                || filter.countDataTypes() != 0) {
15115            throw new IllegalArgumentException(
15116                    "replacePreferredActivity expects filter to have no data authorities, " +
15117                    "paths, or types; and at most one scheme.");
15118        }
15119
15120        final int callingUid = Binder.getCallingUid();
15121        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15122        synchronized (mPackages) {
15123            if (mContext.checkCallingOrSelfPermission(
15124                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15125                    != PackageManager.PERMISSION_GRANTED) {
15126                if (getUidTargetSdkVersionLockedLPr(callingUid)
15127                        < Build.VERSION_CODES.FROYO) {
15128                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15129                            + Binder.getCallingUid());
15130                    return;
15131                }
15132                mContext.enforceCallingOrSelfPermission(
15133                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15134            }
15135
15136            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15137            if (pir != null) {
15138                // Get all of the existing entries that exactly match this filter.
15139                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15140                if (existing != null && existing.size() == 1) {
15141                    PreferredActivity cur = existing.get(0);
15142                    if (DEBUG_PREFERRED) {
15143                        Slog.i(TAG, "Checking replace of preferred:");
15144                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15145                        if (!cur.mPref.mAlways) {
15146                            Slog.i(TAG, "  -- CUR; not mAlways!");
15147                        } else {
15148                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15149                            Slog.i(TAG, "  -- CUR: mSet="
15150                                    + Arrays.toString(cur.mPref.mSetComponents));
15151                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15152                            Slog.i(TAG, "  -- NEW: mMatch="
15153                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15154                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15155                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15156                        }
15157                    }
15158                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15159                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15160                            && cur.mPref.sameSet(set)) {
15161                        // Setting the preferred activity to what it happens to be already
15162                        if (DEBUG_PREFERRED) {
15163                            Slog.i(TAG, "Replacing with same preferred activity "
15164                                    + cur.mPref.mShortComponent + " for user "
15165                                    + userId + ":");
15166                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15167                        }
15168                        return;
15169                    }
15170                }
15171
15172                if (existing != null) {
15173                    if (DEBUG_PREFERRED) {
15174                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15175                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15176                    }
15177                    for (int i = 0; i < existing.size(); i++) {
15178                        PreferredActivity pa = existing.get(i);
15179                        if (DEBUG_PREFERRED) {
15180                            Slog.i(TAG, "Removing existing preferred activity "
15181                                    + pa.mPref.mComponent + ":");
15182                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15183                        }
15184                        pir.removeFilter(pa);
15185                    }
15186                }
15187            }
15188            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15189                    "Replacing preferred");
15190        }
15191    }
15192
15193    @Override
15194    public void clearPackagePreferredActivities(String packageName) {
15195        final int uid = Binder.getCallingUid();
15196        // writer
15197        synchronized (mPackages) {
15198            PackageParser.Package pkg = mPackages.get(packageName);
15199            if (pkg == null || pkg.applicationInfo.uid != uid) {
15200                if (mContext.checkCallingOrSelfPermission(
15201                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15202                        != PackageManager.PERMISSION_GRANTED) {
15203                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15204                            < Build.VERSION_CODES.FROYO) {
15205                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15206                                + Binder.getCallingUid());
15207                        return;
15208                    }
15209                    mContext.enforceCallingOrSelfPermission(
15210                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15211                }
15212            }
15213
15214            int user = UserHandle.getCallingUserId();
15215            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15216                scheduleWritePackageRestrictionsLocked(user);
15217            }
15218        }
15219    }
15220
15221    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15222    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15223        ArrayList<PreferredActivity> removed = null;
15224        boolean changed = false;
15225        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15226            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15227            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15228            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15229                continue;
15230            }
15231            Iterator<PreferredActivity> it = pir.filterIterator();
15232            while (it.hasNext()) {
15233                PreferredActivity pa = it.next();
15234                // Mark entry for removal only if it matches the package name
15235                // and the entry is of type "always".
15236                if (packageName == null ||
15237                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15238                                && pa.mPref.mAlways)) {
15239                    if (removed == null) {
15240                        removed = new ArrayList<PreferredActivity>();
15241                    }
15242                    removed.add(pa);
15243                }
15244            }
15245            if (removed != null) {
15246                for (int j=0; j<removed.size(); j++) {
15247                    PreferredActivity pa = removed.get(j);
15248                    pir.removeFilter(pa);
15249                }
15250                changed = true;
15251            }
15252        }
15253        return changed;
15254    }
15255
15256    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15257    private void clearIntentFilterVerificationsLPw(int userId) {
15258        final int packageCount = mPackages.size();
15259        for (int i = 0; i < packageCount; i++) {
15260            PackageParser.Package pkg = mPackages.valueAt(i);
15261            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15262        }
15263    }
15264
15265    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15266    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15267        if (userId == UserHandle.USER_ALL) {
15268            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15269                    sUserManager.getUserIds())) {
15270                for (int oneUserId : sUserManager.getUserIds()) {
15271                    scheduleWritePackageRestrictionsLocked(oneUserId);
15272                }
15273            }
15274        } else {
15275            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15276                scheduleWritePackageRestrictionsLocked(userId);
15277            }
15278        }
15279    }
15280
15281    void clearDefaultBrowserIfNeeded(String packageName) {
15282        for (int oneUserId : sUserManager.getUserIds()) {
15283            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15284            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15285            if (packageName.equals(defaultBrowserPackageName)) {
15286                setDefaultBrowserPackageName(null, oneUserId);
15287            }
15288        }
15289    }
15290
15291    @Override
15292    public void resetApplicationPreferences(int userId) {
15293        mContext.enforceCallingOrSelfPermission(
15294                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15295        // writer
15296        synchronized (mPackages) {
15297            final long identity = Binder.clearCallingIdentity();
15298            try {
15299                clearPackagePreferredActivitiesLPw(null, userId);
15300                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15301                // TODO: We have to reset the default SMS and Phone. This requires
15302                // significant refactoring to keep all default apps in the package
15303                // manager (cleaner but more work) or have the services provide
15304                // callbacks to the package manager to request a default app reset.
15305                applyFactoryDefaultBrowserLPw(userId);
15306                clearIntentFilterVerificationsLPw(userId);
15307                primeDomainVerificationsLPw(userId);
15308                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15309                scheduleWritePackageRestrictionsLocked(userId);
15310            } finally {
15311                Binder.restoreCallingIdentity(identity);
15312            }
15313        }
15314    }
15315
15316    @Override
15317    public int getPreferredActivities(List<IntentFilter> outFilters,
15318            List<ComponentName> outActivities, String packageName) {
15319
15320        int num = 0;
15321        final int userId = UserHandle.getCallingUserId();
15322        // reader
15323        synchronized (mPackages) {
15324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15325            if (pir != null) {
15326                final Iterator<PreferredActivity> it = pir.filterIterator();
15327                while (it.hasNext()) {
15328                    final PreferredActivity pa = it.next();
15329                    if (packageName == null
15330                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15331                                    && pa.mPref.mAlways)) {
15332                        if (outFilters != null) {
15333                            outFilters.add(new IntentFilter(pa));
15334                        }
15335                        if (outActivities != null) {
15336                            outActivities.add(pa.mPref.mComponent);
15337                        }
15338                    }
15339                }
15340            }
15341        }
15342
15343        return num;
15344    }
15345
15346    @Override
15347    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15348            int userId) {
15349        int callingUid = Binder.getCallingUid();
15350        if (callingUid != Process.SYSTEM_UID) {
15351            throw new SecurityException(
15352                    "addPersistentPreferredActivity can only be run by the system");
15353        }
15354        if (filter.countActions() == 0) {
15355            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15356            return;
15357        }
15358        synchronized (mPackages) {
15359            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15360                    ":");
15361            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15362            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15363                    new PersistentPreferredActivity(filter, activity));
15364            scheduleWritePackageRestrictionsLocked(userId);
15365        }
15366    }
15367
15368    @Override
15369    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15370        int callingUid = Binder.getCallingUid();
15371        if (callingUid != Process.SYSTEM_UID) {
15372            throw new SecurityException(
15373                    "clearPackagePersistentPreferredActivities can only be run by the system");
15374        }
15375        ArrayList<PersistentPreferredActivity> removed = null;
15376        boolean changed = false;
15377        synchronized (mPackages) {
15378            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15379                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15380                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15381                        .valueAt(i);
15382                if (userId != thisUserId) {
15383                    continue;
15384                }
15385                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15386                while (it.hasNext()) {
15387                    PersistentPreferredActivity ppa = it.next();
15388                    // Mark entry for removal only if it matches the package name.
15389                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15390                        if (removed == null) {
15391                            removed = new ArrayList<PersistentPreferredActivity>();
15392                        }
15393                        removed.add(ppa);
15394                    }
15395                }
15396                if (removed != null) {
15397                    for (int j=0; j<removed.size(); j++) {
15398                        PersistentPreferredActivity ppa = removed.get(j);
15399                        ppir.removeFilter(ppa);
15400                    }
15401                    changed = true;
15402                }
15403            }
15404
15405            if (changed) {
15406                scheduleWritePackageRestrictionsLocked(userId);
15407            }
15408        }
15409    }
15410
15411    /**
15412     * Common machinery for picking apart a restored XML blob and passing
15413     * it to a caller-supplied functor to be applied to the running system.
15414     */
15415    private void restoreFromXml(XmlPullParser parser, int userId,
15416            String expectedStartTag, BlobXmlRestorer functor)
15417            throws IOException, XmlPullParserException {
15418        int type;
15419        while ((type = parser.next()) != XmlPullParser.START_TAG
15420                && type != XmlPullParser.END_DOCUMENT) {
15421        }
15422        if (type != XmlPullParser.START_TAG) {
15423            // oops didn't find a start tag?!
15424            if (DEBUG_BACKUP) {
15425                Slog.e(TAG, "Didn't find start tag during restore");
15426            }
15427            return;
15428        }
15429Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15430        // this is supposed to be TAG_PREFERRED_BACKUP
15431        if (!expectedStartTag.equals(parser.getName())) {
15432            if (DEBUG_BACKUP) {
15433                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15434            }
15435            return;
15436        }
15437
15438        // skip interfering stuff, then we're aligned with the backing implementation
15439        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15440Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15441        functor.apply(parser, userId);
15442    }
15443
15444    private interface BlobXmlRestorer {
15445        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15446    }
15447
15448    /**
15449     * Non-Binder method, support for the backup/restore mechanism: write the
15450     * full set of preferred activities in its canonical XML format.  Returns the
15451     * XML output as a byte array, or null if there is none.
15452     */
15453    @Override
15454    public byte[] getPreferredActivityBackup(int userId) {
15455        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15456            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15457        }
15458
15459        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15460        try {
15461            final XmlSerializer serializer = new FastXmlSerializer();
15462            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15463            serializer.startDocument(null, true);
15464            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15465
15466            synchronized (mPackages) {
15467                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15468            }
15469
15470            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15471            serializer.endDocument();
15472            serializer.flush();
15473        } catch (Exception e) {
15474            if (DEBUG_BACKUP) {
15475                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15476            }
15477            return null;
15478        }
15479
15480        return dataStream.toByteArray();
15481    }
15482
15483    @Override
15484    public void restorePreferredActivities(byte[] backup, int userId) {
15485        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15486            throw new SecurityException("Only the system may call restorePreferredActivities()");
15487        }
15488
15489        try {
15490            final XmlPullParser parser = Xml.newPullParser();
15491            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15492            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15493                    new BlobXmlRestorer() {
15494                        @Override
15495                        public void apply(XmlPullParser parser, int userId)
15496                                throws XmlPullParserException, IOException {
15497                            synchronized (mPackages) {
15498                                mSettings.readPreferredActivitiesLPw(parser, userId);
15499                            }
15500                        }
15501                    } );
15502        } catch (Exception e) {
15503            if (DEBUG_BACKUP) {
15504                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15505            }
15506        }
15507    }
15508
15509    /**
15510     * Non-Binder method, support for the backup/restore mechanism: write the
15511     * default browser (etc) settings in its canonical XML format.  Returns the default
15512     * browser XML representation as a byte array, or null if there is none.
15513     */
15514    @Override
15515    public byte[] getDefaultAppsBackup(int userId) {
15516        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15517            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15518        }
15519
15520        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15521        try {
15522            final XmlSerializer serializer = new FastXmlSerializer();
15523            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15524            serializer.startDocument(null, true);
15525            serializer.startTag(null, TAG_DEFAULT_APPS);
15526
15527            synchronized (mPackages) {
15528                mSettings.writeDefaultAppsLPr(serializer, userId);
15529            }
15530
15531            serializer.endTag(null, TAG_DEFAULT_APPS);
15532            serializer.endDocument();
15533            serializer.flush();
15534        } catch (Exception e) {
15535            if (DEBUG_BACKUP) {
15536                Slog.e(TAG, "Unable to write default apps for backup", e);
15537            }
15538            return null;
15539        }
15540
15541        return dataStream.toByteArray();
15542    }
15543
15544    @Override
15545    public void restoreDefaultApps(byte[] backup, int userId) {
15546        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15547            throw new SecurityException("Only the system may call restoreDefaultApps()");
15548        }
15549
15550        try {
15551            final XmlPullParser parser = Xml.newPullParser();
15552            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15553            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15554                    new BlobXmlRestorer() {
15555                        @Override
15556                        public void apply(XmlPullParser parser, int userId)
15557                                throws XmlPullParserException, IOException {
15558                            synchronized (mPackages) {
15559                                mSettings.readDefaultAppsLPw(parser, userId);
15560                            }
15561                        }
15562                    } );
15563        } catch (Exception e) {
15564            if (DEBUG_BACKUP) {
15565                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15566            }
15567        }
15568    }
15569
15570    @Override
15571    public byte[] getIntentFilterVerificationBackup(int userId) {
15572        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15573            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15574        }
15575
15576        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15577        try {
15578            final XmlSerializer serializer = new FastXmlSerializer();
15579            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15580            serializer.startDocument(null, true);
15581            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15582
15583            synchronized (mPackages) {
15584                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15585            }
15586
15587            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15588            serializer.endDocument();
15589            serializer.flush();
15590        } catch (Exception e) {
15591            if (DEBUG_BACKUP) {
15592                Slog.e(TAG, "Unable to write default apps for backup", e);
15593            }
15594            return null;
15595        }
15596
15597        return dataStream.toByteArray();
15598    }
15599
15600    @Override
15601    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15602        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15603            throw new SecurityException("Only the system may call restorePreferredActivities()");
15604        }
15605
15606        try {
15607            final XmlPullParser parser = Xml.newPullParser();
15608            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15609            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15610                    new BlobXmlRestorer() {
15611                        @Override
15612                        public void apply(XmlPullParser parser, int userId)
15613                                throws XmlPullParserException, IOException {
15614                            synchronized (mPackages) {
15615                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15616                                mSettings.writeLPr();
15617                            }
15618                        }
15619                    } );
15620        } catch (Exception e) {
15621            if (DEBUG_BACKUP) {
15622                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15623            }
15624        }
15625    }
15626
15627    @Override
15628    public byte[] getPermissionGrantBackup(int userId) {
15629        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15630            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15631        }
15632
15633        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15634        try {
15635            final XmlSerializer serializer = new FastXmlSerializer();
15636            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15637            serializer.startDocument(null, true);
15638            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15639
15640            synchronized (mPackages) {
15641                serializeRuntimePermissionGrantsLPr(serializer, userId);
15642            }
15643
15644            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15645            serializer.endDocument();
15646            serializer.flush();
15647        } catch (Exception e) {
15648            if (DEBUG_BACKUP) {
15649                Slog.e(TAG, "Unable to write default apps for backup", e);
15650            }
15651            return null;
15652        }
15653
15654        return dataStream.toByteArray();
15655    }
15656
15657    @Override
15658    public void restorePermissionGrants(byte[] backup, int userId) {
15659        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15660            throw new SecurityException("Only the system may call restorePermissionGrants()");
15661        }
15662
15663        try {
15664            final XmlPullParser parser = Xml.newPullParser();
15665            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15666            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15667                    new BlobXmlRestorer() {
15668                        @Override
15669                        public void apply(XmlPullParser parser, int userId)
15670                                throws XmlPullParserException, IOException {
15671                            synchronized (mPackages) {
15672                                processRestoredPermissionGrantsLPr(parser, userId);
15673                            }
15674                        }
15675                    } );
15676        } catch (Exception e) {
15677            if (DEBUG_BACKUP) {
15678                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15679            }
15680        }
15681    }
15682
15683    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15684            throws IOException {
15685        serializer.startTag(null, TAG_ALL_GRANTS);
15686
15687        final int N = mSettings.mPackages.size();
15688        for (int i = 0; i < N; i++) {
15689            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15690            boolean pkgGrantsKnown = false;
15691
15692            PermissionsState packagePerms = ps.getPermissionsState();
15693
15694            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15695                final int grantFlags = state.getFlags();
15696                // only look at grants that are not system/policy fixed
15697                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15698                    final boolean isGranted = state.isGranted();
15699                    // And only back up the user-twiddled state bits
15700                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15701                        final String packageName = mSettings.mPackages.keyAt(i);
15702                        if (!pkgGrantsKnown) {
15703                            serializer.startTag(null, TAG_GRANT);
15704                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15705                            pkgGrantsKnown = true;
15706                        }
15707
15708                        final boolean userSet =
15709                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15710                        final boolean userFixed =
15711                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15712                        final boolean revoke =
15713                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15714
15715                        serializer.startTag(null, TAG_PERMISSION);
15716                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15717                        if (isGranted) {
15718                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15719                        }
15720                        if (userSet) {
15721                            serializer.attribute(null, ATTR_USER_SET, "true");
15722                        }
15723                        if (userFixed) {
15724                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15725                        }
15726                        if (revoke) {
15727                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15728                        }
15729                        serializer.endTag(null, TAG_PERMISSION);
15730                    }
15731                }
15732            }
15733
15734            if (pkgGrantsKnown) {
15735                serializer.endTag(null, TAG_GRANT);
15736            }
15737        }
15738
15739        serializer.endTag(null, TAG_ALL_GRANTS);
15740    }
15741
15742    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15743            throws XmlPullParserException, IOException {
15744        String pkgName = null;
15745        int outerDepth = parser.getDepth();
15746        int type;
15747        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15748                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15749            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15750                continue;
15751            }
15752
15753            final String tagName = parser.getName();
15754            if (tagName.equals(TAG_GRANT)) {
15755                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15756                if (DEBUG_BACKUP) {
15757                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15758                }
15759            } else if (tagName.equals(TAG_PERMISSION)) {
15760
15761                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15762                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15763
15764                int newFlagSet = 0;
15765                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15766                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15767                }
15768                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15769                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15770                }
15771                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15772                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15773                }
15774                if (DEBUG_BACKUP) {
15775                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15776                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15777                }
15778                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15779                if (ps != null) {
15780                    // Already installed so we apply the grant immediately
15781                    if (DEBUG_BACKUP) {
15782                        Slog.v(TAG, "        + already installed; applying");
15783                    }
15784                    PermissionsState perms = ps.getPermissionsState();
15785                    BasePermission bp = mSettings.mPermissions.get(permName);
15786                    if (bp != null) {
15787                        if (isGranted) {
15788                            perms.grantRuntimePermission(bp, userId);
15789                        }
15790                        if (newFlagSet != 0) {
15791                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15792                        }
15793                    }
15794                } else {
15795                    // Need to wait for post-restore install to apply the grant
15796                    if (DEBUG_BACKUP) {
15797                        Slog.v(TAG, "        - not yet installed; saving for later");
15798                    }
15799                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15800                            isGranted, newFlagSet, userId);
15801                }
15802            } else {
15803                PackageManagerService.reportSettingsProblem(Log.WARN,
15804                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15805                XmlUtils.skipCurrentTag(parser);
15806            }
15807        }
15808
15809        scheduleWriteSettingsLocked();
15810        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15811    }
15812
15813    @Override
15814    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15815            int sourceUserId, int targetUserId, int flags) {
15816        mContext.enforceCallingOrSelfPermission(
15817                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15818        int callingUid = Binder.getCallingUid();
15819        enforceOwnerRights(ownerPackage, callingUid);
15820        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15821        if (intentFilter.countActions() == 0) {
15822            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15823            return;
15824        }
15825        synchronized (mPackages) {
15826            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15827                    ownerPackage, targetUserId, flags);
15828            CrossProfileIntentResolver resolver =
15829                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15830            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15831            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15832            if (existing != null) {
15833                int size = existing.size();
15834                for (int i = 0; i < size; i++) {
15835                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15836                        return;
15837                    }
15838                }
15839            }
15840            resolver.addFilter(newFilter);
15841            scheduleWritePackageRestrictionsLocked(sourceUserId);
15842        }
15843    }
15844
15845    @Override
15846    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15847        mContext.enforceCallingOrSelfPermission(
15848                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15849        int callingUid = Binder.getCallingUid();
15850        enforceOwnerRights(ownerPackage, callingUid);
15851        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15852        synchronized (mPackages) {
15853            CrossProfileIntentResolver resolver =
15854                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15855            ArraySet<CrossProfileIntentFilter> set =
15856                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15857            for (CrossProfileIntentFilter filter : set) {
15858                if (filter.getOwnerPackage().equals(ownerPackage)) {
15859                    resolver.removeFilter(filter);
15860                }
15861            }
15862            scheduleWritePackageRestrictionsLocked(sourceUserId);
15863        }
15864    }
15865
15866    // Enforcing that callingUid is owning pkg on userId
15867    private void enforceOwnerRights(String pkg, int callingUid) {
15868        // The system owns everything.
15869        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15870            return;
15871        }
15872        int callingUserId = UserHandle.getUserId(callingUid);
15873        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15874        if (pi == null) {
15875            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15876                    + callingUserId);
15877        }
15878        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15879            throw new SecurityException("Calling uid " + callingUid
15880                    + " does not own package " + pkg);
15881        }
15882    }
15883
15884    @Override
15885    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15886        Intent intent = new Intent(Intent.ACTION_MAIN);
15887        intent.addCategory(Intent.CATEGORY_HOME);
15888
15889        final int callingUserId = UserHandle.getCallingUserId();
15890        List<ResolveInfo> list = queryIntentActivities(intent, null,
15891                PackageManager.GET_META_DATA, callingUserId);
15892        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15893                true, false, false, callingUserId);
15894
15895        allHomeCandidates.clear();
15896        if (list != null) {
15897            for (ResolveInfo ri : list) {
15898                allHomeCandidates.add(ri);
15899            }
15900        }
15901        return (preferred == null || preferred.activityInfo == null)
15902                ? null
15903                : new ComponentName(preferred.activityInfo.packageName,
15904                        preferred.activityInfo.name);
15905    }
15906
15907    @Override
15908    public void setApplicationEnabledSetting(String appPackageName,
15909            int newState, int flags, int userId, String callingPackage) {
15910        if (!sUserManager.exists(userId)) return;
15911        if (callingPackage == null) {
15912            callingPackage = Integer.toString(Binder.getCallingUid());
15913        }
15914        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15915    }
15916
15917    @Override
15918    public void setComponentEnabledSetting(ComponentName componentName,
15919            int newState, int flags, int userId) {
15920        if (!sUserManager.exists(userId)) return;
15921        setEnabledSetting(componentName.getPackageName(),
15922                componentName.getClassName(), newState, flags, userId, null);
15923    }
15924
15925    private void setEnabledSetting(final String packageName, String className, int newState,
15926            final int flags, int userId, String callingPackage) {
15927        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15928              || newState == COMPONENT_ENABLED_STATE_ENABLED
15929              || newState == COMPONENT_ENABLED_STATE_DISABLED
15930              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15931              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15932            throw new IllegalArgumentException("Invalid new component state: "
15933                    + newState);
15934        }
15935        PackageSetting pkgSetting;
15936        final int uid = Binder.getCallingUid();
15937        final int permission = mContext.checkCallingOrSelfPermission(
15938                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15939        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15940        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15941        boolean sendNow = false;
15942        boolean isApp = (className == null);
15943        String componentName = isApp ? packageName : className;
15944        int packageUid = -1;
15945        ArrayList<String> components;
15946
15947        // writer
15948        synchronized (mPackages) {
15949            pkgSetting = mSettings.mPackages.get(packageName);
15950            if (pkgSetting == null) {
15951                if (className == null) {
15952                    throw new IllegalArgumentException("Unknown package: " + packageName);
15953                }
15954                throw new IllegalArgumentException(
15955                        "Unknown component: " + packageName + "/" + className);
15956            }
15957            // Allow root and verify that userId is not being specified by a different user
15958            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15959                throw new SecurityException(
15960                        "Permission Denial: attempt to change component state from pid="
15961                        + Binder.getCallingPid()
15962                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15963            }
15964            if (className == null) {
15965                // We're dealing with an application/package level state change
15966                if (pkgSetting.getEnabled(userId) == newState) {
15967                    // Nothing to do
15968                    return;
15969                }
15970                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15971                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15972                    // Don't care about who enables an app.
15973                    callingPackage = null;
15974                }
15975                pkgSetting.setEnabled(newState, userId, callingPackage);
15976                // pkgSetting.pkg.mSetEnabled = newState;
15977            } else {
15978                // We're dealing with a component level state change
15979                // First, verify that this is a valid class name.
15980                PackageParser.Package pkg = pkgSetting.pkg;
15981                if (pkg == null || !pkg.hasComponentClassName(className)) {
15982                    if (pkg != null &&
15983                            pkg.applicationInfo.targetSdkVersion >=
15984                                    Build.VERSION_CODES.JELLY_BEAN) {
15985                        throw new IllegalArgumentException("Component class " + className
15986                                + " does not exist in " + packageName);
15987                    } else {
15988                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15989                                + className + " does not exist in " + packageName);
15990                    }
15991                }
15992                switch (newState) {
15993                case COMPONENT_ENABLED_STATE_ENABLED:
15994                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15995                        return;
15996                    }
15997                    break;
15998                case COMPONENT_ENABLED_STATE_DISABLED:
15999                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16000                        return;
16001                    }
16002                    break;
16003                case COMPONENT_ENABLED_STATE_DEFAULT:
16004                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16005                        return;
16006                    }
16007                    break;
16008                default:
16009                    Slog.e(TAG, "Invalid new component state: " + newState);
16010                    return;
16011                }
16012            }
16013            scheduleWritePackageRestrictionsLocked(userId);
16014            components = mPendingBroadcasts.get(userId, packageName);
16015            final boolean newPackage = components == null;
16016            if (newPackage) {
16017                components = new ArrayList<String>();
16018            }
16019            if (!components.contains(componentName)) {
16020                components.add(componentName);
16021            }
16022            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16023                sendNow = true;
16024                // Purge entry from pending broadcast list if another one exists already
16025                // since we are sending one right away.
16026                mPendingBroadcasts.remove(userId, packageName);
16027            } else {
16028                if (newPackage) {
16029                    mPendingBroadcasts.put(userId, packageName, components);
16030                }
16031                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16032                    // Schedule a message
16033                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16034                }
16035            }
16036        }
16037
16038        long callingId = Binder.clearCallingIdentity();
16039        try {
16040            if (sendNow) {
16041                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16042                sendPackageChangedBroadcast(packageName,
16043                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16044            }
16045        } finally {
16046            Binder.restoreCallingIdentity(callingId);
16047        }
16048    }
16049
16050    private void sendPackageChangedBroadcast(String packageName,
16051            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16052        if (DEBUG_INSTALL)
16053            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16054                    + componentNames);
16055        Bundle extras = new Bundle(4);
16056        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16057        String nameList[] = new String[componentNames.size()];
16058        componentNames.toArray(nameList);
16059        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16060        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16061        extras.putInt(Intent.EXTRA_UID, packageUid);
16062        // If this is not reporting a change of the overall package, then only send it
16063        // to registered receivers.  We don't want to launch a swath of apps for every
16064        // little component state change.
16065        final int flags = !componentNames.contains(packageName)
16066                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16067        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16068                new int[] {UserHandle.getUserId(packageUid)});
16069    }
16070
16071    @Override
16072    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16073        if (!sUserManager.exists(userId)) return;
16074        final int uid = Binder.getCallingUid();
16075        final int permission = mContext.checkCallingOrSelfPermission(
16076                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16077        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16078        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16079        // writer
16080        synchronized (mPackages) {
16081            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16082                    allowedByPermission, uid, userId)) {
16083                scheduleWritePackageRestrictionsLocked(userId);
16084            }
16085        }
16086    }
16087
16088    @Override
16089    public String getInstallerPackageName(String packageName) {
16090        // reader
16091        synchronized (mPackages) {
16092            return mSettings.getInstallerPackageNameLPr(packageName);
16093        }
16094    }
16095
16096    @Override
16097    public int getApplicationEnabledSetting(String packageName, int userId) {
16098        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16099        int uid = Binder.getCallingUid();
16100        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16101        // reader
16102        synchronized (mPackages) {
16103            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16104        }
16105    }
16106
16107    @Override
16108    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16109        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16110        int uid = Binder.getCallingUid();
16111        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16112        // reader
16113        synchronized (mPackages) {
16114            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16115        }
16116    }
16117
16118    @Override
16119    public void enterSafeMode() {
16120        enforceSystemOrRoot("Only the system can request entering safe mode");
16121
16122        if (!mSystemReady) {
16123            mSafeMode = true;
16124        }
16125    }
16126
16127    @Override
16128    public void systemReady() {
16129        mSystemReady = true;
16130
16131        // Read the compatibilty setting when the system is ready.
16132        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16133                mContext.getContentResolver(),
16134                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16135        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16136        if (DEBUG_SETTINGS) {
16137            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16138        }
16139
16140        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16141
16142        synchronized (mPackages) {
16143            // Verify that all of the preferred activity components actually
16144            // exist.  It is possible for applications to be updated and at
16145            // that point remove a previously declared activity component that
16146            // had been set as a preferred activity.  We try to clean this up
16147            // the next time we encounter that preferred activity, but it is
16148            // possible for the user flow to never be able to return to that
16149            // situation so here we do a sanity check to make sure we haven't
16150            // left any junk around.
16151            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16152            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16153                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16154                removed.clear();
16155                for (PreferredActivity pa : pir.filterSet()) {
16156                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16157                        removed.add(pa);
16158                    }
16159                }
16160                if (removed.size() > 0) {
16161                    for (int r=0; r<removed.size(); r++) {
16162                        PreferredActivity pa = removed.get(r);
16163                        Slog.w(TAG, "Removing dangling preferred activity: "
16164                                + pa.mPref.mComponent);
16165                        pir.removeFilter(pa);
16166                    }
16167                    mSettings.writePackageRestrictionsLPr(
16168                            mSettings.mPreferredActivities.keyAt(i));
16169                }
16170            }
16171
16172            for (int userId : UserManagerService.getInstance().getUserIds()) {
16173                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16174                    grantPermissionsUserIds = ArrayUtils.appendInt(
16175                            grantPermissionsUserIds, userId);
16176                }
16177            }
16178        }
16179        sUserManager.systemReady();
16180
16181        // If we upgraded grant all default permissions before kicking off.
16182        for (int userId : grantPermissionsUserIds) {
16183            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16184        }
16185
16186        // Kick off any messages waiting for system ready
16187        if (mPostSystemReadyMessages != null) {
16188            for (Message msg : mPostSystemReadyMessages) {
16189                msg.sendToTarget();
16190            }
16191            mPostSystemReadyMessages = null;
16192        }
16193
16194        // Watch for external volumes that come and go over time
16195        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16196        storage.registerListener(mStorageListener);
16197
16198        mInstallerService.systemReady();
16199        mPackageDexOptimizer.systemReady();
16200
16201        MountServiceInternal mountServiceInternal = LocalServices.getService(
16202                MountServiceInternal.class);
16203        mountServiceInternal.addExternalStoragePolicy(
16204                new MountServiceInternal.ExternalStorageMountPolicy() {
16205            @Override
16206            public int getMountMode(int uid, String packageName) {
16207                if (Process.isIsolated(uid)) {
16208                    return Zygote.MOUNT_EXTERNAL_NONE;
16209                }
16210                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16211                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16212                }
16213                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16214                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16215                }
16216                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16217                    return Zygote.MOUNT_EXTERNAL_READ;
16218                }
16219                return Zygote.MOUNT_EXTERNAL_WRITE;
16220            }
16221
16222            @Override
16223            public boolean hasExternalStorage(int uid, String packageName) {
16224                return true;
16225            }
16226        });
16227    }
16228
16229    @Override
16230    public boolean isSafeMode() {
16231        return mSafeMode;
16232    }
16233
16234    @Override
16235    public boolean hasSystemUidErrors() {
16236        return mHasSystemUidErrors;
16237    }
16238
16239    static String arrayToString(int[] array) {
16240        StringBuffer buf = new StringBuffer(128);
16241        buf.append('[');
16242        if (array != null) {
16243            for (int i=0; i<array.length; i++) {
16244                if (i > 0) buf.append(", ");
16245                buf.append(array[i]);
16246            }
16247        }
16248        buf.append(']');
16249        return buf.toString();
16250    }
16251
16252    static class DumpState {
16253        public static final int DUMP_LIBS = 1 << 0;
16254        public static final int DUMP_FEATURES = 1 << 1;
16255        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16256        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16257        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16258        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16259        public static final int DUMP_PERMISSIONS = 1 << 6;
16260        public static final int DUMP_PACKAGES = 1 << 7;
16261        public static final int DUMP_SHARED_USERS = 1 << 8;
16262        public static final int DUMP_MESSAGES = 1 << 9;
16263        public static final int DUMP_PROVIDERS = 1 << 10;
16264        public static final int DUMP_VERIFIERS = 1 << 11;
16265        public static final int DUMP_PREFERRED = 1 << 12;
16266        public static final int DUMP_PREFERRED_XML = 1 << 13;
16267        public static final int DUMP_KEYSETS = 1 << 14;
16268        public static final int DUMP_VERSION = 1 << 15;
16269        public static final int DUMP_INSTALLS = 1 << 16;
16270        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16271        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16272
16273        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16274
16275        private int mTypes;
16276
16277        private int mOptions;
16278
16279        private boolean mTitlePrinted;
16280
16281        private SharedUserSetting mSharedUser;
16282
16283        public boolean isDumping(int type) {
16284            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16285                return true;
16286            }
16287
16288            return (mTypes & type) != 0;
16289        }
16290
16291        public void setDump(int type) {
16292            mTypes |= type;
16293        }
16294
16295        public boolean isOptionEnabled(int option) {
16296            return (mOptions & option) != 0;
16297        }
16298
16299        public void setOptionEnabled(int option) {
16300            mOptions |= option;
16301        }
16302
16303        public boolean onTitlePrinted() {
16304            final boolean printed = mTitlePrinted;
16305            mTitlePrinted = true;
16306            return printed;
16307        }
16308
16309        public boolean getTitlePrinted() {
16310            return mTitlePrinted;
16311        }
16312
16313        public void setTitlePrinted(boolean enabled) {
16314            mTitlePrinted = enabled;
16315        }
16316
16317        public SharedUserSetting getSharedUser() {
16318            return mSharedUser;
16319        }
16320
16321        public void setSharedUser(SharedUserSetting user) {
16322            mSharedUser = user;
16323        }
16324    }
16325
16326    @Override
16327    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16328            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16329        (new PackageManagerShellCommand(this)).exec(
16330                this, in, out, err, args, resultReceiver);
16331    }
16332
16333    @Override
16334    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16335        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16336                != PackageManager.PERMISSION_GRANTED) {
16337            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16338                    + Binder.getCallingPid()
16339                    + ", uid=" + Binder.getCallingUid()
16340                    + " without permission "
16341                    + android.Manifest.permission.DUMP);
16342            return;
16343        }
16344
16345        DumpState dumpState = new DumpState();
16346        boolean fullPreferred = false;
16347        boolean checkin = false;
16348
16349        String packageName = null;
16350        ArraySet<String> permissionNames = null;
16351
16352        int opti = 0;
16353        while (opti < args.length) {
16354            String opt = args[opti];
16355            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16356                break;
16357            }
16358            opti++;
16359
16360            if ("-a".equals(opt)) {
16361                // Right now we only know how to print all.
16362            } else if ("-h".equals(opt)) {
16363                pw.println("Package manager dump options:");
16364                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16365                pw.println("    --checkin: dump for a checkin");
16366                pw.println("    -f: print details of intent filters");
16367                pw.println("    -h: print this help");
16368                pw.println("  cmd may be one of:");
16369                pw.println("    l[ibraries]: list known shared libraries");
16370                pw.println("    f[eatures]: list device features");
16371                pw.println("    k[eysets]: print known keysets");
16372                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16373                pw.println("    perm[issions]: dump permissions");
16374                pw.println("    permission [name ...]: dump declaration and use of given permission");
16375                pw.println("    pref[erred]: print preferred package settings");
16376                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16377                pw.println("    prov[iders]: dump content providers");
16378                pw.println("    p[ackages]: dump installed packages");
16379                pw.println("    s[hared-users]: dump shared user IDs");
16380                pw.println("    m[essages]: print collected runtime messages");
16381                pw.println("    v[erifiers]: print package verifier info");
16382                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16383                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16384                pw.println("    version: print database version info");
16385                pw.println("    write: write current settings now");
16386                pw.println("    installs: details about install sessions");
16387                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16388                pw.println("    <package.name>: info about given package");
16389                return;
16390            } else if ("--checkin".equals(opt)) {
16391                checkin = true;
16392            } else if ("-f".equals(opt)) {
16393                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16394            } else {
16395                pw.println("Unknown argument: " + opt + "; use -h for help");
16396            }
16397        }
16398
16399        // Is the caller requesting to dump a particular piece of data?
16400        if (opti < args.length) {
16401            String cmd = args[opti];
16402            opti++;
16403            // Is this a package name?
16404            if ("android".equals(cmd) || cmd.contains(".")) {
16405                packageName = cmd;
16406                // When dumping a single package, we always dump all of its
16407                // filter information since the amount of data will be reasonable.
16408                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16409            } else if ("check-permission".equals(cmd)) {
16410                if (opti >= args.length) {
16411                    pw.println("Error: check-permission missing permission argument");
16412                    return;
16413                }
16414                String perm = args[opti];
16415                opti++;
16416                if (opti >= args.length) {
16417                    pw.println("Error: check-permission missing package argument");
16418                    return;
16419                }
16420                String pkg = args[opti];
16421                opti++;
16422                int user = UserHandle.getUserId(Binder.getCallingUid());
16423                if (opti < args.length) {
16424                    try {
16425                        user = Integer.parseInt(args[opti]);
16426                    } catch (NumberFormatException e) {
16427                        pw.println("Error: check-permission user argument is not a number: "
16428                                + args[opti]);
16429                        return;
16430                    }
16431                }
16432                pw.println(checkPermission(perm, pkg, user));
16433                return;
16434            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16435                dumpState.setDump(DumpState.DUMP_LIBS);
16436            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16437                dumpState.setDump(DumpState.DUMP_FEATURES);
16438            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16439                if (opti >= args.length) {
16440                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16441                            | DumpState.DUMP_SERVICE_RESOLVERS
16442                            | DumpState.DUMP_RECEIVER_RESOLVERS
16443                            | DumpState.DUMP_CONTENT_RESOLVERS);
16444                } else {
16445                    while (opti < args.length) {
16446                        String name = args[opti];
16447                        if ("a".equals(name) || "activity".equals(name)) {
16448                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16449                        } else if ("s".equals(name) || "service".equals(name)) {
16450                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16451                        } else if ("r".equals(name) || "receiver".equals(name)) {
16452                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16453                        } else if ("c".equals(name) || "content".equals(name)) {
16454                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16455                        } else {
16456                            pw.println("Error: unknown resolver table type: " + name);
16457                            return;
16458                        }
16459                        opti++;
16460                    }
16461                }
16462            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16463                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16464            } else if ("permission".equals(cmd)) {
16465                if (opti >= args.length) {
16466                    pw.println("Error: permission requires permission name");
16467                    return;
16468                }
16469                permissionNames = new ArraySet<>();
16470                while (opti < args.length) {
16471                    permissionNames.add(args[opti]);
16472                    opti++;
16473                }
16474                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16475                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16476            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16477                dumpState.setDump(DumpState.DUMP_PREFERRED);
16478            } else if ("preferred-xml".equals(cmd)) {
16479                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16480                if (opti < args.length && "--full".equals(args[opti])) {
16481                    fullPreferred = true;
16482                    opti++;
16483                }
16484            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16485                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16486            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16487                dumpState.setDump(DumpState.DUMP_PACKAGES);
16488            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16489                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16490            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16491                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16492            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16493                dumpState.setDump(DumpState.DUMP_MESSAGES);
16494            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16495                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16496            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16497                    || "intent-filter-verifiers".equals(cmd)) {
16498                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16499            } else if ("version".equals(cmd)) {
16500                dumpState.setDump(DumpState.DUMP_VERSION);
16501            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16502                dumpState.setDump(DumpState.DUMP_KEYSETS);
16503            } else if ("installs".equals(cmd)) {
16504                dumpState.setDump(DumpState.DUMP_INSTALLS);
16505            } else if ("write".equals(cmd)) {
16506                synchronized (mPackages) {
16507                    mSettings.writeLPr();
16508                    pw.println("Settings written.");
16509                    return;
16510                }
16511            }
16512        }
16513
16514        if (checkin) {
16515            pw.println("vers,1");
16516        }
16517
16518        // reader
16519        synchronized (mPackages) {
16520            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16521                if (!checkin) {
16522                    if (dumpState.onTitlePrinted())
16523                        pw.println();
16524                    pw.println("Database versions:");
16525                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16526                }
16527            }
16528
16529            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16530                if (!checkin) {
16531                    if (dumpState.onTitlePrinted())
16532                        pw.println();
16533                    pw.println("Verifiers:");
16534                    pw.print("  Required: ");
16535                    pw.print(mRequiredVerifierPackage);
16536                    pw.print(" (uid=");
16537                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16538                            UserHandle.USER_SYSTEM));
16539                    pw.println(")");
16540                } else if (mRequiredVerifierPackage != null) {
16541                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16542                    pw.print(",");
16543                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16544                            UserHandle.USER_SYSTEM));
16545                }
16546            }
16547
16548            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16549                    packageName == null) {
16550                if (mIntentFilterVerifierComponent != null) {
16551                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16552                    if (!checkin) {
16553                        if (dumpState.onTitlePrinted())
16554                            pw.println();
16555                        pw.println("Intent Filter Verifier:");
16556                        pw.print("  Using: ");
16557                        pw.print(verifierPackageName);
16558                        pw.print(" (uid=");
16559                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16560                                UserHandle.USER_SYSTEM));
16561                        pw.println(")");
16562                    } else if (verifierPackageName != null) {
16563                        pw.print("ifv,"); pw.print(verifierPackageName);
16564                        pw.print(",");
16565                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16566                                UserHandle.USER_SYSTEM));
16567                    }
16568                } else {
16569                    pw.println();
16570                    pw.println("No Intent Filter Verifier available!");
16571                }
16572            }
16573
16574            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16575                boolean printedHeader = false;
16576                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16577                while (it.hasNext()) {
16578                    String name = it.next();
16579                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16580                    if (!checkin) {
16581                        if (!printedHeader) {
16582                            if (dumpState.onTitlePrinted())
16583                                pw.println();
16584                            pw.println("Libraries:");
16585                            printedHeader = true;
16586                        }
16587                        pw.print("  ");
16588                    } else {
16589                        pw.print("lib,");
16590                    }
16591                    pw.print(name);
16592                    if (!checkin) {
16593                        pw.print(" -> ");
16594                    }
16595                    if (ent.path != null) {
16596                        if (!checkin) {
16597                            pw.print("(jar) ");
16598                            pw.print(ent.path);
16599                        } else {
16600                            pw.print(",jar,");
16601                            pw.print(ent.path);
16602                        }
16603                    } else {
16604                        if (!checkin) {
16605                            pw.print("(apk) ");
16606                            pw.print(ent.apk);
16607                        } else {
16608                            pw.print(",apk,");
16609                            pw.print(ent.apk);
16610                        }
16611                    }
16612                    pw.println();
16613                }
16614            }
16615
16616            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16617                if (dumpState.onTitlePrinted())
16618                    pw.println();
16619                if (!checkin) {
16620                    pw.println("Features:");
16621                }
16622                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16623                while (it.hasNext()) {
16624                    String name = it.next();
16625                    if (!checkin) {
16626                        pw.print("  ");
16627                    } else {
16628                        pw.print("feat,");
16629                    }
16630                    pw.println(name);
16631                }
16632            }
16633
16634            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16635                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16636                        : "Activity Resolver Table:", "  ", packageName,
16637                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16638                    dumpState.setTitlePrinted(true);
16639                }
16640            }
16641            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16642                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16643                        : "Receiver Resolver Table:", "  ", packageName,
16644                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16645                    dumpState.setTitlePrinted(true);
16646                }
16647            }
16648            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16649                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16650                        : "Service Resolver Table:", "  ", packageName,
16651                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16652                    dumpState.setTitlePrinted(true);
16653                }
16654            }
16655            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16656                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16657                        : "Provider Resolver Table:", "  ", packageName,
16658                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16659                    dumpState.setTitlePrinted(true);
16660                }
16661            }
16662
16663            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16664                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16665                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16666                    int user = mSettings.mPreferredActivities.keyAt(i);
16667                    if (pir.dump(pw,
16668                            dumpState.getTitlePrinted()
16669                                ? "\nPreferred Activities User " + user + ":"
16670                                : "Preferred Activities User " + user + ":", "  ",
16671                            packageName, true, false)) {
16672                        dumpState.setTitlePrinted(true);
16673                    }
16674                }
16675            }
16676
16677            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16678                pw.flush();
16679                FileOutputStream fout = new FileOutputStream(fd);
16680                BufferedOutputStream str = new BufferedOutputStream(fout);
16681                XmlSerializer serializer = new FastXmlSerializer();
16682                try {
16683                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16684                    serializer.startDocument(null, true);
16685                    serializer.setFeature(
16686                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16687                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16688                    serializer.endDocument();
16689                    serializer.flush();
16690                } catch (IllegalArgumentException e) {
16691                    pw.println("Failed writing: " + e);
16692                } catch (IllegalStateException e) {
16693                    pw.println("Failed writing: " + e);
16694                } catch (IOException e) {
16695                    pw.println("Failed writing: " + e);
16696                }
16697            }
16698
16699            if (!checkin
16700                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16701                    && packageName == null) {
16702                pw.println();
16703                int count = mSettings.mPackages.size();
16704                if (count == 0) {
16705                    pw.println("No applications!");
16706                    pw.println();
16707                } else {
16708                    final String prefix = "  ";
16709                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16710                    if (allPackageSettings.size() == 0) {
16711                        pw.println("No domain preferred apps!");
16712                        pw.println();
16713                    } else {
16714                        pw.println("App verification status:");
16715                        pw.println();
16716                        count = 0;
16717                        for (PackageSetting ps : allPackageSettings) {
16718                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16719                            if (ivi == null || ivi.getPackageName() == null) continue;
16720                            pw.println(prefix + "Package: " + ivi.getPackageName());
16721                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16722                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16723                            pw.println();
16724                            count++;
16725                        }
16726                        if (count == 0) {
16727                            pw.println(prefix + "No app verification established.");
16728                            pw.println();
16729                        }
16730                        for (int userId : sUserManager.getUserIds()) {
16731                            pw.println("App linkages for user " + userId + ":");
16732                            pw.println();
16733                            count = 0;
16734                            for (PackageSetting ps : allPackageSettings) {
16735                                final long status = ps.getDomainVerificationStatusForUser(userId);
16736                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16737                                    continue;
16738                                }
16739                                pw.println(prefix + "Package: " + ps.name);
16740                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16741                                String statusStr = IntentFilterVerificationInfo.
16742                                        getStatusStringFromValue(status);
16743                                pw.println(prefix + "Status:  " + statusStr);
16744                                pw.println();
16745                                count++;
16746                            }
16747                            if (count == 0) {
16748                                pw.println(prefix + "No configured app linkages.");
16749                                pw.println();
16750                            }
16751                        }
16752                    }
16753                }
16754            }
16755
16756            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16757                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16758                if (packageName == null && permissionNames == null) {
16759                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16760                        if (iperm == 0) {
16761                            if (dumpState.onTitlePrinted())
16762                                pw.println();
16763                            pw.println("AppOp Permissions:");
16764                        }
16765                        pw.print("  AppOp Permission ");
16766                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16767                        pw.println(":");
16768                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16769                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16770                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16771                        }
16772                    }
16773                }
16774            }
16775
16776            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16777                boolean printedSomething = false;
16778                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16779                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16780                        continue;
16781                    }
16782                    if (!printedSomething) {
16783                        if (dumpState.onTitlePrinted())
16784                            pw.println();
16785                        pw.println("Registered ContentProviders:");
16786                        printedSomething = true;
16787                    }
16788                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16789                    pw.print("    "); pw.println(p.toString());
16790                }
16791                printedSomething = false;
16792                for (Map.Entry<String, PackageParser.Provider> entry :
16793                        mProvidersByAuthority.entrySet()) {
16794                    PackageParser.Provider p = entry.getValue();
16795                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16796                        continue;
16797                    }
16798                    if (!printedSomething) {
16799                        if (dumpState.onTitlePrinted())
16800                            pw.println();
16801                        pw.println("ContentProvider Authorities:");
16802                        printedSomething = true;
16803                    }
16804                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16805                    pw.print("    "); pw.println(p.toString());
16806                    if (p.info != null && p.info.applicationInfo != null) {
16807                        final String appInfo = p.info.applicationInfo.toString();
16808                        pw.print("      applicationInfo="); pw.println(appInfo);
16809                    }
16810                }
16811            }
16812
16813            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16814                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16815            }
16816
16817            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16818                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16819            }
16820
16821            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16822                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16823            }
16824
16825            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16826                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16827            }
16828
16829            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16830                // XXX should handle packageName != null by dumping only install data that
16831                // the given package is involved with.
16832                if (dumpState.onTitlePrinted()) pw.println();
16833                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16834            }
16835
16836            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16837                if (dumpState.onTitlePrinted()) pw.println();
16838                mSettings.dumpReadMessagesLPr(pw, dumpState);
16839
16840                pw.println();
16841                pw.println("Package warning messages:");
16842                BufferedReader in = null;
16843                String line = null;
16844                try {
16845                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16846                    while ((line = in.readLine()) != null) {
16847                        if (line.contains("ignored: updated version")) continue;
16848                        pw.println(line);
16849                    }
16850                } catch (IOException ignored) {
16851                } finally {
16852                    IoUtils.closeQuietly(in);
16853                }
16854            }
16855
16856            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16857                BufferedReader in = null;
16858                String line = null;
16859                try {
16860                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16861                    while ((line = in.readLine()) != null) {
16862                        if (line.contains("ignored: updated version")) continue;
16863                        pw.print("msg,");
16864                        pw.println(line);
16865                    }
16866                } catch (IOException ignored) {
16867                } finally {
16868                    IoUtils.closeQuietly(in);
16869                }
16870            }
16871        }
16872    }
16873
16874    private String dumpDomainString(String packageName) {
16875        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16876        List<IntentFilter> filters = getAllIntentFilters(packageName);
16877
16878        ArraySet<String> result = new ArraySet<>();
16879        if (iviList.size() > 0) {
16880            for (IntentFilterVerificationInfo ivi : iviList) {
16881                for (String host : ivi.getDomains()) {
16882                    result.add(host);
16883                }
16884            }
16885        }
16886        if (filters != null && filters.size() > 0) {
16887            for (IntentFilter filter : filters) {
16888                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16889                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16890                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16891                    result.addAll(filter.getHostsList());
16892                }
16893            }
16894        }
16895
16896        StringBuilder sb = new StringBuilder(result.size() * 16);
16897        for (String domain : result) {
16898            if (sb.length() > 0) sb.append(" ");
16899            sb.append(domain);
16900        }
16901        return sb.toString();
16902    }
16903
16904    // ------- apps on sdcard specific code -------
16905    static final boolean DEBUG_SD_INSTALL = false;
16906
16907    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16908
16909    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16910
16911    private boolean mMediaMounted = false;
16912
16913    static String getEncryptKey() {
16914        try {
16915            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16916                    SD_ENCRYPTION_KEYSTORE_NAME);
16917            if (sdEncKey == null) {
16918                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16919                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16920                if (sdEncKey == null) {
16921                    Slog.e(TAG, "Failed to create encryption keys");
16922                    return null;
16923                }
16924            }
16925            return sdEncKey;
16926        } catch (NoSuchAlgorithmException nsae) {
16927            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16928            return null;
16929        } catch (IOException ioe) {
16930            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16931            return null;
16932        }
16933    }
16934
16935    /*
16936     * Update media status on PackageManager.
16937     */
16938    @Override
16939    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16940        int callingUid = Binder.getCallingUid();
16941        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16942            throw new SecurityException("Media status can only be updated by the system");
16943        }
16944        // reader; this apparently protects mMediaMounted, but should probably
16945        // be a different lock in that case.
16946        synchronized (mPackages) {
16947            Log.i(TAG, "Updating external media status from "
16948                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16949                    + (mediaStatus ? "mounted" : "unmounted"));
16950            if (DEBUG_SD_INSTALL)
16951                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16952                        + ", mMediaMounted=" + mMediaMounted);
16953            if (mediaStatus == mMediaMounted) {
16954                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16955                        : 0, -1);
16956                mHandler.sendMessage(msg);
16957                return;
16958            }
16959            mMediaMounted = mediaStatus;
16960        }
16961        // Queue up an async operation since the package installation may take a
16962        // little while.
16963        mHandler.post(new Runnable() {
16964            public void run() {
16965                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16966            }
16967        });
16968    }
16969
16970    /**
16971     * Called by MountService when the initial ASECs to scan are available.
16972     * Should block until all the ASEC containers are finished being scanned.
16973     */
16974    public void scanAvailableAsecs() {
16975        updateExternalMediaStatusInner(true, false, false);
16976    }
16977
16978    /*
16979     * Collect information of applications on external media, map them against
16980     * existing containers and update information based on current mount status.
16981     * Please note that we always have to report status if reportStatus has been
16982     * set to true especially when unloading packages.
16983     */
16984    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16985            boolean externalStorage) {
16986        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16987        int[] uidArr = EmptyArray.INT;
16988
16989        final String[] list = PackageHelper.getSecureContainerList();
16990        if (ArrayUtils.isEmpty(list)) {
16991            Log.i(TAG, "No secure containers found");
16992        } else {
16993            // Process list of secure containers and categorize them
16994            // as active or stale based on their package internal state.
16995
16996            // reader
16997            synchronized (mPackages) {
16998                for (String cid : list) {
16999                    // Leave stages untouched for now; installer service owns them
17000                    if (PackageInstallerService.isStageName(cid)) continue;
17001
17002                    if (DEBUG_SD_INSTALL)
17003                        Log.i(TAG, "Processing container " + cid);
17004                    String pkgName = getAsecPackageName(cid);
17005                    if (pkgName == null) {
17006                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17007                        continue;
17008                    }
17009                    if (DEBUG_SD_INSTALL)
17010                        Log.i(TAG, "Looking for pkg : " + pkgName);
17011
17012                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17013                    if (ps == null) {
17014                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17015                        continue;
17016                    }
17017
17018                    /*
17019                     * Skip packages that are not external if we're unmounting
17020                     * external storage.
17021                     */
17022                    if (externalStorage && !isMounted && !isExternal(ps)) {
17023                        continue;
17024                    }
17025
17026                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17027                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17028                    // The package status is changed only if the code path
17029                    // matches between settings and the container id.
17030                    if (ps.codePathString != null
17031                            && ps.codePathString.startsWith(args.getCodePath())) {
17032                        if (DEBUG_SD_INSTALL) {
17033                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17034                                    + " at code path: " + ps.codePathString);
17035                        }
17036
17037                        // We do have a valid package installed on sdcard
17038                        processCids.put(args, ps.codePathString);
17039                        final int uid = ps.appId;
17040                        if (uid != -1) {
17041                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17042                        }
17043                    } else {
17044                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17045                                + ps.codePathString);
17046                    }
17047                }
17048            }
17049
17050            Arrays.sort(uidArr);
17051        }
17052
17053        // Process packages with valid entries.
17054        if (isMounted) {
17055            if (DEBUG_SD_INSTALL)
17056                Log.i(TAG, "Loading packages");
17057            loadMediaPackages(processCids, uidArr, externalStorage);
17058            startCleaningPackages();
17059            mInstallerService.onSecureContainersAvailable();
17060        } else {
17061            if (DEBUG_SD_INSTALL)
17062                Log.i(TAG, "Unloading packages");
17063            unloadMediaPackages(processCids, uidArr, reportStatus);
17064        }
17065    }
17066
17067    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17068            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17069        final int size = infos.size();
17070        final String[] packageNames = new String[size];
17071        final int[] packageUids = new int[size];
17072        for (int i = 0; i < size; i++) {
17073            final ApplicationInfo info = infos.get(i);
17074            packageNames[i] = info.packageName;
17075            packageUids[i] = info.uid;
17076        }
17077        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17078                finishedReceiver);
17079    }
17080
17081    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17082            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17083        sendResourcesChangedBroadcast(mediaStatus, replacing,
17084                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17085    }
17086
17087    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17088            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17089        int size = pkgList.length;
17090        if (size > 0) {
17091            // Send broadcasts here
17092            Bundle extras = new Bundle();
17093            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17094            if (uidArr != null) {
17095                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17096            }
17097            if (replacing) {
17098                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17099            }
17100            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17101                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17102            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17103        }
17104    }
17105
17106   /*
17107     * Look at potentially valid container ids from processCids If package
17108     * information doesn't match the one on record or package scanning fails,
17109     * the cid is added to list of removeCids. We currently don't delete stale
17110     * containers.
17111     */
17112    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17113            boolean externalStorage) {
17114        ArrayList<String> pkgList = new ArrayList<String>();
17115        Set<AsecInstallArgs> keys = processCids.keySet();
17116
17117        for (AsecInstallArgs args : keys) {
17118            String codePath = processCids.get(args);
17119            if (DEBUG_SD_INSTALL)
17120                Log.i(TAG, "Loading container : " + args.cid);
17121            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17122            try {
17123                // Make sure there are no container errors first.
17124                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17125                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17126                            + " when installing from sdcard");
17127                    continue;
17128                }
17129                // Check code path here.
17130                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17131                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17132                            + " does not match one in settings " + codePath);
17133                    continue;
17134                }
17135                // Parse package
17136                int parseFlags = mDefParseFlags;
17137                if (args.isExternalAsec()) {
17138                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17139                }
17140                if (args.isFwdLocked()) {
17141                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17142                }
17143
17144                synchronized (mInstallLock) {
17145                    PackageParser.Package pkg = null;
17146                    try {
17147                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17148                    } catch (PackageManagerException e) {
17149                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17150                    }
17151                    // Scan the package
17152                    if (pkg != null) {
17153                        /*
17154                         * TODO why is the lock being held? doPostInstall is
17155                         * called in other places without the lock. This needs
17156                         * to be straightened out.
17157                         */
17158                        // writer
17159                        synchronized (mPackages) {
17160                            retCode = PackageManager.INSTALL_SUCCEEDED;
17161                            pkgList.add(pkg.packageName);
17162                            // Post process args
17163                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17164                                    pkg.applicationInfo.uid);
17165                        }
17166                    } else {
17167                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17168                    }
17169                }
17170
17171            } finally {
17172                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17173                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17174                }
17175            }
17176        }
17177        // writer
17178        synchronized (mPackages) {
17179            // If the platform SDK has changed since the last time we booted,
17180            // we need to re-grant app permission to catch any new ones that
17181            // appear. This is really a hack, and means that apps can in some
17182            // cases get permissions that the user didn't initially explicitly
17183            // allow... it would be nice to have some better way to handle
17184            // this situation.
17185            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17186                    : mSettings.getInternalVersion();
17187            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17188                    : StorageManager.UUID_PRIVATE_INTERNAL;
17189
17190            int updateFlags = UPDATE_PERMISSIONS_ALL;
17191            if (ver.sdkVersion != mSdkVersion) {
17192                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17193                        + mSdkVersion + "; regranting permissions for external");
17194                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17195            }
17196            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17197
17198            // Yay, everything is now upgraded
17199            ver.forceCurrent();
17200
17201            // can downgrade to reader
17202            // Persist settings
17203            mSettings.writeLPr();
17204        }
17205        // Send a broadcast to let everyone know we are done processing
17206        if (pkgList.size() > 0) {
17207            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17208        }
17209    }
17210
17211   /*
17212     * Utility method to unload a list of specified containers
17213     */
17214    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17215        // Just unmount all valid containers.
17216        for (AsecInstallArgs arg : cidArgs) {
17217            synchronized (mInstallLock) {
17218                arg.doPostDeleteLI(false);
17219           }
17220       }
17221   }
17222
17223    /*
17224     * Unload packages mounted on external media. This involves deleting package
17225     * data from internal structures, sending broadcasts about disabled packages,
17226     * gc'ing to free up references, unmounting all secure containers
17227     * corresponding to packages on external media, and posting a
17228     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17229     * that we always have to post this message if status has been requested no
17230     * matter what.
17231     */
17232    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17233            final boolean reportStatus) {
17234        if (DEBUG_SD_INSTALL)
17235            Log.i(TAG, "unloading media packages");
17236        ArrayList<String> pkgList = new ArrayList<String>();
17237        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17238        final Set<AsecInstallArgs> keys = processCids.keySet();
17239        for (AsecInstallArgs args : keys) {
17240            String pkgName = args.getPackageName();
17241            if (DEBUG_SD_INSTALL)
17242                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17243            // Delete package internally
17244            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17245            synchronized (mInstallLock) {
17246                boolean res = deletePackageLI(pkgName, null, false, null, null,
17247                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17248                if (res) {
17249                    pkgList.add(pkgName);
17250                } else {
17251                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17252                    failedList.add(args);
17253                }
17254            }
17255        }
17256
17257        // reader
17258        synchronized (mPackages) {
17259            // We didn't update the settings after removing each package;
17260            // write them now for all packages.
17261            mSettings.writeLPr();
17262        }
17263
17264        // We have to absolutely send UPDATED_MEDIA_STATUS only
17265        // after confirming that all the receivers processed the ordered
17266        // broadcast when packages get disabled, force a gc to clean things up.
17267        // and unload all the containers.
17268        if (pkgList.size() > 0) {
17269            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17270                    new IIntentReceiver.Stub() {
17271                public void performReceive(Intent intent, int resultCode, String data,
17272                        Bundle extras, boolean ordered, boolean sticky,
17273                        int sendingUser) throws RemoteException {
17274                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17275                            reportStatus ? 1 : 0, 1, keys);
17276                    mHandler.sendMessage(msg);
17277                }
17278            });
17279        } else {
17280            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17281                    keys);
17282            mHandler.sendMessage(msg);
17283        }
17284    }
17285
17286    private void loadPrivatePackages(final VolumeInfo vol) {
17287        mHandler.post(new Runnable() {
17288            @Override
17289            public void run() {
17290                loadPrivatePackagesInner(vol);
17291            }
17292        });
17293    }
17294
17295    private void loadPrivatePackagesInner(VolumeInfo vol) {
17296        final String volumeUuid = vol.fsUuid;
17297        if (TextUtils.isEmpty(volumeUuid)) {
17298            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17299            return;
17300        }
17301
17302        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17303        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17304
17305        final VersionInfo ver;
17306        final List<PackageSetting> packages;
17307        synchronized (mPackages) {
17308            ver = mSettings.findOrCreateVersion(volumeUuid);
17309            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17310        }
17311
17312        // TODO: introduce a new concept similar to "frozen" to prevent these
17313        // apps from being launched until after data has been fully reconciled
17314        for (PackageSetting ps : packages) {
17315            synchronized (mInstallLock) {
17316                final PackageParser.Package pkg;
17317                try {
17318                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17319                    loaded.add(pkg.applicationInfo);
17320
17321                } catch (PackageManagerException e) {
17322                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17323                }
17324
17325                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17326                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17327                }
17328            }
17329        }
17330
17331        // Reconcile app data for all started/unlocked users
17332        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17333        final UserManager um = mContext.getSystemService(UserManager.class);
17334        for (UserInfo user : um.getUsers()) {
17335            final int flags;
17336            if (um.isUserUnlocked(user.id)) {
17337                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17338            } else if (um.isUserRunning(user.id)) {
17339                flags = StorageManager.FLAG_STORAGE_DE;
17340            } else {
17341                continue;
17342            }
17343
17344            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17345            reconcileAppsData(volumeUuid, user.id, flags);
17346        }
17347
17348        synchronized (mPackages) {
17349            int updateFlags = UPDATE_PERMISSIONS_ALL;
17350            if (ver.sdkVersion != mSdkVersion) {
17351                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17352                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17353                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17354            }
17355            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17356
17357            // Yay, everything is now upgraded
17358            ver.forceCurrent();
17359
17360            mSettings.writeLPr();
17361        }
17362
17363        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17364        sendResourcesChangedBroadcast(true, false, loaded, null);
17365    }
17366
17367    private void unloadPrivatePackages(final VolumeInfo vol) {
17368        mHandler.post(new Runnable() {
17369            @Override
17370            public void run() {
17371                unloadPrivatePackagesInner(vol);
17372            }
17373        });
17374    }
17375
17376    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17377        final String volumeUuid = vol.fsUuid;
17378        if (TextUtils.isEmpty(volumeUuid)) {
17379            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17380            return;
17381        }
17382
17383        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17384        synchronized (mInstallLock) {
17385        synchronized (mPackages) {
17386            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17387            for (PackageSetting ps : packages) {
17388                if (ps.pkg == null) continue;
17389
17390                final ApplicationInfo info = ps.pkg.applicationInfo;
17391                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17392                if (deletePackageLI(ps.name, null, false, null, null,
17393                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17394                    unloaded.add(info);
17395                } else {
17396                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17397                }
17398            }
17399
17400            mSettings.writeLPr();
17401        }
17402        }
17403
17404        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17405        sendResourcesChangedBroadcast(false, false, unloaded, null);
17406    }
17407
17408    /**
17409     * Examine all users present on given mounted volume, and destroy data
17410     * belonging to users that are no longer valid, or whose user ID has been
17411     * recycled.
17412     */
17413    private void reconcileUsers(String volumeUuid) {
17414        final File[] files = FileUtils
17415                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
17416        for (File file : files) {
17417            if (!file.isDirectory()) continue;
17418
17419            final int userId;
17420            final UserInfo info;
17421            try {
17422                userId = Integer.parseInt(file.getName());
17423                info = sUserManager.getUserInfo(userId);
17424            } catch (NumberFormatException e) {
17425                Slog.w(TAG, "Invalid user directory " + file);
17426                continue;
17427            }
17428
17429            boolean destroyUser = false;
17430            if (info == null) {
17431                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17432                        + " because no matching user was found");
17433                destroyUser = true;
17434            } else {
17435                try {
17436                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17437                } catch (IOException e) {
17438                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17439                            + " because we failed to enforce serial number: " + e);
17440                    destroyUser = true;
17441                }
17442            }
17443
17444            if (destroyUser) {
17445                synchronized (mInstallLock) {
17446                    try {
17447                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17448                    } catch (InstallerException e) {
17449                        Slog.w(TAG, "Failed to clean up user dirs", e);
17450                    }
17451                }
17452            }
17453        }
17454    }
17455
17456    private void assertPackageKnown(String volumeUuid, String packageName)
17457            throws PackageManagerException {
17458        synchronized (mPackages) {
17459            final PackageSetting ps = mSettings.mPackages.get(packageName);
17460            if (ps == null) {
17461                throw new PackageManagerException("Package " + packageName + " is unknown");
17462            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17463                throw new PackageManagerException(
17464                        "Package " + packageName + " found on unknown volume " + volumeUuid
17465                                + "; expected volume " + ps.volumeUuid);
17466            }
17467        }
17468    }
17469
17470    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17471            throws PackageManagerException {
17472        synchronized (mPackages) {
17473            final PackageSetting ps = mSettings.mPackages.get(packageName);
17474            if (ps == null) {
17475                throw new PackageManagerException("Package " + packageName + " is unknown");
17476            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17477                throw new PackageManagerException(
17478                        "Package " + packageName + " found on unknown volume " + volumeUuid
17479                                + "; expected volume " + ps.volumeUuid);
17480            } else if (!ps.getInstalled(userId)) {
17481                throw new PackageManagerException(
17482                        "Package " + packageName + " not installed for user " + userId);
17483            }
17484        }
17485    }
17486
17487    /**
17488     * Examine all apps present on given mounted volume, and destroy apps that
17489     * aren't expected, either due to uninstallation or reinstallation on
17490     * another volume.
17491     */
17492    private void reconcileApps(String volumeUuid) {
17493        final File[] files = FileUtils
17494                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17495        for (File file : files) {
17496            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17497                    && !PackageInstallerService.isStageName(file.getName());
17498            if (!isPackage) {
17499                // Ignore entries which are not packages
17500                continue;
17501            }
17502
17503            try {
17504                final PackageLite pkg = PackageParser.parsePackageLite(file,
17505                        PackageParser.PARSE_MUST_BE_APK);
17506                assertPackageKnown(volumeUuid, pkg.packageName);
17507
17508            } catch (PackageParserException | PackageManagerException e) {
17509                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17510                synchronized (mInstallLock) {
17511                    removeCodePathLI(file);
17512                }
17513            }
17514        }
17515    }
17516
17517    /**
17518     * Reconcile all app data for the given user.
17519     * <p>
17520     * Verifies that directories exist and that ownership and labeling is
17521     * correct for all installed apps on all mounted volumes.
17522     */
17523    void reconcileAppsData(int userId, int flags) {
17524        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17525        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17526            final String volumeUuid = vol.getFsUuid();
17527            reconcileAppsData(volumeUuid, userId, flags);
17528        }
17529    }
17530
17531    /**
17532     * Reconcile all app data on given mounted volume.
17533     * <p>
17534     * Destroys app data that isn't expected, either due to uninstallation or
17535     * reinstallation on another volume.
17536     * <p>
17537     * Verifies that directories exist and that ownership and labeling is
17538     * correct for all installed apps.
17539     */
17540    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17541        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17542                + Integer.toHexString(flags));
17543
17544        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
17545        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
17546
17547        boolean restoreconNeeded = false;
17548
17549        // First look for stale data that doesn't belong, and check if things
17550        // have changed since we did our last restorecon
17551        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17552            if (!isUserKeyUnlocked(userId)) {
17553                throw new RuntimeException(
17554                        "Yikes, someone asked us to reconcile CE storage while " + userId
17555                                + " was still locked; this would have caused massive data loss!");
17556            }
17557
17558            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17559
17560            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17561            for (File file : files) {
17562                final String packageName = file.getName();
17563                try {
17564                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17565                } catch (PackageManagerException e) {
17566                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17567                    synchronized (mInstallLock) {
17568                        destroyAppDataLI(volumeUuid, packageName, userId,
17569                                StorageManager.FLAG_STORAGE_CE);
17570                    }
17571                }
17572            }
17573        }
17574        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17575            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17576
17577            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17578            for (File file : files) {
17579                final String packageName = file.getName();
17580                try {
17581                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17582                } catch (PackageManagerException e) {
17583                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17584                    synchronized (mInstallLock) {
17585                        destroyAppDataLI(volumeUuid, packageName, userId,
17586                                StorageManager.FLAG_STORAGE_DE);
17587                    }
17588                }
17589            }
17590        }
17591
17592        // Ensure that data directories are ready to roll for all packages
17593        // installed for this volume and user
17594        final List<PackageSetting> packages;
17595        synchronized (mPackages) {
17596            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17597        }
17598        int preparedCount = 0;
17599        for (PackageSetting ps : packages) {
17600            final String packageName = ps.name;
17601            if (ps.pkg == null) {
17602                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17603                // TODO: might be due to legacy ASEC apps; we should circle back
17604                // and reconcile again once they're scanned
17605                continue;
17606            }
17607
17608            if (ps.getInstalled(userId)) {
17609                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17610                preparedCount++;
17611            }
17612        }
17613
17614        if (restoreconNeeded) {
17615            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17616                SELinuxMMAC.setRestoreconDone(ceDir);
17617            }
17618            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17619                SELinuxMMAC.setRestoreconDone(deDir);
17620            }
17621        }
17622
17623        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17624                + " packages; restoreconNeeded was " + restoreconNeeded);
17625    }
17626
17627    /**
17628     * Prepare app data for the given app just after it was installed or
17629     * upgraded. This method carefully only touches users that it's installed
17630     * for, and it forces a restorecon to handle any seinfo changes.
17631     * <p>
17632     * Verifies that directories exist and that ownership and labeling is
17633     * correct for all installed apps. If there is an ownership mismatch, it
17634     * will try recovering system apps by wiping data; third-party app data is
17635     * left intact.
17636     */
17637    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17638        prepareAppDataAfterInstallInternal(pkg);
17639        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17640        for (int i = 0; i < childCount; i++) {
17641            PackageParser.Package childPackage = pkg.childPackages.get(i);
17642            prepareAppDataAfterInstallInternal(childPackage);
17643        }
17644    }
17645
17646    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
17647        final PackageSetting ps;
17648        synchronized (mPackages) {
17649            ps = mSettings.mPackages.get(pkg.packageName);
17650        }
17651
17652        final UserManager um = mContext.getSystemService(UserManager.class);
17653        for (UserInfo user : um.getUsers()) {
17654            final int flags;
17655            if (um.isUserUnlocked(user.id)) {
17656                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17657            } else if (um.isUserRunning(user.id)) {
17658                flags = StorageManager.FLAG_STORAGE_DE;
17659            } else {
17660                continue;
17661            }
17662
17663            if (ps.getInstalled(user.id)) {
17664                // Whenever an app changes, force a restorecon of its data
17665                // TODO: when user data is locked, mark that we're still dirty
17666                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17667            }
17668        }
17669    }
17670
17671    /**
17672     * Prepare app data for the given app.
17673     * <p>
17674     * Verifies that directories exist and that ownership and labeling is
17675     * correct for all installed apps. If there is an ownership mismatch, this
17676     * will try recovering system apps by wiping data; third-party app data is
17677     * left intact.
17678     */
17679    private void prepareAppData(String volumeUuid, int userId, int flags,
17680            PackageParser.Package pkg, boolean restoreconNeeded) {
17681        if (DEBUG_APP_DATA) {
17682            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17683                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17684        }
17685
17686        final String packageName = pkg.packageName;
17687        final ApplicationInfo app = pkg.applicationInfo;
17688        final int appId = UserHandle.getAppId(app.uid);
17689
17690        Preconditions.checkNotNull(app.seinfo);
17691
17692        synchronized (mInstallLock) {
17693            try {
17694                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17695                        appId, app.seinfo, app.targetSdkVersion);
17696            } catch (InstallerException e) {
17697                if (app.isSystemApp()) {
17698                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17699                            + ", but trying to recover: " + e);
17700                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17701                    try {
17702                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17703                                appId, app.seinfo, app.targetSdkVersion);
17704                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17705                    } catch (InstallerException e2) {
17706                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17707                    }
17708                } else {
17709                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17710                }
17711            }
17712
17713            if (restoreconNeeded) {
17714                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17715            }
17716
17717            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17718                // Create a native library symlink only if we have native libraries
17719                // and if the native libraries are 32 bit libraries. We do not provide
17720                // this symlink for 64 bit libraries.
17721                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17722                    final String nativeLibPath = app.nativeLibraryDir;
17723                    try {
17724                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17725                                nativeLibPath, userId);
17726                    } catch (InstallerException e) {
17727                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17728                    }
17729                }
17730            }
17731        }
17732    }
17733
17734    private void unfreezePackage(String packageName) {
17735        synchronized (mPackages) {
17736            final PackageSetting ps = mSettings.mPackages.get(packageName);
17737            if (ps != null) {
17738                ps.frozen = false;
17739            }
17740        }
17741    }
17742
17743    @Override
17744    public int movePackage(final String packageName, final String volumeUuid) {
17745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17746
17747        final int moveId = mNextMoveId.getAndIncrement();
17748        mHandler.post(new Runnable() {
17749            @Override
17750            public void run() {
17751                try {
17752                    movePackageInternal(packageName, volumeUuid, moveId);
17753                } catch (PackageManagerException e) {
17754                    Slog.w(TAG, "Failed to move " + packageName, e);
17755                    mMoveCallbacks.notifyStatusChanged(moveId,
17756                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17757                }
17758            }
17759        });
17760        return moveId;
17761    }
17762
17763    private void movePackageInternal(final String packageName, final String volumeUuid,
17764            final int moveId) throws PackageManagerException {
17765        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17766        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17767        final PackageManager pm = mContext.getPackageManager();
17768
17769        final boolean currentAsec;
17770        final String currentVolumeUuid;
17771        final File codeFile;
17772        final String installerPackageName;
17773        final String packageAbiOverride;
17774        final int appId;
17775        final String seinfo;
17776        final String label;
17777        final int targetSdkVersion;
17778
17779        // reader
17780        synchronized (mPackages) {
17781            final PackageParser.Package pkg = mPackages.get(packageName);
17782            final PackageSetting ps = mSettings.mPackages.get(packageName);
17783            if (pkg == null || ps == null) {
17784                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17785            }
17786
17787            if (pkg.applicationInfo.isSystemApp()) {
17788                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17789                        "Cannot move system application");
17790            }
17791
17792            if (pkg.applicationInfo.isExternalAsec()) {
17793                currentAsec = true;
17794                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17795            } else if (pkg.applicationInfo.isForwardLocked()) {
17796                currentAsec = true;
17797                currentVolumeUuid = "forward_locked";
17798            } else {
17799                currentAsec = false;
17800                currentVolumeUuid = ps.volumeUuid;
17801
17802                final File probe = new File(pkg.codePath);
17803                final File probeOat = new File(probe, "oat");
17804                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17805                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17806                            "Move only supported for modern cluster style installs");
17807                }
17808            }
17809
17810            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17811                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17812                        "Package already moved to " + volumeUuid);
17813            }
17814
17815            if (ps.frozen) {
17816                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17817                        "Failed to move already frozen package");
17818            }
17819            ps.frozen = true;
17820
17821            codeFile = new File(pkg.codePath);
17822            installerPackageName = ps.installerPackageName;
17823            packageAbiOverride = ps.cpuAbiOverrideString;
17824            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17825            seinfo = pkg.applicationInfo.seinfo;
17826            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17827            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17828        }
17829
17830        // Now that we're guarded by frozen state, kill app during move
17831        final long token = Binder.clearCallingIdentity();
17832        try {
17833            killApplication(packageName, appId, "move pkg");
17834        } finally {
17835            Binder.restoreCallingIdentity(token);
17836        }
17837
17838        final Bundle extras = new Bundle();
17839        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17840        extras.putString(Intent.EXTRA_TITLE, label);
17841        mMoveCallbacks.notifyCreated(moveId, extras);
17842
17843        int installFlags;
17844        final boolean moveCompleteApp;
17845        final File measurePath;
17846
17847        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17848            installFlags = INSTALL_INTERNAL;
17849            moveCompleteApp = !currentAsec;
17850            measurePath = Environment.getDataAppDirectory(volumeUuid);
17851        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17852            installFlags = INSTALL_EXTERNAL;
17853            moveCompleteApp = false;
17854            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17855        } else {
17856            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17857            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17858                    || !volume.isMountedWritable()) {
17859                unfreezePackage(packageName);
17860                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17861                        "Move location not mounted private volume");
17862            }
17863
17864            Preconditions.checkState(!currentAsec);
17865
17866            installFlags = INSTALL_INTERNAL;
17867            moveCompleteApp = true;
17868            measurePath = Environment.getDataAppDirectory(volumeUuid);
17869        }
17870
17871        final PackageStats stats = new PackageStats(null, -1);
17872        synchronized (mInstaller) {
17873            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17874                unfreezePackage(packageName);
17875                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17876                        "Failed to measure package size");
17877            }
17878        }
17879
17880        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17881                + stats.dataSize);
17882
17883        final long startFreeBytes = measurePath.getFreeSpace();
17884        final long sizeBytes;
17885        if (moveCompleteApp) {
17886            sizeBytes = stats.codeSize + stats.dataSize;
17887        } else {
17888            sizeBytes = stats.codeSize;
17889        }
17890
17891        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17892            unfreezePackage(packageName);
17893            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17894                    "Not enough free space to move");
17895        }
17896
17897        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17898
17899        final CountDownLatch installedLatch = new CountDownLatch(1);
17900        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17901            @Override
17902            public void onUserActionRequired(Intent intent) throws RemoteException {
17903                throw new IllegalStateException();
17904            }
17905
17906            @Override
17907            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17908                    Bundle extras) throws RemoteException {
17909                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17910                        + PackageManager.installStatusToString(returnCode, msg));
17911
17912                installedLatch.countDown();
17913
17914                // Regardless of success or failure of the move operation,
17915                // always unfreeze the package
17916                unfreezePackage(packageName);
17917
17918                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17919                switch (status) {
17920                    case PackageInstaller.STATUS_SUCCESS:
17921                        mMoveCallbacks.notifyStatusChanged(moveId,
17922                                PackageManager.MOVE_SUCCEEDED);
17923                        break;
17924                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17925                        mMoveCallbacks.notifyStatusChanged(moveId,
17926                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17927                        break;
17928                    default:
17929                        mMoveCallbacks.notifyStatusChanged(moveId,
17930                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17931                        break;
17932                }
17933            }
17934        };
17935
17936        final MoveInfo move;
17937        if (moveCompleteApp) {
17938            // Kick off a thread to report progress estimates
17939            new Thread() {
17940                @Override
17941                public void run() {
17942                    while (true) {
17943                        try {
17944                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17945                                break;
17946                            }
17947                        } catch (InterruptedException ignored) {
17948                        }
17949
17950                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17951                        final int progress = 10 + (int) MathUtils.constrain(
17952                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17953                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17954                    }
17955                }
17956            }.start();
17957
17958            final String dataAppName = codeFile.getName();
17959            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17960                    dataAppName, appId, seinfo, targetSdkVersion);
17961        } else {
17962            move = null;
17963        }
17964
17965        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17966
17967        final Message msg = mHandler.obtainMessage(INIT_COPY);
17968        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17969        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17970                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17971        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17972        msg.obj = params;
17973
17974        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17975                System.identityHashCode(msg.obj));
17976        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17977                System.identityHashCode(msg.obj));
17978
17979        mHandler.sendMessage(msg);
17980    }
17981
17982    @Override
17983    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17984        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17985
17986        final int realMoveId = mNextMoveId.getAndIncrement();
17987        final Bundle extras = new Bundle();
17988        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17989        mMoveCallbacks.notifyCreated(realMoveId, extras);
17990
17991        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17992            @Override
17993            public void onCreated(int moveId, Bundle extras) {
17994                // Ignored
17995            }
17996
17997            @Override
17998            public void onStatusChanged(int moveId, int status, long estMillis) {
17999                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18000            }
18001        };
18002
18003        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18004        storage.setPrimaryStorageUuid(volumeUuid, callback);
18005        return realMoveId;
18006    }
18007
18008    @Override
18009    public int getMoveStatus(int moveId) {
18010        mContext.enforceCallingOrSelfPermission(
18011                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18012        return mMoveCallbacks.mLastStatus.get(moveId);
18013    }
18014
18015    @Override
18016    public void registerMoveCallback(IPackageMoveObserver callback) {
18017        mContext.enforceCallingOrSelfPermission(
18018                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18019        mMoveCallbacks.register(callback);
18020    }
18021
18022    @Override
18023    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18024        mContext.enforceCallingOrSelfPermission(
18025                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18026        mMoveCallbacks.unregister(callback);
18027    }
18028
18029    @Override
18030    public boolean setInstallLocation(int loc) {
18031        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18032                null);
18033        if (getInstallLocation() == loc) {
18034            return true;
18035        }
18036        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18037                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18038            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18039                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18040            return true;
18041        }
18042        return false;
18043   }
18044
18045    @Override
18046    public int getInstallLocation() {
18047        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18048                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18049                PackageHelper.APP_INSTALL_AUTO);
18050    }
18051
18052    /** Called by UserManagerService */
18053    void cleanUpUser(UserManagerService userManager, int userHandle) {
18054        synchronized (mPackages) {
18055            mDirtyUsers.remove(userHandle);
18056            mUserNeedsBadging.delete(userHandle);
18057            mSettings.removeUserLPw(userHandle);
18058            mPendingBroadcasts.remove(userHandle);
18059            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18060        }
18061        synchronized (mInstallLock) {
18062            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18063            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18064                final String volumeUuid = vol.getFsUuid();
18065                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18066                try {
18067                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18068                } catch (InstallerException e) {
18069                    Slog.w(TAG, "Failed to remove user data", e);
18070                }
18071            }
18072            synchronized (mPackages) {
18073                removeUnusedPackagesLILPw(userManager, userHandle);
18074            }
18075        }
18076    }
18077
18078    /**
18079     * We're removing userHandle and would like to remove any downloaded packages
18080     * that are no longer in use by any other user.
18081     * @param userHandle the user being removed
18082     */
18083    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18084        final boolean DEBUG_CLEAN_APKS = false;
18085        int [] users = userManager.getUserIds();
18086        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18087        while (psit.hasNext()) {
18088            PackageSetting ps = psit.next();
18089            if (ps.pkg == null) {
18090                continue;
18091            }
18092            final String packageName = ps.pkg.packageName;
18093            // Skip over if system app
18094            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18095                continue;
18096            }
18097            if (DEBUG_CLEAN_APKS) {
18098                Slog.i(TAG, "Checking package " + packageName);
18099            }
18100            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18101            if (keep) {
18102                if (DEBUG_CLEAN_APKS) {
18103                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18104                }
18105            } else {
18106                for (int i = 0; i < users.length; i++) {
18107                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18108                        keep = true;
18109                        if (DEBUG_CLEAN_APKS) {
18110                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18111                                    + users[i]);
18112                        }
18113                        break;
18114                    }
18115                }
18116            }
18117            if (!keep) {
18118                if (DEBUG_CLEAN_APKS) {
18119                    Slog.i(TAG, "  Removing package " + packageName);
18120                }
18121                mHandler.post(new Runnable() {
18122                    public void run() {
18123                        deletePackageX(packageName, userHandle, 0);
18124                    } //end run
18125                });
18126            }
18127        }
18128    }
18129
18130    /** Called by UserManagerService */
18131    void createNewUser(int userHandle) {
18132        synchronized (mInstallLock) {
18133            try {
18134                mInstaller.createUserConfig(userHandle);
18135            } catch (InstallerException e) {
18136                Slog.w(TAG, "Failed to create user config", e);
18137            }
18138            mSettings.createNewUserLI(this, mInstaller, userHandle);
18139        }
18140        synchronized (mPackages) {
18141            applyFactoryDefaultBrowserLPw(userHandle);
18142            primeDomainVerificationsLPw(userHandle);
18143        }
18144    }
18145
18146    void newUserCreated(final int userHandle) {
18147        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18148        // If permission review for legacy apps is required, we represent
18149        // dagerous permissions for such apps as always granted runtime
18150        // permissions to keep per user flag state whether review is needed.
18151        // Hence, if a new user is added we have to propagate dangerous
18152        // permission grants for these legacy apps.
18153        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18154            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18155                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18156        }
18157    }
18158
18159    @Override
18160    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18161        mContext.enforceCallingOrSelfPermission(
18162                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18163                "Only package verification agents can read the verifier device identity");
18164
18165        synchronized (mPackages) {
18166            return mSettings.getVerifierDeviceIdentityLPw();
18167        }
18168    }
18169
18170    @Override
18171    public void setPermissionEnforced(String permission, boolean enforced) {
18172        // TODO: Now that we no longer change GID for storage, this should to away.
18173        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18174                "setPermissionEnforced");
18175        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18176            synchronized (mPackages) {
18177                if (mSettings.mReadExternalStorageEnforced == null
18178                        || mSettings.mReadExternalStorageEnforced != enforced) {
18179                    mSettings.mReadExternalStorageEnforced = enforced;
18180                    mSettings.writeLPr();
18181                }
18182            }
18183            // kill any non-foreground processes so we restart them and
18184            // grant/revoke the GID.
18185            final IActivityManager am = ActivityManagerNative.getDefault();
18186            if (am != null) {
18187                final long token = Binder.clearCallingIdentity();
18188                try {
18189                    am.killProcessesBelowForeground("setPermissionEnforcement");
18190                } catch (RemoteException e) {
18191                } finally {
18192                    Binder.restoreCallingIdentity(token);
18193                }
18194            }
18195        } else {
18196            throw new IllegalArgumentException("No selective enforcement for " + permission);
18197        }
18198    }
18199
18200    @Override
18201    @Deprecated
18202    public boolean isPermissionEnforced(String permission) {
18203        return true;
18204    }
18205
18206    @Override
18207    public boolean isStorageLow() {
18208        final long token = Binder.clearCallingIdentity();
18209        try {
18210            final DeviceStorageMonitorInternal
18211                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18212            if (dsm != null) {
18213                return dsm.isMemoryLow();
18214            } else {
18215                return false;
18216            }
18217        } finally {
18218            Binder.restoreCallingIdentity(token);
18219        }
18220    }
18221
18222    @Override
18223    public IPackageInstaller getPackageInstaller() {
18224        return mInstallerService;
18225    }
18226
18227    private boolean userNeedsBadging(int userId) {
18228        int index = mUserNeedsBadging.indexOfKey(userId);
18229        if (index < 0) {
18230            final UserInfo userInfo;
18231            final long token = Binder.clearCallingIdentity();
18232            try {
18233                userInfo = sUserManager.getUserInfo(userId);
18234            } finally {
18235                Binder.restoreCallingIdentity(token);
18236            }
18237            final boolean b;
18238            if (userInfo != null && userInfo.isManagedProfile()) {
18239                b = true;
18240            } else {
18241                b = false;
18242            }
18243            mUserNeedsBadging.put(userId, b);
18244            return b;
18245        }
18246        return mUserNeedsBadging.valueAt(index);
18247    }
18248
18249    @Override
18250    public KeySet getKeySetByAlias(String packageName, String alias) {
18251        if (packageName == null || alias == null) {
18252            return null;
18253        }
18254        synchronized(mPackages) {
18255            final PackageParser.Package pkg = mPackages.get(packageName);
18256            if (pkg == null) {
18257                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18258                throw new IllegalArgumentException("Unknown package: " + packageName);
18259            }
18260            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18261            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18262        }
18263    }
18264
18265    @Override
18266    public KeySet getSigningKeySet(String packageName) {
18267        if (packageName == null) {
18268            return null;
18269        }
18270        synchronized(mPackages) {
18271            final PackageParser.Package pkg = mPackages.get(packageName);
18272            if (pkg == null) {
18273                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18274                throw new IllegalArgumentException("Unknown package: " + packageName);
18275            }
18276            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18277                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18278                throw new SecurityException("May not access signing KeySet of other apps.");
18279            }
18280            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18281            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18282        }
18283    }
18284
18285    @Override
18286    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18287        if (packageName == null || ks == null) {
18288            return false;
18289        }
18290        synchronized(mPackages) {
18291            final PackageParser.Package pkg = mPackages.get(packageName);
18292            if (pkg == null) {
18293                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18294                throw new IllegalArgumentException("Unknown package: " + packageName);
18295            }
18296            IBinder ksh = ks.getToken();
18297            if (ksh instanceof KeySetHandle) {
18298                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18299                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18300            }
18301            return false;
18302        }
18303    }
18304
18305    @Override
18306    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18307        if (packageName == null || ks == null) {
18308            return false;
18309        }
18310        synchronized(mPackages) {
18311            final PackageParser.Package pkg = mPackages.get(packageName);
18312            if (pkg == null) {
18313                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18314                throw new IllegalArgumentException("Unknown package: " + packageName);
18315            }
18316            IBinder ksh = ks.getToken();
18317            if (ksh instanceof KeySetHandle) {
18318                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18319                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18320            }
18321            return false;
18322        }
18323    }
18324
18325    private void deletePackageIfUnusedLPr(final String packageName) {
18326        PackageSetting ps = mSettings.mPackages.get(packageName);
18327        if (ps == null) {
18328            return;
18329        }
18330        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18331            // TODO Implement atomic delete if package is unused
18332            // It is currently possible that the package will be deleted even if it is installed
18333            // after this method returns.
18334            mHandler.post(new Runnable() {
18335                public void run() {
18336                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18337                }
18338            });
18339        }
18340    }
18341
18342    /**
18343     * Check and throw if the given before/after packages would be considered a
18344     * downgrade.
18345     */
18346    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18347            throws PackageManagerException {
18348        if (after.versionCode < before.mVersionCode) {
18349            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18350                    "Update version code " + after.versionCode + " is older than current "
18351                    + before.mVersionCode);
18352        } else if (after.versionCode == before.mVersionCode) {
18353            if (after.baseRevisionCode < before.baseRevisionCode) {
18354                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18355                        "Update base revision code " + after.baseRevisionCode
18356                        + " is older than current " + before.baseRevisionCode);
18357            }
18358
18359            if (!ArrayUtils.isEmpty(after.splitNames)) {
18360                for (int i = 0; i < after.splitNames.length; i++) {
18361                    final String splitName = after.splitNames[i];
18362                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18363                    if (j != -1) {
18364                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18365                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18366                                    "Update split " + splitName + " revision code "
18367                                    + after.splitRevisionCodes[i] + " is older than current "
18368                                    + before.splitRevisionCodes[j]);
18369                        }
18370                    }
18371                }
18372            }
18373        }
18374    }
18375
18376    private static class MoveCallbacks extends Handler {
18377        private static final int MSG_CREATED = 1;
18378        private static final int MSG_STATUS_CHANGED = 2;
18379
18380        private final RemoteCallbackList<IPackageMoveObserver>
18381                mCallbacks = new RemoteCallbackList<>();
18382
18383        private final SparseIntArray mLastStatus = new SparseIntArray();
18384
18385        public MoveCallbacks(Looper looper) {
18386            super(looper);
18387        }
18388
18389        public void register(IPackageMoveObserver callback) {
18390            mCallbacks.register(callback);
18391        }
18392
18393        public void unregister(IPackageMoveObserver callback) {
18394            mCallbacks.unregister(callback);
18395        }
18396
18397        @Override
18398        public void handleMessage(Message msg) {
18399            final SomeArgs args = (SomeArgs) msg.obj;
18400            final int n = mCallbacks.beginBroadcast();
18401            for (int i = 0; i < n; i++) {
18402                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18403                try {
18404                    invokeCallback(callback, msg.what, args);
18405                } catch (RemoteException ignored) {
18406                }
18407            }
18408            mCallbacks.finishBroadcast();
18409            args.recycle();
18410        }
18411
18412        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18413                throws RemoteException {
18414            switch (what) {
18415                case MSG_CREATED: {
18416                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18417                    break;
18418                }
18419                case MSG_STATUS_CHANGED: {
18420                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18421                    break;
18422                }
18423            }
18424        }
18425
18426        private void notifyCreated(int moveId, Bundle extras) {
18427            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18428
18429            final SomeArgs args = SomeArgs.obtain();
18430            args.argi1 = moveId;
18431            args.arg2 = extras;
18432            obtainMessage(MSG_CREATED, args).sendToTarget();
18433        }
18434
18435        private void notifyStatusChanged(int moveId, int status) {
18436            notifyStatusChanged(moveId, status, -1);
18437        }
18438
18439        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18440            Slog.v(TAG, "Move " + moveId + " status " + status);
18441
18442            final SomeArgs args = SomeArgs.obtain();
18443            args.argi1 = moveId;
18444            args.argi2 = status;
18445            args.arg3 = estMillis;
18446            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18447
18448            synchronized (mLastStatus) {
18449                mLastStatus.put(moveId, status);
18450            }
18451        }
18452    }
18453
18454    private final static class OnPermissionChangeListeners extends Handler {
18455        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18456
18457        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18458                new RemoteCallbackList<>();
18459
18460        public OnPermissionChangeListeners(Looper looper) {
18461            super(looper);
18462        }
18463
18464        @Override
18465        public void handleMessage(Message msg) {
18466            switch (msg.what) {
18467                case MSG_ON_PERMISSIONS_CHANGED: {
18468                    final int uid = msg.arg1;
18469                    handleOnPermissionsChanged(uid);
18470                } break;
18471            }
18472        }
18473
18474        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18475            mPermissionListeners.register(listener);
18476
18477        }
18478
18479        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18480            mPermissionListeners.unregister(listener);
18481        }
18482
18483        public void onPermissionsChanged(int uid) {
18484            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18485                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18486            }
18487        }
18488
18489        private void handleOnPermissionsChanged(int uid) {
18490            final int count = mPermissionListeners.beginBroadcast();
18491            try {
18492                for (int i = 0; i < count; i++) {
18493                    IOnPermissionsChangeListener callback = mPermissionListeners
18494                            .getBroadcastItem(i);
18495                    try {
18496                        callback.onPermissionsChanged(uid);
18497                    } catch (RemoteException e) {
18498                        Log.e(TAG, "Permission listener is dead", e);
18499                    }
18500                }
18501            } finally {
18502                mPermissionListeners.finishBroadcast();
18503            }
18504        }
18505    }
18506
18507    private class PackageManagerInternalImpl extends PackageManagerInternal {
18508        @Override
18509        public void setLocationPackagesProvider(PackagesProvider provider) {
18510            synchronized (mPackages) {
18511                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18512            }
18513        }
18514
18515        @Override
18516        public void setImePackagesProvider(PackagesProvider provider) {
18517            synchronized (mPackages) {
18518                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
18519            }
18520        }
18521
18522        @Override
18523        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18524            synchronized (mPackages) {
18525                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18526            }
18527        }
18528
18529        @Override
18530        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18531            synchronized (mPackages) {
18532                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18533            }
18534        }
18535
18536        @Override
18537        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18538            synchronized (mPackages) {
18539                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18540            }
18541        }
18542
18543        @Override
18544        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18545            synchronized (mPackages) {
18546                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18547            }
18548        }
18549
18550        @Override
18551        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18552            synchronized (mPackages) {
18553                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18554            }
18555        }
18556
18557        @Override
18558        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18559            synchronized (mPackages) {
18560                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18561                        packageName, userId);
18562            }
18563        }
18564
18565        @Override
18566        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18567            synchronized (mPackages) {
18568                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18569                        packageName, userId);
18570            }
18571        }
18572
18573        @Override
18574        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18575            synchronized (mPackages) {
18576                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18577                        packageName, userId);
18578            }
18579        }
18580
18581        @Override
18582        public void setKeepUninstalledPackages(final List<String> packageList) {
18583            Preconditions.checkNotNull(packageList);
18584            List<String> removedFromList = null;
18585            synchronized (mPackages) {
18586                if (mKeepUninstalledPackages != null) {
18587                    final int packagesCount = mKeepUninstalledPackages.size();
18588                    for (int i = 0; i < packagesCount; i++) {
18589                        String oldPackage = mKeepUninstalledPackages.get(i);
18590                        if (packageList != null && packageList.contains(oldPackage)) {
18591                            continue;
18592                        }
18593                        if (removedFromList == null) {
18594                            removedFromList = new ArrayList<>();
18595                        }
18596                        removedFromList.add(oldPackage);
18597                    }
18598                }
18599                mKeepUninstalledPackages = new ArrayList<>(packageList);
18600                if (removedFromList != null) {
18601                    final int removedCount = removedFromList.size();
18602                    for (int i = 0; i < removedCount; i++) {
18603                        deletePackageIfUnusedLPr(removedFromList.get(i));
18604                    }
18605                }
18606            }
18607        }
18608
18609        @Override
18610        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18611            synchronized (mPackages) {
18612                // If we do not support permission review, done.
18613                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18614                    return false;
18615                }
18616
18617                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18618                if (packageSetting == null) {
18619                    return false;
18620                }
18621
18622                // Permission review applies only to apps not supporting the new permission model.
18623                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18624                    return false;
18625                }
18626
18627                // Legacy apps have the permission and get user consent on launch.
18628                PermissionsState permissionsState = packageSetting.getPermissionsState();
18629                return permissionsState.isPermissionReviewRequired(userId);
18630            }
18631        }
18632    }
18633
18634    @Override
18635    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18636        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18637        synchronized (mPackages) {
18638            final long identity = Binder.clearCallingIdentity();
18639            try {
18640                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18641                        packageNames, userId);
18642            } finally {
18643                Binder.restoreCallingIdentity(identity);
18644            }
18645        }
18646    }
18647
18648    private static void enforceSystemOrPhoneCaller(String tag) {
18649        int callingUid = Binder.getCallingUid();
18650        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18651            throw new SecurityException(
18652                    "Cannot call " + tag + " from UID " + callingUid);
18653        }
18654    }
18655
18656    boolean isHistoricalPackageUsageAvailable() {
18657        return mPackageUsage.isHistoricalPackageUsageAvailable();
18658    }
18659}
18660