PackageManagerService.java revision 8924e8759f9a8cffb5ad538ca40a7826793aac07
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
87
88import android.Manifest;
89import android.app.ActivityManager;
90import android.app.ActivityManagerNative;
91import android.app.AppGlobals;
92import android.app.IActivityManager;
93import android.app.admin.IDevicePolicyManager;
94import android.app.backup.IBackupManager;
95import android.app.usage.UsageStats;
96import android.app.usage.UsageStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.AppsQueryHelper;
109import android.content.pm.FeatureInfo;
110import android.content.pm.IOnPermissionsChangeListener;
111import android.content.pm.IPackageDataObserver;
112import android.content.pm.IPackageDeleteObserver;
113import android.content.pm.IPackageDeleteObserver2;
114import android.content.pm.IPackageInstallObserver2;
115import android.content.pm.IPackageInstaller;
116import android.content.pm.IPackageManager;
117import android.content.pm.IPackageMoveObserver;
118import android.content.pm.IPackageStatsObserver;
119import android.content.pm.InstrumentationInfo;
120import android.content.pm.IntentFilterVerificationInfo;
121import android.content.pm.KeySet;
122import android.content.pm.ManifestDigest;
123import android.content.pm.PackageCleanItem;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageInfoLite;
126import android.content.pm.PackageInstaller;
127import android.content.pm.PackageManager;
128import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
129import android.content.pm.PackageManagerInternal;
130import android.content.pm.PackageParser;
131import android.content.pm.PackageParser.ActivityIntentInfo;
132import android.content.pm.PackageParser.PackageLite;
133import android.content.pm.PackageParser.PackageParserException;
134import android.content.pm.PackageStats;
135import android.content.pm.PackageUserState;
136import android.content.pm.ParceledListSlice;
137import android.content.pm.PermissionGroupInfo;
138import android.content.pm.PermissionInfo;
139import android.content.pm.ProviderInfo;
140import android.content.pm.ResolveInfo;
141import android.content.pm.ServiceInfo;
142import android.content.pm.Signature;
143import android.content.pm.UserInfo;
144import android.content.pm.VerificationParams;
145import android.content.pm.VerifierDeviceIdentity;
146import android.content.pm.VerifierInfo;
147import android.content.res.Resources;
148import android.hardware.display.DisplayManager;
149import android.net.Uri;
150import android.os.Debug;
151import android.os.Binder;
152import android.os.Build;
153import android.os.Bundle;
154import android.os.Environment;
155import android.os.Environment.UserEnvironment;
156import android.os.FileUtils;
157import android.os.Handler;
158import android.os.IBinder;
159import android.os.Looper;
160import android.os.Message;
161import android.os.Parcel;
162import android.os.ParcelFileDescriptor;
163import android.os.Process;
164import android.os.RemoteCallbackList;
165import android.os.RemoteException;
166import android.os.ResultReceiver;
167import android.os.SELinux;
168import android.os.ServiceManager;
169import android.os.SystemClock;
170import android.os.SystemProperties;
171import android.os.Trace;
172import android.os.UserHandle;
173import android.os.UserManager;
174import android.os.storage.IMountService;
175import android.os.storage.MountServiceInternal;
176import android.os.storage.StorageEventListener;
177import android.os.storage.StorageManager;
178import android.os.storage.VolumeInfo;
179import android.os.storage.VolumeRecord;
180import android.security.KeyStore;
181import android.security.SystemKeyStore;
182import android.system.ErrnoException;
183import android.system.Os;
184import android.system.StructStat;
185import android.text.TextUtils;
186import android.text.format.DateUtils;
187import android.util.ArrayMap;
188import android.util.ArraySet;
189import android.util.AtomicFile;
190import android.util.DisplayMetrics;
191import android.util.EventLog;
192import android.util.ExceptionUtils;
193import android.util.Log;
194import android.util.LogPrinter;
195import android.util.MathUtils;
196import android.util.PrintStreamPrinter;
197import android.util.Slog;
198import android.util.SparseArray;
199import android.util.SparseBooleanArray;
200import android.util.SparseIntArray;
201import android.util.Xml;
202import android.view.Display;
203
204import dalvik.system.DexFile;
205import dalvik.system.VMRuntime;
206
207import libcore.io.IoUtils;
208import libcore.util.EmptyArray;
209
210import com.android.internal.R;
211import com.android.internal.annotations.GuardedBy;
212import com.android.internal.app.EphemeralResolveInfo;
213import com.android.internal.app.IMediaContainerService;
214import com.android.internal.app.ResolverActivity;
215import com.android.internal.content.NativeLibraryHelper;
216import com.android.internal.content.PackageHelper;
217import com.android.internal.os.IParcelFileDescriptorFactory;
218import com.android.internal.os.SomeArgs;
219import com.android.internal.os.Zygote;
220import com.android.internal.util.ArrayUtils;
221import com.android.internal.util.FastPrintWriter;
222import com.android.internal.util.FastXmlSerializer;
223import com.android.internal.util.IndentingPrintWriter;
224import com.android.internal.util.Preconditions;
225import com.android.server.EventLogTags;
226import com.android.server.FgThread;
227import com.android.server.IntentResolver;
228import com.android.server.LocalServices;
229import com.android.server.ServiceThread;
230import com.android.server.SystemConfig;
231import com.android.server.Watchdog;
232import com.android.server.pm.PermissionsState.PermissionState;
233import com.android.server.pm.Settings.DatabaseVersion;
234import com.android.server.pm.Settings.VersionInfo;
235import com.android.server.storage.DeviceStorageMonitorInternal;
236
237import org.xmlpull.v1.XmlPullParser;
238import org.xmlpull.v1.XmlPullParserException;
239import org.xmlpull.v1.XmlSerializer;
240
241import java.io.BufferedInputStream;
242import java.io.BufferedOutputStream;
243import java.io.BufferedReader;
244import java.io.ByteArrayInputStream;
245import java.io.ByteArrayOutputStream;
246import java.io.File;
247import java.io.FileDescriptor;
248import java.io.FileNotFoundException;
249import java.io.FileOutputStream;
250import java.io.FileReader;
251import java.io.FilenameFilter;
252import java.io.IOException;
253import java.io.InputStream;
254import java.io.PrintWriter;
255import java.nio.charset.StandardCharsets;
256import java.security.MessageDigest;
257import java.security.NoSuchAlgorithmException;
258import java.security.PublicKey;
259import java.security.cert.CertificateEncodingException;
260import java.security.cert.CertificateException;
261import java.text.SimpleDateFormat;
262import java.util.ArrayList;
263import java.util.Arrays;
264import java.util.Collection;
265import java.util.Collections;
266import java.util.Comparator;
267import java.util.Date;
268import java.util.Iterator;
269import java.util.List;
270import java.util.Map;
271import java.util.Objects;
272import java.util.Set;
273import java.util.concurrent.CountDownLatch;
274import java.util.concurrent.TimeUnit;
275import java.util.concurrent.atomic.AtomicBoolean;
276import java.util.concurrent.atomic.AtomicInteger;
277import java.util.concurrent.atomic.AtomicLong;
278
279/**
280 * Keep track of all those .apks everywhere.
281 *
282 * This is very central to the platform's security; please run the unit
283 * tests whenever making modifications here:
284 *
285runtest -c android.content.pm.PackageManagerTests frameworks-core
286 *
287 * {@hide}
288 */
289public class PackageManagerService extends IPackageManager.Stub {
290    static final String TAG = "PackageManager";
291    static final boolean DEBUG_SETTINGS = false;
292    static final boolean DEBUG_PREFERRED = false;
293    static final boolean DEBUG_UPGRADE = false;
294    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
295    private static final boolean DEBUG_BACKUP = false;
296    private static final boolean DEBUG_INSTALL = false;
297    private static final boolean DEBUG_REMOVE = false;
298    private static final boolean DEBUG_BROADCASTS = false;
299    private static final boolean DEBUG_SHOW_INFO = false;
300    private static final boolean DEBUG_PACKAGE_INFO = false;
301    private static final boolean DEBUG_INTENT_MATCHING = false;
302    private static final boolean DEBUG_PACKAGE_SCANNING = false;
303    private static final boolean DEBUG_VERIFY = false;
304    private static final boolean DEBUG_DEXOPT = false;
305    private static final boolean DEBUG_ABI_SELECTION = false;
306    private static final boolean DEBUG_EPHEMERAL = false;
307
308    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
309
310    private static final int RADIO_UID = Process.PHONE_UID;
311    private static final int LOG_UID = Process.LOG_UID;
312    private static final int NFC_UID = Process.NFC_UID;
313    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
314    private static final int SHELL_UID = Process.SHELL_UID;
315
316    // Cap the size of permission trees that 3rd party apps can define
317    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
318
319    // Suffix used during package installation when copying/moving
320    // package apks to install directory.
321    private static final String INSTALL_PACKAGE_SUFFIX = "-";
322
323    static final int SCAN_NO_DEX = 1<<1;
324    static final int SCAN_FORCE_DEX = 1<<2;
325    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
326    static final int SCAN_NEW_INSTALL = 1<<4;
327    static final int SCAN_NO_PATHS = 1<<5;
328    static final int SCAN_UPDATE_TIME = 1<<6;
329    static final int SCAN_DEFER_DEX = 1<<7;
330    static final int SCAN_BOOTING = 1<<8;
331    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
332    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
333    static final int SCAN_REPLACING = 1<<11;
334    static final int SCAN_REQUIRE_KNOWN = 1<<12;
335    static final int SCAN_MOVE = 1<<13;
336    static final int SCAN_INITIAL = 1<<14;
337
338    static final int REMOVE_CHATTY = 1<<16;
339
340    private static final int[] EMPTY_INT_ARRAY = new int[0];
341
342    /**
343     * Timeout (in milliseconds) after which the watchdog should declare that
344     * our handler thread is wedged.  The usual default for such things is one
345     * minute but we sometimes do very lengthy I/O operations on this thread,
346     * such as installing multi-gigabyte applications, so ours needs to be longer.
347     */
348    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
349
350    /**
351     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
352     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
353     * settings entry if available, otherwise we use the hardcoded default.  If it's been
354     * more than this long since the last fstrim, we force one during the boot sequence.
355     *
356     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
357     * one gets run at the next available charging+idle time.  This final mandatory
358     * no-fstrim check kicks in only of the other scheduling criteria is never met.
359     */
360    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
361
362    /**
363     * Whether verification is enabled by default.
364     */
365    private static final boolean DEFAULT_VERIFY_ENABLE = true;
366
367    /**
368     * The default maximum time to wait for the verification agent to return in
369     * milliseconds.
370     */
371    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
372
373    /**
374     * The default response for package verification timeout.
375     *
376     * This can be either PackageManager.VERIFICATION_ALLOW or
377     * PackageManager.VERIFICATION_REJECT.
378     */
379    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
380
381    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
382
383    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
384            DEFAULT_CONTAINER_PACKAGE,
385            "com.android.defcontainer.DefaultContainerService");
386
387    private static final String KILL_APP_REASON_GIDS_CHANGED =
388            "permission grant or revoke changed gids";
389
390    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
391            "permissions revoked";
392
393    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
394
395    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
396
397    /** Permission grant: not grant the permission. */
398    private static final int GRANT_DENIED = 1;
399
400    /** Permission grant: grant the permission as an install permission. */
401    private static final int GRANT_INSTALL = 2;
402
403    /** Permission grant: grant the permission as an install permission for a legacy app. */
404    private static final int GRANT_INSTALL_LEGACY = 3;
405
406    /** Permission grant: grant the permission as a runtime one. */
407    private static final int GRANT_RUNTIME = 4;
408
409    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
410    private static final int GRANT_UPGRADE = 5;
411
412    /** Canonical intent used to identify what counts as a "web browser" app */
413    private static final Intent sBrowserIntent;
414    static {
415        sBrowserIntent = new Intent();
416        sBrowserIntent.setAction(Intent.ACTION_VIEW);
417        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
418        sBrowserIntent.setData(Uri.parse("http:"));
419    }
420
421    final ServiceThread mHandlerThread;
422
423    final PackageHandler mHandler;
424
425    /**
426     * Messages for {@link #mHandler} that need to wait for system ready before
427     * being dispatched.
428     */
429    private ArrayList<Message> mPostSystemReadyMessages;
430
431    final int mSdkVersion = Build.VERSION.SDK_INT;
432
433    final Context mContext;
434    final boolean mFactoryTest;
435    final boolean mOnlyCore;
436    final DisplayMetrics mMetrics;
437    final int mDefParseFlags;
438    final String[] mSeparateProcesses;
439    final boolean mIsUpgrade;
440
441    // This is where all application persistent data goes.
442    final File mAppDataDir;
443
444    // This is where all application persistent data goes for secondary users.
445    final File mUserAppDataDir;
446
447    /** The location for ASEC container files on internal storage. */
448    final String mAsecInternalPath;
449
450    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
451    // LOCK HELD.  Can be called with mInstallLock held.
452    @GuardedBy("mInstallLock")
453    final Installer mInstaller;
454
455    /** Directory where installed third-party apps stored */
456    final File mAppInstallDir;
457
458    /**
459     * Directory to which applications installed internally have their
460     * 32 bit native libraries copied.
461     */
462    private File mAppLib32InstallDir;
463
464    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
465    // apps.
466    final File mDrmAppPrivateInstallDir;
467
468    // ----------------------------------------------------------------
469
470    // Lock for state used when installing and doing other long running
471    // operations.  Methods that must be called with this lock held have
472    // the suffix "LI".
473    final Object mInstallLock = new Object();
474
475    // ----------------------------------------------------------------
476
477    // Keys are String (package name), values are Package.  This also serves
478    // as the lock for the global state.  Methods that must be called with
479    // this lock held have the prefix "LP".
480    @GuardedBy("mPackages")
481    final ArrayMap<String, PackageParser.Package> mPackages =
482            new ArrayMap<String, PackageParser.Package>();
483
484    // Tracks available target package names -> overlay package paths.
485    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
486        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
487
488    /**
489     * Tracks new system packages [received in an OTA] that we expect to
490     * find updated user-installed versions. Keys are package name, values
491     * are package location.
492     */
493    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
494
495    /**
496     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
497     */
498    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
499    /**
500     * Whether or not system app permissions should be promoted from install to runtime.
501     */
502    boolean mPromoteSystemApps;
503
504    final Settings mSettings;
505    boolean mRestoredSettings;
506
507    // System configuration read by SystemConfig.
508    final int[] mGlobalGids;
509    final SparseArray<ArraySet<String>> mSystemPermissions;
510    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
511
512    // If mac_permissions.xml was found for seinfo labeling.
513    boolean mFoundPolicyFile;
514
515    // If a recursive restorecon of /data/data/<pkg> is needed.
516    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
517
518    public static final class SharedLibraryEntry {
519        public final String path;
520        public final String apk;
521
522        SharedLibraryEntry(String _path, String _apk) {
523            path = _path;
524            apk = _apk;
525        }
526    }
527
528    // Currently known shared libraries.
529    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
530            new ArrayMap<String, SharedLibraryEntry>();
531
532    // All available activities, for your resolving pleasure.
533    final ActivityIntentResolver mActivities =
534            new ActivityIntentResolver();
535
536    // All available receivers, for your resolving pleasure.
537    final ActivityIntentResolver mReceivers =
538            new ActivityIntentResolver();
539
540    // All available services, for your resolving pleasure.
541    final ServiceIntentResolver mServices = new ServiceIntentResolver();
542
543    // All available providers, for your resolving pleasure.
544    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
545
546    // Mapping from provider base names (first directory in content URI codePath)
547    // to the provider information.
548    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
549            new ArrayMap<String, PackageParser.Provider>();
550
551    // Mapping from instrumentation class names to info about them.
552    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
553            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
554
555    // Mapping from permission names to info about them.
556    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
557            new ArrayMap<String, PackageParser.PermissionGroup>();
558
559    // Packages whose data we have transfered into another package, thus
560    // should no longer exist.
561    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
562
563    // Broadcast actions that are only available to the system.
564    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
565
566    /** List of packages waiting for verification. */
567    final SparseArray<PackageVerificationState> mPendingVerification
568            = new SparseArray<PackageVerificationState>();
569
570    /** Set of packages associated with each app op permission. */
571    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
572
573    final PackageInstallerService mInstallerService;
574
575    private final PackageDexOptimizer mPackageDexOptimizer;
576
577    private AtomicInteger mNextMoveId = new AtomicInteger();
578    private final MoveCallbacks mMoveCallbacks;
579
580    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
581
582    // Cache of users who need badging.
583    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
584
585    /** Token for keys in mPendingVerification. */
586    private int mPendingVerificationToken = 0;
587
588    volatile boolean mSystemReady;
589    volatile boolean mSafeMode;
590    volatile boolean mHasSystemUidErrors;
591
592    ApplicationInfo mAndroidApplication;
593    final ActivityInfo mResolveActivity = new ActivityInfo();
594    final ResolveInfo mResolveInfo = new ResolveInfo();
595    ComponentName mResolveComponentName;
596    PackageParser.Package mPlatformPackage;
597    ComponentName mCustomResolverComponentName;
598
599    boolean mResolverReplaced = false;
600
601    private final ComponentName mIntentFilterVerifierComponent;
602    private int mIntentFilterVerificationToken = 0;
603
604    /** Component that knows whether or not an ephemeral application exists */
605    final ComponentName mEphemeralResolverComponent;
606    /** The service connection to the ephemeral resolver */
607    final EphemeralResolverConnection mEphemeralResolverConnection;
608
609    /** Component used to install ephemeral applications */
610    final ComponentName mEphemeralInstallerComponent;
611    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
612    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
613
614    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
615            = new SparseArray<IntentFilterVerificationState>();
616
617    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
618            new DefaultPermissionGrantPolicy(this);
619
620    // List of packages names to keep cached, even if they are uninstalled for all users
621    private List<String> mKeepUninstalledPackages;
622
623    private static class IFVerificationParams {
624        PackageParser.Package pkg;
625        boolean replacing;
626        int userId;
627        int verifierUid;
628
629        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
630                int _userId, int _verifierUid) {
631            pkg = _pkg;
632            replacing = _replacing;
633            userId = _userId;
634            replacing = _replacing;
635            verifierUid = _verifierUid;
636        }
637    }
638
639    private interface IntentFilterVerifier<T extends IntentFilter> {
640        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
641                                               T filter, String packageName);
642        void startVerifications(int userId);
643        void receiveVerificationResponse(int verificationId);
644    }
645
646    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
647        private Context mContext;
648        private ComponentName mIntentFilterVerifierComponent;
649        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
650
651        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
652            mContext = context;
653            mIntentFilterVerifierComponent = verifierComponent;
654        }
655
656        private String getDefaultScheme() {
657            return IntentFilter.SCHEME_HTTPS;
658        }
659
660        @Override
661        public void startVerifications(int userId) {
662            // Launch verifications requests
663            int count = mCurrentIntentFilterVerifications.size();
664            for (int n=0; n<count; n++) {
665                int verificationId = mCurrentIntentFilterVerifications.get(n);
666                final IntentFilterVerificationState ivs =
667                        mIntentFilterVerificationStates.get(verificationId);
668
669                String packageName = ivs.getPackageName();
670
671                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
672                final int filterCount = filters.size();
673                ArraySet<String> domainsSet = new ArraySet<>();
674                for (int m=0; m<filterCount; m++) {
675                    PackageParser.ActivityIntentInfo filter = filters.get(m);
676                    domainsSet.addAll(filter.getHostsList());
677                }
678                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
679                synchronized (mPackages) {
680                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
681                            packageName, domainsList) != null) {
682                        scheduleWriteSettingsLocked();
683                    }
684                }
685                sendVerificationRequest(userId, verificationId, ivs);
686            }
687            mCurrentIntentFilterVerifications.clear();
688        }
689
690        private void sendVerificationRequest(int userId, int verificationId,
691                IntentFilterVerificationState ivs) {
692
693            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
696                    verificationId);
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
699                    getDefaultScheme());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
702                    ivs.getHostsString());
703            verificationIntent.putExtra(
704                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
705                    ivs.getPackageName());
706            verificationIntent.setComponent(mIntentFilterVerifierComponent);
707            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
708
709            UserHandle user = new UserHandle(userId);
710            mContext.sendBroadcastAsUser(verificationIntent, user);
711            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
712                    "Sending IntentFilter verification broadcast");
713        }
714
715        public void receiveVerificationResponse(int verificationId) {
716            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
717
718            final boolean verified = ivs.isVerified();
719
720            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
721            final int count = filters.size();
722            if (DEBUG_DOMAIN_VERIFICATION) {
723                Slog.i(TAG, "Received verification response " + verificationId
724                        + " for " + count + " filters, verified=" + verified);
725            }
726            for (int n=0; n<count; n++) {
727                PackageParser.ActivityIntentInfo filter = filters.get(n);
728                filter.setVerified(verified);
729
730                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
731                        + " verified with result:" + verified + " and hosts:"
732                        + ivs.getHostsString());
733            }
734
735            mIntentFilterVerificationStates.remove(verificationId);
736
737            final String packageName = ivs.getPackageName();
738            IntentFilterVerificationInfo ivi = null;
739
740            synchronized (mPackages) {
741                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
742            }
743            if (ivi == null) {
744                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
745                        + verificationId + " packageName:" + packageName);
746                return;
747            }
748            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
749                    "Updating IntentFilterVerificationInfo for package " + packageName
750                            +" verificationId:" + verificationId);
751
752            synchronized (mPackages) {
753                if (verified) {
754                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
755                } else {
756                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
757                }
758                scheduleWriteSettingsLocked();
759
760                final int userId = ivs.getUserId();
761                if (userId != UserHandle.USER_ALL) {
762                    final int userStatus =
763                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
764
765                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
766                    boolean needUpdate = false;
767
768                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
769                    // already been set by the User thru the Disambiguation dialog
770                    switch (userStatus) {
771                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
772                            if (verified) {
773                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
774                            } else {
775                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
776                            }
777                            needUpdate = true;
778                            break;
779
780                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
781                            if (verified) {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
783                                needUpdate = true;
784                            }
785                            break;
786
787                        default:
788                            // Nothing to do
789                    }
790
791                    if (needUpdate) {
792                        mSettings.updateIntentFilterVerificationStatusLPw(
793                                packageName, updatedStatus, userId);
794                        scheduleWritePackageRestrictionsLocked(userId);
795                    }
796                }
797            }
798        }
799
800        @Override
801        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
802                    ActivityIntentInfo filter, String packageName) {
803            if (!hasValidDomains(filter)) {
804                return false;
805            }
806            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
807            if (ivs == null) {
808                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
809                        packageName);
810            }
811            if (DEBUG_DOMAIN_VERIFICATION) {
812                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
813            }
814            ivs.addFilter(filter);
815            return true;
816        }
817
818        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
819                int userId, int verificationId, String packageName) {
820            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
821                    verifierUid, userId, packageName);
822            ivs.setPendingState();
823            synchronized (mPackages) {
824                mIntentFilterVerificationStates.append(verificationId, ivs);
825                mCurrentIntentFilterVerifications.add(verificationId);
826            }
827            return ivs;
828        }
829    }
830
831    private static boolean hasValidDomains(ActivityIntentInfo filter) {
832        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
833                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
834                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
835    }
836
837    private IntentFilterVerifier mIntentFilterVerifier;
838
839    // Set of pending broadcasts for aggregating enable/disable of components.
840    static class PendingPackageBroadcasts {
841        // for each user id, a map of <package name -> components within that package>
842        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
843
844        public PendingPackageBroadcasts() {
845            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
846        }
847
848        public ArrayList<String> get(int userId, String packageName) {
849            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
850            return packages.get(packageName);
851        }
852
853        public void put(int userId, String packageName, ArrayList<String> components) {
854            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
855            packages.put(packageName, components);
856        }
857
858        public void remove(int userId, String packageName) {
859            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
860            if (packages != null) {
861                packages.remove(packageName);
862            }
863        }
864
865        public void remove(int userId) {
866            mUidMap.remove(userId);
867        }
868
869        public int userIdCount() {
870            return mUidMap.size();
871        }
872
873        public int userIdAt(int n) {
874            return mUidMap.keyAt(n);
875        }
876
877        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
878            return mUidMap.get(userId);
879        }
880
881        public int size() {
882            // total number of pending broadcast entries across all userIds
883            int num = 0;
884            for (int i = 0; i< mUidMap.size(); i++) {
885                num += mUidMap.valueAt(i).size();
886            }
887            return num;
888        }
889
890        public void clear() {
891            mUidMap.clear();
892        }
893
894        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
895            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
896            if (map == null) {
897                map = new ArrayMap<String, ArrayList<String>>();
898                mUidMap.put(userId, map);
899            }
900            return map;
901        }
902    }
903    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
904
905    // Service Connection to remote media container service to copy
906    // package uri's from external media onto secure containers
907    // or internal storage.
908    private IMediaContainerService mContainerService = null;
909
910    static final int SEND_PENDING_BROADCAST = 1;
911    static final int MCS_BOUND = 3;
912    static final int END_COPY = 4;
913    static final int INIT_COPY = 5;
914    static final int MCS_UNBIND = 6;
915    static final int START_CLEANING_PACKAGE = 7;
916    static final int FIND_INSTALL_LOC = 8;
917    static final int POST_INSTALL = 9;
918    static final int MCS_RECONNECT = 10;
919    static final int MCS_GIVE_UP = 11;
920    static final int UPDATED_MEDIA_STATUS = 12;
921    static final int WRITE_SETTINGS = 13;
922    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
923    static final int PACKAGE_VERIFIED = 15;
924    static final int CHECK_PENDING_VERIFICATION = 16;
925    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
926    static final int INTENT_FILTER_VERIFIED = 18;
927
928    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
929
930    // Delay time in millisecs
931    static final int BROADCAST_DELAY = 10 * 1000;
932
933    static UserManagerService sUserManager;
934
935    // Stores a list of users whose package restrictions file needs to be updated
936    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
937
938    final private DefaultContainerConnection mDefContainerConn =
939            new DefaultContainerConnection();
940    class DefaultContainerConnection implements ServiceConnection {
941        public void onServiceConnected(ComponentName name, IBinder service) {
942            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
943            IMediaContainerService imcs =
944                IMediaContainerService.Stub.asInterface(service);
945            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
946        }
947
948        public void onServiceDisconnected(ComponentName name) {
949            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
950        }
951    }
952
953    // Recordkeeping of restore-after-install operations that are currently in flight
954    // between the Package Manager and the Backup Manager
955    class PostInstallData {
956        public InstallArgs args;
957        public PackageInstalledInfo res;
958
959        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
960            args = _a;
961            res = _r;
962        }
963    }
964
965    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
966    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
967
968    // XML tags for backup/restore of various bits of state
969    private static final String TAG_PREFERRED_BACKUP = "pa";
970    private static final String TAG_DEFAULT_APPS = "da";
971    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
972
973    final String mRequiredVerifierPackage;
974    final String mRequiredInstallerPackage;
975
976    private final PackageUsage mPackageUsage = new PackageUsage();
977
978    private class PackageUsage {
979        private static final int WRITE_INTERVAL
980            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
981
982        private final Object mFileLock = new Object();
983        private final AtomicLong mLastWritten = new AtomicLong(0);
984        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
985
986        private boolean mIsHistoricalPackageUsageAvailable = true;
987
988        boolean isHistoricalPackageUsageAvailable() {
989            return mIsHistoricalPackageUsageAvailable;
990        }
991
992        void write(boolean force) {
993            if (force) {
994                writeInternal();
995                return;
996            }
997            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
998                && !DEBUG_DEXOPT) {
999                return;
1000            }
1001            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1002                new Thread("PackageUsage_DiskWriter") {
1003                    @Override
1004                    public void run() {
1005                        try {
1006                            writeInternal();
1007                        } finally {
1008                            mBackgroundWriteRunning.set(false);
1009                        }
1010                    }
1011                }.start();
1012            }
1013        }
1014
1015        private void writeInternal() {
1016            synchronized (mPackages) {
1017                synchronized (mFileLock) {
1018                    AtomicFile file = getFile();
1019                    FileOutputStream f = null;
1020                    try {
1021                        f = file.startWrite();
1022                        BufferedOutputStream out = new BufferedOutputStream(f);
1023                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1024                        StringBuilder sb = new StringBuilder();
1025                        for (PackageParser.Package pkg : mPackages.values()) {
1026                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1027                                continue;
1028                            }
1029                            sb.setLength(0);
1030                            sb.append(pkg.packageName);
1031                            sb.append(' ');
1032                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1033                            sb.append('\n');
1034                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1035                        }
1036                        out.flush();
1037                        file.finishWrite(f);
1038                    } catch (IOException e) {
1039                        if (f != null) {
1040                            file.failWrite(f);
1041                        }
1042                        Log.e(TAG, "Failed to write package usage times", e);
1043                    }
1044                }
1045            }
1046            mLastWritten.set(SystemClock.elapsedRealtime());
1047        }
1048
1049        void readLP() {
1050            synchronized (mFileLock) {
1051                AtomicFile file = getFile();
1052                BufferedInputStream in = null;
1053                try {
1054                    in = new BufferedInputStream(file.openRead());
1055                    StringBuffer sb = new StringBuffer();
1056                    while (true) {
1057                        String packageName = readToken(in, sb, ' ');
1058                        if (packageName == null) {
1059                            break;
1060                        }
1061                        String timeInMillisString = readToken(in, sb, '\n');
1062                        if (timeInMillisString == null) {
1063                            throw new IOException("Failed to find last usage time for package "
1064                                                  + packageName);
1065                        }
1066                        PackageParser.Package pkg = mPackages.get(packageName);
1067                        if (pkg == null) {
1068                            continue;
1069                        }
1070                        long timeInMillis;
1071                        try {
1072                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1073                        } catch (NumberFormatException e) {
1074                            throw new IOException("Failed to parse " + timeInMillisString
1075                                                  + " as a long.", e);
1076                        }
1077                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1078                    }
1079                } catch (FileNotFoundException expected) {
1080                    mIsHistoricalPackageUsageAvailable = false;
1081                } catch (IOException e) {
1082                    Log.w(TAG, "Failed to read package usage times", e);
1083                } finally {
1084                    IoUtils.closeQuietly(in);
1085                }
1086            }
1087            mLastWritten.set(SystemClock.elapsedRealtime());
1088        }
1089
1090        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1091                throws IOException {
1092            sb.setLength(0);
1093            while (true) {
1094                int ch = in.read();
1095                if (ch == -1) {
1096                    if (sb.length() == 0) {
1097                        return null;
1098                    }
1099                    throw new IOException("Unexpected EOF");
1100                }
1101                if (ch == endOfToken) {
1102                    return sb.toString();
1103                }
1104                sb.append((char)ch);
1105            }
1106        }
1107
1108        private AtomicFile getFile() {
1109            File dataDir = Environment.getDataDirectory();
1110            File systemDir = new File(dataDir, "system");
1111            File fname = new File(systemDir, "package-usage.list");
1112            return new AtomicFile(fname);
1113        }
1114    }
1115
1116    class PackageHandler extends Handler {
1117        private boolean mBound = false;
1118        final ArrayList<HandlerParams> mPendingInstalls =
1119            new ArrayList<HandlerParams>();
1120
1121        private boolean connectToService() {
1122            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1123                    " DefaultContainerService");
1124            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1125            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1126            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1127                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1128                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1129                mBound = true;
1130                return true;
1131            }
1132            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1133            return false;
1134        }
1135
1136        private void disconnectService() {
1137            mContainerService = null;
1138            mBound = false;
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1140            mContext.unbindService(mDefContainerConn);
1141            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142        }
1143
1144        PackageHandler(Looper looper) {
1145            super(looper);
1146        }
1147
1148        public void handleMessage(Message msg) {
1149            try {
1150                doHandleMessage(msg);
1151            } finally {
1152                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1153            }
1154        }
1155
1156        void doHandleMessage(Message msg) {
1157            switch (msg.what) {
1158                case INIT_COPY: {
1159                    HandlerParams params = (HandlerParams) msg.obj;
1160                    int idx = mPendingInstalls.size();
1161                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1162                    // If a bind was already initiated we dont really
1163                    // need to do anything. The pending install
1164                    // will be processed later on.
1165                    if (!mBound) {
1166                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1167                                System.identityHashCode(mHandler));
1168                        // If this is the only one pending we might
1169                        // have to bind to the service again.
1170                        if (!connectToService()) {
1171                            Slog.e(TAG, "Failed to bind to media container service");
1172                            params.serviceError();
1173                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1174                                    System.identityHashCode(mHandler));
1175                            if (params.traceMethod != null) {
1176                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1177                                        params.traceCookie);
1178                            }
1179                            return;
1180                        } else {
1181                            // Once we bind to the service, the first
1182                            // pending request will be processed.
1183                            mPendingInstalls.add(idx, params);
1184                        }
1185                    } else {
1186                        mPendingInstalls.add(idx, params);
1187                        // Already bound to the service. Just make
1188                        // sure we trigger off processing the first request.
1189                        if (idx == 0) {
1190                            mHandler.sendEmptyMessage(MCS_BOUND);
1191                        }
1192                    }
1193                    break;
1194                }
1195                case MCS_BOUND: {
1196                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1197                    if (msg.obj != null) {
1198                        mContainerService = (IMediaContainerService) msg.obj;
1199                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200                                System.identityHashCode(mHandler));
1201                    }
1202                    if (mContainerService == null) {
1203                        if (!mBound) {
1204                            // Something seriously wrong since we are not bound and we are not
1205                            // waiting for connection. Bail out.
1206                            Slog.e(TAG, "Cannot bind to media container service");
1207                            for (HandlerParams params : mPendingInstalls) {
1208                                // Indicate service bind error
1209                                params.serviceError();
1210                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1211                                        System.identityHashCode(params));
1212                                if (params.traceMethod != null) {
1213                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1214                                            params.traceMethod, params.traceCookie);
1215                                }
1216                                return;
1217                            }
1218                            mPendingInstalls.clear();
1219                        } else {
1220                            Slog.w(TAG, "Waiting to connect to media container service");
1221                        }
1222                    } else if (mPendingInstalls.size() > 0) {
1223                        HandlerParams params = mPendingInstalls.get(0);
1224                        if (params != null) {
1225                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1226                                    System.identityHashCode(params));
1227                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1228                            if (params.startCopy()) {
1229                                // We are done...  look for more work or to
1230                                // go idle.
1231                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1232                                        "Checking for more work or unbind...");
1233                                // Delete pending install
1234                                if (mPendingInstalls.size() > 0) {
1235                                    mPendingInstalls.remove(0);
1236                                }
1237                                if (mPendingInstalls.size() == 0) {
1238                                    if (mBound) {
1239                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1240                                                "Posting delayed MCS_UNBIND");
1241                                        removeMessages(MCS_UNBIND);
1242                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1243                                        // Unbind after a little delay, to avoid
1244                                        // continual thrashing.
1245                                        sendMessageDelayed(ubmsg, 10000);
1246                                    }
1247                                } else {
1248                                    // There are more pending requests in queue.
1249                                    // Just post MCS_BOUND message to trigger processing
1250                                    // of next pending install.
1251                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1252                                            "Posting MCS_BOUND for next work");
1253                                    mHandler.sendEmptyMessage(MCS_BOUND);
1254                                }
1255                            }
1256                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1257                        }
1258                    } else {
1259                        // Should never happen ideally.
1260                        Slog.w(TAG, "Empty queue");
1261                    }
1262                    break;
1263                }
1264                case MCS_RECONNECT: {
1265                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1266                    if (mPendingInstalls.size() > 0) {
1267                        if (mBound) {
1268                            disconnectService();
1269                        }
1270                        if (!connectToService()) {
1271                            Slog.e(TAG, "Failed to bind to media container service");
1272                            for (HandlerParams params : mPendingInstalls) {
1273                                // Indicate service bind error
1274                                params.serviceError();
1275                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1276                                        System.identityHashCode(params));
1277                            }
1278                            mPendingInstalls.clear();
1279                        }
1280                    }
1281                    break;
1282                }
1283                case MCS_UNBIND: {
1284                    // If there is no actual work left, then time to unbind.
1285                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1286
1287                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1288                        if (mBound) {
1289                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1290
1291                            disconnectService();
1292                        }
1293                    } else if (mPendingInstalls.size() > 0) {
1294                        // There are more pending requests in queue.
1295                        // Just post MCS_BOUND message to trigger processing
1296                        // of next pending install.
1297                        mHandler.sendEmptyMessage(MCS_BOUND);
1298                    }
1299
1300                    break;
1301                }
1302                case MCS_GIVE_UP: {
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1304                    HandlerParams params = mPendingInstalls.remove(0);
1305                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1306                            System.identityHashCode(params));
1307                    break;
1308                }
1309                case SEND_PENDING_BROADCAST: {
1310                    String packages[];
1311                    ArrayList<String> components[];
1312                    int size = 0;
1313                    int uids[];
1314                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1315                    synchronized (mPackages) {
1316                        if (mPendingBroadcasts == null) {
1317                            return;
1318                        }
1319                        size = mPendingBroadcasts.size();
1320                        if (size <= 0) {
1321                            // Nothing to be done. Just return
1322                            return;
1323                        }
1324                        packages = new String[size];
1325                        components = new ArrayList[size];
1326                        uids = new int[size];
1327                        int i = 0;  // filling out the above arrays
1328
1329                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1330                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1331                            Iterator<Map.Entry<String, ArrayList<String>>> it
1332                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1333                                            .entrySet().iterator();
1334                            while (it.hasNext() && i < size) {
1335                                Map.Entry<String, ArrayList<String>> ent = it.next();
1336                                packages[i] = ent.getKey();
1337                                components[i] = ent.getValue();
1338                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1339                                uids[i] = (ps != null)
1340                                        ? UserHandle.getUid(packageUserId, ps.appId)
1341                                        : -1;
1342                                i++;
1343                            }
1344                        }
1345                        size = i;
1346                        mPendingBroadcasts.clear();
1347                    }
1348                    // Send broadcasts
1349                    for (int i = 0; i < size; i++) {
1350                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1351                    }
1352                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1353                    break;
1354                }
1355                case START_CLEANING_PACKAGE: {
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1357                    final String packageName = (String)msg.obj;
1358                    final int userId = msg.arg1;
1359                    final boolean andCode = msg.arg2 != 0;
1360                    synchronized (mPackages) {
1361                        if (userId == UserHandle.USER_ALL) {
1362                            int[] users = sUserManager.getUserIds();
1363                            for (int user : users) {
1364                                mSettings.addPackageToCleanLPw(
1365                                        new PackageCleanItem(user, packageName, andCode));
1366                            }
1367                        } else {
1368                            mSettings.addPackageToCleanLPw(
1369                                    new PackageCleanItem(userId, packageName, andCode));
1370                        }
1371                    }
1372                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1373                    startCleaningPackages();
1374                } break;
1375                case POST_INSTALL: {
1376                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1377                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1378                    mRunningInstalls.delete(msg.arg1);
1379                    boolean deleteOld = false;
1380
1381                    if (data != null) {
1382                        InstallArgs args = data.args;
1383                        PackageInstalledInfo res = data.res;
1384
1385                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1386                            final String packageName = res.pkg.applicationInfo.packageName;
1387                            res.removedInfo.sendBroadcast(false, true, false);
1388                            Bundle extras = new Bundle(1);
1389                            extras.putInt(Intent.EXTRA_UID, res.uid);
1390
1391                            // Now that we successfully installed the package, grant runtime
1392                            // permissions if requested before broadcasting the install.
1393                            if ((args.installFlags
1394                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1395                                    && res.pkg.applicationInfo.targetSdkVersion
1396                                            >= Build.VERSION_CODES.M) {
1397                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1398                                        args.installGrantPermissions);
1399                            }
1400
1401                            // Determine the set of users who are adding this
1402                            // package for the first time vs. those who are seeing
1403                            // an update.
1404                            int[] firstUsers;
1405                            int[] updateUsers = new int[0];
1406                            if (res.origUsers == null || res.origUsers.length == 0) {
1407                                firstUsers = res.newUsers;
1408                            } else {
1409                                firstUsers = new int[0];
1410                                for (int i=0; i<res.newUsers.length; i++) {
1411                                    int user = res.newUsers[i];
1412                                    boolean isNew = true;
1413                                    for (int j=0; j<res.origUsers.length; j++) {
1414                                        if (res.origUsers[j] == user) {
1415                                            isNew = false;
1416                                            break;
1417                                        }
1418                                    }
1419                                    if (isNew) {
1420                                        int[] newFirst = new int[firstUsers.length+1];
1421                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1422                                                firstUsers.length);
1423                                        newFirst[firstUsers.length] = user;
1424                                        firstUsers = newFirst;
1425                                    } else {
1426                                        int[] newUpdate = new int[updateUsers.length+1];
1427                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1428                                                updateUsers.length);
1429                                        newUpdate[updateUsers.length] = user;
1430                                        updateUsers = newUpdate;
1431                                    }
1432                                }
1433                            }
1434                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1435                                    packageName, extras, 0, null, null, firstUsers);
1436                            final boolean update = res.removedInfo.removedPackage != null;
1437                            if (update) {
1438                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1439                            }
1440                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1441                                    packageName, extras, 0, null, null, updateUsers);
1442                            if (update) {
1443                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1444                                        packageName, extras, 0, null, null, updateUsers);
1445                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1446                                        null, null, 0, packageName, null, updateUsers);
1447
1448                                // treat asec-hosted packages like removable media on upgrade
1449                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1450                                    if (DEBUG_INSTALL) {
1451                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1452                                                + " is ASEC-hosted -> AVAILABLE");
1453                                    }
1454                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1455                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1456                                    pkgList.add(packageName);
1457                                    sendResourcesChangedBroadcast(true, true,
1458                                            pkgList,uidArray, null);
1459                                }
1460                            }
1461                            if (res.removedInfo.args != null) {
1462                                // Remove the replaced package's older resources safely now
1463                                deleteOld = true;
1464                            }
1465
1466                            // If this app is a browser and it's newly-installed for some
1467                            // users, clear any default-browser state in those users
1468                            if (firstUsers.length > 0) {
1469                                // the app's nature doesn't depend on the user, so we can just
1470                                // check its browser nature in any user and generalize.
1471                                if (packageIsBrowser(packageName, firstUsers[0])) {
1472                                    synchronized (mPackages) {
1473                                        for (int userId : firstUsers) {
1474                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1475                                        }
1476                                    }
1477                                }
1478                            }
1479                            // Log current value of "unknown sources" setting
1480                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1481                                getUnknownSourcesSettings());
1482                        }
1483                        // Force a gc to clear up things
1484                        Runtime.getRuntime().gc();
1485                        // We delete after a gc for applications  on sdcard.
1486                        if (deleteOld) {
1487                            synchronized (mInstallLock) {
1488                                res.removedInfo.args.doPostDeleteLI(true);
1489                            }
1490                        }
1491                        if (args.observer != null) {
1492                            try {
1493                                Bundle extras = extrasForInstallResult(res);
1494                                args.observer.onPackageInstalled(res.name, res.returnCode,
1495                                        res.returnMsg, extras);
1496                            } catch (RemoteException e) {
1497                                Slog.i(TAG, "Observer no longer exists.");
1498                            }
1499                        }
1500                        if (args.traceMethod != null) {
1501                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1502                                    args.traceCookie);
1503                        }
1504                        return;
1505                    } else {
1506                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1507                    }
1508
1509                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1510                } break;
1511                case UPDATED_MEDIA_STATUS: {
1512                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1513                    boolean reportStatus = msg.arg1 == 1;
1514                    boolean doGc = msg.arg2 == 1;
1515                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1516                    if (doGc) {
1517                        // Force a gc to clear up stale containers.
1518                        Runtime.getRuntime().gc();
1519                    }
1520                    if (msg.obj != null) {
1521                        @SuppressWarnings("unchecked")
1522                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1523                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1524                        // Unload containers
1525                        unloadAllContainers(args);
1526                    }
1527                    if (reportStatus) {
1528                        try {
1529                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1530                            PackageHelper.getMountService().finishMediaUpdate();
1531                        } catch (RemoteException e) {
1532                            Log.e(TAG, "MountService not running?");
1533                        }
1534                    }
1535                } break;
1536                case WRITE_SETTINGS: {
1537                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1538                    synchronized (mPackages) {
1539                        removeMessages(WRITE_SETTINGS);
1540                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1541                        mSettings.writeLPr();
1542                        mDirtyUsers.clear();
1543                    }
1544                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1545                } break;
1546                case WRITE_PACKAGE_RESTRICTIONS: {
1547                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1548                    synchronized (mPackages) {
1549                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1550                        for (int userId : mDirtyUsers) {
1551                            mSettings.writePackageRestrictionsLPr(userId);
1552                        }
1553                        mDirtyUsers.clear();
1554                    }
1555                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1556                } break;
1557                case CHECK_PENDING_VERIFICATION: {
1558                    final int verificationId = msg.arg1;
1559                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1560
1561                    if ((state != null) && !state.timeoutExtended()) {
1562                        final InstallArgs args = state.getInstallArgs();
1563                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1564
1565                        Slog.i(TAG, "Verification timed out for " + originUri);
1566                        mPendingVerification.remove(verificationId);
1567
1568                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1569
1570                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1571                            Slog.i(TAG, "Continuing with installation of " + originUri);
1572                            state.setVerifierResponse(Binder.getCallingUid(),
1573                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1574                            broadcastPackageVerified(verificationId, originUri,
1575                                    PackageManager.VERIFICATION_ALLOW,
1576                                    state.getInstallArgs().getUser());
1577                            try {
1578                                ret = args.copyApk(mContainerService, true);
1579                            } catch (RemoteException e) {
1580                                Slog.e(TAG, "Could not contact the ContainerService");
1581                            }
1582                        } else {
1583                            broadcastPackageVerified(verificationId, originUri,
1584                                    PackageManager.VERIFICATION_REJECT,
1585                                    state.getInstallArgs().getUser());
1586                        }
1587
1588                        Trace.asyncTraceEnd(
1589                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1590
1591                        processPendingInstall(args, ret);
1592                        mHandler.sendEmptyMessage(MCS_UNBIND);
1593                    }
1594                    break;
1595                }
1596                case PACKAGE_VERIFIED: {
1597                    final int verificationId = msg.arg1;
1598
1599                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1600                    if (state == null) {
1601                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1602                        break;
1603                    }
1604
1605                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1606
1607                    state.setVerifierResponse(response.callerUid, response.code);
1608
1609                    if (state.isVerificationComplete()) {
1610                        mPendingVerification.remove(verificationId);
1611
1612                        final InstallArgs args = state.getInstallArgs();
1613                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1614
1615                        int ret;
1616                        if (state.isInstallAllowed()) {
1617                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1618                            broadcastPackageVerified(verificationId, originUri,
1619                                    response.code, state.getInstallArgs().getUser());
1620                            try {
1621                                ret = args.copyApk(mContainerService, true);
1622                            } catch (RemoteException e) {
1623                                Slog.e(TAG, "Could not contact the ContainerService");
1624                            }
1625                        } else {
1626                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1627                        }
1628
1629                        Trace.asyncTraceEnd(
1630                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1631
1632                        processPendingInstall(args, ret);
1633                        mHandler.sendEmptyMessage(MCS_UNBIND);
1634                    }
1635
1636                    break;
1637                }
1638                case START_INTENT_FILTER_VERIFICATIONS: {
1639                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1640                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1641                            params.replacing, params.pkg);
1642                    break;
1643                }
1644                case INTENT_FILTER_VERIFIED: {
1645                    final int verificationId = msg.arg1;
1646
1647                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1648                            verificationId);
1649                    if (state == null) {
1650                        Slog.w(TAG, "Invalid IntentFilter verification token "
1651                                + verificationId + " received");
1652                        break;
1653                    }
1654
1655                    final int userId = state.getUserId();
1656
1657                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1658                            "Processing IntentFilter verification with token:"
1659                            + verificationId + " and userId:" + userId);
1660
1661                    final IntentFilterVerificationResponse response =
1662                            (IntentFilterVerificationResponse) msg.obj;
1663
1664                    state.setVerifierResponse(response.callerUid, response.code);
1665
1666                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1667                            "IntentFilter verification with token:" + verificationId
1668                            + " and userId:" + userId
1669                            + " is settings verifier response with response code:"
1670                            + response.code);
1671
1672                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1673                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1674                                + response.getFailedDomainsString());
1675                    }
1676
1677                    if (state.isVerificationComplete()) {
1678                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1679                    } else {
1680                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1681                                "IntentFilter verification with token:" + verificationId
1682                                + " was not said to be complete");
1683                    }
1684
1685                    break;
1686                }
1687            }
1688        }
1689    }
1690
1691    private StorageEventListener mStorageListener = new StorageEventListener() {
1692        @Override
1693        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1694            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1695                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1696                    final String volumeUuid = vol.getFsUuid();
1697
1698                    // Clean up any users or apps that were removed or recreated
1699                    // while this volume was missing
1700                    reconcileUsers(volumeUuid);
1701                    reconcileApps(volumeUuid);
1702
1703                    // Clean up any install sessions that expired or were
1704                    // cancelled while this volume was missing
1705                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1706
1707                    loadPrivatePackages(vol);
1708
1709                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1710                    unloadPrivatePackages(vol);
1711                }
1712            }
1713
1714            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1715                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1716                    updateExternalMediaStatus(true, false);
1717                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1718                    updateExternalMediaStatus(false, false);
1719                }
1720            }
1721        }
1722
1723        @Override
1724        public void onVolumeForgotten(String fsUuid) {
1725            if (TextUtils.isEmpty(fsUuid)) {
1726                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1727                return;
1728            }
1729
1730            // Remove any apps installed on the forgotten volume
1731            synchronized (mPackages) {
1732                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1733                for (PackageSetting ps : packages) {
1734                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1735                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1736                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1737                }
1738
1739                mSettings.onVolumeForgotten(fsUuid);
1740                mSettings.writeLPr();
1741            }
1742        }
1743    };
1744
1745    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1746            String[] grantedPermissions) {
1747        if (userId >= UserHandle.USER_SYSTEM) {
1748            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1749        } else if (userId == UserHandle.USER_ALL) {
1750            final int[] userIds;
1751            synchronized (mPackages) {
1752                userIds = UserManagerService.getInstance().getUserIds();
1753            }
1754            for (int someUserId : userIds) {
1755                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1756            }
1757        }
1758
1759        // We could have touched GID membership, so flush out packages.list
1760        synchronized (mPackages) {
1761            mSettings.writePackageListLPr();
1762        }
1763    }
1764
1765    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1766            String[] grantedPermissions) {
1767        SettingBase sb = (SettingBase) pkg.mExtras;
1768        if (sb == null) {
1769            return;
1770        }
1771
1772        PermissionsState permissionsState = sb.getPermissionsState();
1773
1774        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1775                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1776
1777        synchronized (mPackages) {
1778            for (String permission : pkg.requestedPermissions) {
1779                BasePermission bp = mSettings.mPermissions.get(permission);
1780                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1781                        && (grantedPermissions == null
1782                               || ArrayUtils.contains(grantedPermissions, permission))) {
1783                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1784                    // Installer cannot change immutable permissions.
1785                    if ((flags & immutableFlags) == 0) {
1786                        grantRuntimePermission(pkg.packageName, permission, userId);
1787                    }
1788                }
1789            }
1790        }
1791    }
1792
1793    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1794        Bundle extras = null;
1795        switch (res.returnCode) {
1796            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1797                extras = new Bundle();
1798                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1799                        res.origPermission);
1800                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1801                        res.origPackage);
1802                break;
1803            }
1804            case PackageManager.INSTALL_SUCCEEDED: {
1805                extras = new Bundle();
1806                extras.putBoolean(Intent.EXTRA_REPLACING,
1807                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1808                break;
1809            }
1810        }
1811        return extras;
1812    }
1813
1814    void scheduleWriteSettingsLocked() {
1815        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1816            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1817        }
1818    }
1819
1820    void scheduleWritePackageRestrictionsLocked(int userId) {
1821        if (!sUserManager.exists(userId)) return;
1822        mDirtyUsers.add(userId);
1823        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1824            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1825        }
1826    }
1827
1828    public static PackageManagerService main(Context context, Installer installer,
1829            boolean factoryTest, boolean onlyCore) {
1830        PackageManagerService m = new PackageManagerService(context, installer,
1831                factoryTest, onlyCore);
1832        m.enableSystemUserApps();
1833        ServiceManager.addService("package", m);
1834        return m;
1835    }
1836
1837    private void enableSystemUserApps() {
1838        if (!UserManager.isSplitSystemUser()) {
1839            return;
1840        }
1841        // For system user, enable apps based on the following conditions:
1842        // - app is whitelisted or belong to one of these groups:
1843        //   -- system app which has no launcher icons
1844        //   -- system app which has INTERACT_ACROSS_USERS permission
1845        //   -- system IME app
1846        // - app is not in the blacklist
1847        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1848        Set<String> enableApps = new ArraySet<>();
1849        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1850                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1851                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1852        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1853        enableApps.addAll(wlApps);
1854        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1855        enableApps.removeAll(blApps);
1856
1857        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1858                UserHandle.SYSTEM);
1859        final int systemAppsSize = systemApps.size();
1860        synchronized (mPackages) {
1861            for (int i = 0; i < systemAppsSize; i++) {
1862                String pName = systemApps.get(i);
1863                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1864                // Should not happen, but we shouldn't be failing if it does
1865                if (pkgSetting == null) {
1866                    continue;
1867                }
1868                boolean installed = enableApps.contains(pName);
1869                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1870            }
1871        }
1872    }
1873
1874    static String[] splitString(String str, char sep) {
1875        int count = 1;
1876        int i = 0;
1877        while ((i=str.indexOf(sep, i)) >= 0) {
1878            count++;
1879            i++;
1880        }
1881
1882        String[] res = new String[count];
1883        i=0;
1884        count = 0;
1885        int lastI=0;
1886        while ((i=str.indexOf(sep, i)) >= 0) {
1887            res[count] = str.substring(lastI, i);
1888            count++;
1889            i++;
1890            lastI = i;
1891        }
1892        res[count] = str.substring(lastI, str.length());
1893        return res;
1894    }
1895
1896    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1897        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1898                Context.DISPLAY_SERVICE);
1899        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1900    }
1901
1902    public PackageManagerService(Context context, Installer installer,
1903            boolean factoryTest, boolean onlyCore) {
1904        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1905                SystemClock.uptimeMillis());
1906
1907        if (mSdkVersion <= 0) {
1908            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1909        }
1910
1911        mContext = context;
1912        mFactoryTest = factoryTest;
1913        mOnlyCore = onlyCore;
1914        mMetrics = new DisplayMetrics();
1915        mSettings = new Settings(mPackages);
1916        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1917                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1918        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1919                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1920        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1921                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1922        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1923                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1924        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928
1929        String separateProcesses = SystemProperties.get("debug.separate_processes");
1930        if (separateProcesses != null && separateProcesses.length() > 0) {
1931            if ("*".equals(separateProcesses)) {
1932                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1933                mSeparateProcesses = null;
1934                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1935            } else {
1936                mDefParseFlags = 0;
1937                mSeparateProcesses = separateProcesses.split(",");
1938                Slog.w(TAG, "Running with debug.separate_processes: "
1939                        + separateProcesses);
1940            }
1941        } else {
1942            mDefParseFlags = 0;
1943            mSeparateProcesses = null;
1944        }
1945
1946        mInstaller = installer;
1947        mPackageDexOptimizer = new PackageDexOptimizer(this);
1948        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1949
1950        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1951                FgThread.get().getLooper());
1952
1953        getDefaultDisplayMetrics(context, mMetrics);
1954
1955        SystemConfig systemConfig = SystemConfig.getInstance();
1956        mGlobalGids = systemConfig.getGlobalGids();
1957        mSystemPermissions = systemConfig.getSystemPermissions();
1958        mAvailableFeatures = systemConfig.getAvailableFeatures();
1959
1960        synchronized (mInstallLock) {
1961        // writer
1962        synchronized (mPackages) {
1963            mHandlerThread = new ServiceThread(TAG,
1964                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1965            mHandlerThread.start();
1966            mHandler = new PackageHandler(mHandlerThread.getLooper());
1967            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1968
1969            File dataDir = Environment.getDataDirectory();
1970            mAppDataDir = new File(dataDir, "data");
1971            mAppInstallDir = new File(dataDir, "app");
1972            mAppLib32InstallDir = new File(dataDir, "app-lib");
1973            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1974            mUserAppDataDir = new File(dataDir, "user");
1975            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1976
1977            sUserManager = new UserManagerService(context, this, mPackages);
1978
1979            // Propagate permission configuration in to package manager.
1980            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1981                    = systemConfig.getPermissions();
1982            for (int i=0; i<permConfig.size(); i++) {
1983                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1984                BasePermission bp = mSettings.mPermissions.get(perm.name);
1985                if (bp == null) {
1986                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1987                    mSettings.mPermissions.put(perm.name, bp);
1988                }
1989                if (perm.gids != null) {
1990                    bp.setGids(perm.gids, perm.perUser);
1991                }
1992            }
1993
1994            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1995            for (int i=0; i<libConfig.size(); i++) {
1996                mSharedLibraries.put(libConfig.keyAt(i),
1997                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1998            }
1999
2000            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2001
2002            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2003
2004            String customResolverActivity = Resources.getSystem().getString(
2005                    R.string.config_customResolverActivity);
2006            if (TextUtils.isEmpty(customResolverActivity)) {
2007                customResolverActivity = null;
2008            } else {
2009                mCustomResolverComponentName = ComponentName.unflattenFromString(
2010                        customResolverActivity);
2011            }
2012
2013            long startTime = SystemClock.uptimeMillis();
2014
2015            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2016                    startTime);
2017
2018            // Set flag to monitor and not change apk file paths when
2019            // scanning install directories.
2020            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2021
2022            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2023            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2024
2025            if (bootClassPath == null) {
2026                Slog.w(TAG, "No BOOTCLASSPATH found!");
2027            }
2028
2029            if (systemServerClassPath == null) {
2030                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2031            }
2032
2033            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2034            final String[] dexCodeInstructionSets =
2035                    getDexCodeInstructionSets(
2036                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2037
2038            /**
2039             * Ensure all external libraries have had dexopt run on them.
2040             */
2041            if (mSharedLibraries.size() > 0) {
2042                // NOTE: For now, we're compiling these system "shared libraries"
2043                // (and framework jars) into all available architectures. It's possible
2044                // to compile them only when we come across an app that uses them (there's
2045                // already logic for that in scanPackageLI) but that adds some complexity.
2046                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2047                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2048                        final String lib = libEntry.path;
2049                        if (lib == null) {
2050                            continue;
2051                        }
2052
2053                        try {
2054                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2055                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2056                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2057                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2058                            }
2059                        } catch (FileNotFoundException e) {
2060                            Slog.w(TAG, "Library not found: " + lib);
2061                        } catch (IOException e) {
2062                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2063                                    + e.getMessage());
2064                        }
2065                    }
2066                }
2067            }
2068
2069            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2070
2071            final VersionInfo ver = mSettings.getInternalVersion();
2072            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2073            // when upgrading from pre-M, promote system app permissions from install to runtime
2074            mPromoteSystemApps =
2075                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2076
2077            // save off the names of pre-existing system packages prior to scanning; we don't
2078            // want to automatically grant runtime permissions for new system apps
2079            if (mPromoteSystemApps) {
2080                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2081                while (pkgSettingIter.hasNext()) {
2082                    PackageSetting ps = pkgSettingIter.next();
2083                    if (isSystemApp(ps)) {
2084                        mExistingSystemPackages.add(ps.name);
2085                    }
2086                }
2087            }
2088
2089            // Collect vendor overlay packages.
2090            // (Do this before scanning any apps.)
2091            // For security and version matching reason, only consider
2092            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2093            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2094            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2095                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2096
2097            // Find base frameworks (resource packages without code).
2098            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2099                    | PackageParser.PARSE_IS_SYSTEM_DIR
2100                    | PackageParser.PARSE_IS_PRIVILEGED,
2101                    scanFlags | SCAN_NO_DEX, 0);
2102
2103            // Collected privileged system packages.
2104            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2105            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2106                    | PackageParser.PARSE_IS_SYSTEM_DIR
2107                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2108
2109            // Collect ordinary system packages.
2110            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2111            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2112                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2113
2114            // Collect all vendor packages.
2115            File vendorAppDir = new File("/vendor/app");
2116            try {
2117                vendorAppDir = vendorAppDir.getCanonicalFile();
2118            } catch (IOException e) {
2119                // failed to look up canonical path, continue with original one
2120            }
2121            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2122                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2123
2124            // Collect all OEM packages.
2125            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2126            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2127                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2128
2129            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2130            mInstaller.moveFiles();
2131
2132            // Prune any system packages that no longer exist.
2133            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2134            if (!mOnlyCore) {
2135                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2136                while (psit.hasNext()) {
2137                    PackageSetting ps = psit.next();
2138
2139                    /*
2140                     * If this is not a system app, it can't be a
2141                     * disable system app.
2142                     */
2143                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2144                        continue;
2145                    }
2146
2147                    /*
2148                     * If the package is scanned, it's not erased.
2149                     */
2150                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2151                    if (scannedPkg != null) {
2152                        /*
2153                         * If the system app is both scanned and in the
2154                         * disabled packages list, then it must have been
2155                         * added via OTA. Remove it from the currently
2156                         * scanned package so the previously user-installed
2157                         * application can be scanned.
2158                         */
2159                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2160                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2161                                    + ps.name + "; removing system app.  Last known codePath="
2162                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2163                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2164                                    + scannedPkg.mVersionCode);
2165                            removePackageLI(ps, true);
2166                            mExpectingBetter.put(ps.name, ps.codePath);
2167                        }
2168
2169                        continue;
2170                    }
2171
2172                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2173                        psit.remove();
2174                        logCriticalInfo(Log.WARN, "System package " + ps.name
2175                                + " no longer exists; wiping its data");
2176                        removeDataDirsLI(null, ps.name);
2177                    } else {
2178                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2179                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2180                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2181                        }
2182                    }
2183                }
2184            }
2185
2186            //look for any incomplete package installations
2187            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2188            //clean up list
2189            for(int i = 0; i < deletePkgsList.size(); i++) {
2190                //clean up here
2191                cleanupInstallFailedPackage(deletePkgsList.get(i));
2192            }
2193            //delete tmp files
2194            deleteTempPackageFiles();
2195
2196            // Remove any shared userIDs that have no associated packages
2197            mSettings.pruneSharedUsersLPw();
2198
2199            if (!mOnlyCore) {
2200                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2201                        SystemClock.uptimeMillis());
2202                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2203
2204                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2205                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2206
2207                /**
2208                 * Remove disable package settings for any updated system
2209                 * apps that were removed via an OTA. If they're not a
2210                 * previously-updated app, remove them completely.
2211                 * Otherwise, just revoke their system-level permissions.
2212                 */
2213                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2214                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2215                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2216
2217                    String msg;
2218                    if (deletedPkg == null) {
2219                        msg = "Updated system package " + deletedAppName
2220                                + " no longer exists; wiping its data";
2221                        removeDataDirsLI(null, deletedAppName);
2222                    } else {
2223                        msg = "Updated system app + " + deletedAppName
2224                                + " no longer present; removing system privileges for "
2225                                + deletedAppName;
2226
2227                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2228
2229                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2230                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2231                    }
2232                    logCriticalInfo(Log.WARN, msg);
2233                }
2234
2235                /**
2236                 * Make sure all system apps that we expected to appear on
2237                 * the userdata partition actually showed up. If they never
2238                 * appeared, crawl back and revive the system version.
2239                 */
2240                for (int i = 0; i < mExpectingBetter.size(); i++) {
2241                    final String packageName = mExpectingBetter.keyAt(i);
2242                    if (!mPackages.containsKey(packageName)) {
2243                        final File scanFile = mExpectingBetter.valueAt(i);
2244
2245                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2246                                + " but never showed up; reverting to system");
2247
2248                        final int reparseFlags;
2249                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2250                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2251                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2252                                    | PackageParser.PARSE_IS_PRIVILEGED;
2253                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2254                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2255                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2256                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2257                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2258                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2259                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2260                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2261                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2262                        } else {
2263                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2264                            continue;
2265                        }
2266
2267                        mSettings.enableSystemPackageLPw(packageName);
2268
2269                        try {
2270                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2271                        } catch (PackageManagerException e) {
2272                            Slog.e(TAG, "Failed to parse original system package: "
2273                                    + e.getMessage());
2274                        }
2275                    }
2276                }
2277            }
2278            mExpectingBetter.clear();
2279
2280            // Now that we know all of the shared libraries, update all clients to have
2281            // the correct library paths.
2282            updateAllSharedLibrariesLPw();
2283
2284            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2285                // NOTE: We ignore potential failures here during a system scan (like
2286                // the rest of the commands above) because there's precious little we
2287                // can do about it. A settings error is reported, though.
2288                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2289                        false /* boot complete */);
2290            }
2291
2292            // Now that we know all the packages we are keeping,
2293            // read and update their last usage times.
2294            mPackageUsage.readLP();
2295
2296            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2297                    SystemClock.uptimeMillis());
2298            Slog.i(TAG, "Time to scan packages: "
2299                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2300                    + " seconds");
2301
2302            // If the platform SDK has changed since the last time we booted,
2303            // we need to re-grant app permission to catch any new ones that
2304            // appear.  This is really a hack, and means that apps can in some
2305            // cases get permissions that the user didn't initially explicitly
2306            // allow...  it would be nice to have some better way to handle
2307            // this situation.
2308            int updateFlags = UPDATE_PERMISSIONS_ALL;
2309            if (ver.sdkVersion != mSdkVersion) {
2310                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2311                        + mSdkVersion + "; regranting permissions for internal storage");
2312                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2313            }
2314            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2315            ver.sdkVersion = mSdkVersion;
2316
2317            // If this is the first boot or an update from pre-M, and it is a normal
2318            // boot, then we need to initialize the default preferred apps across
2319            // all defined users.
2320            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2321                for (UserInfo user : sUserManager.getUsers(true)) {
2322                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2323                    applyFactoryDefaultBrowserLPw(user.id);
2324                    primeDomainVerificationsLPw(user.id);
2325                }
2326            }
2327
2328            // If this is first boot after an OTA, and a normal boot, then
2329            // we need to clear code cache directories.
2330            if (mIsUpgrade && !onlyCore) {
2331                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2332                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2333                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2334                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2335                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2336                    }
2337                }
2338                ver.fingerprint = Build.FINGERPRINT;
2339            }
2340
2341            checkDefaultBrowser();
2342
2343            // clear only after permissions and other defaults have been updated
2344            mExistingSystemPackages.clear();
2345            mPromoteSystemApps = false;
2346
2347            // All the changes are done during package scanning.
2348            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2349
2350            // can downgrade to reader
2351            mSettings.writeLPr();
2352
2353            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2354                    SystemClock.uptimeMillis());
2355
2356            mRequiredVerifierPackage = getRequiredVerifierLPr();
2357            mRequiredInstallerPackage = getRequiredInstallerLPr();
2358
2359            mInstallerService = new PackageInstallerService(context, this);
2360
2361            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2362            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2363                    mIntentFilterVerifierComponent);
2364
2365            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2366            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2367            // both the installer and resolver must be present to enable ephemeral
2368            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2369                if (DEBUG_EPHEMERAL) {
2370                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2371                            + " installer:" + ephemeralInstallerComponent);
2372                }
2373                mEphemeralResolverComponent = ephemeralResolverComponent;
2374                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2375                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2376                mEphemeralResolverConnection =
2377                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2378            } else {
2379                if (DEBUG_EPHEMERAL) {
2380                    final String missingComponent =
2381                            (ephemeralResolverComponent == null)
2382                            ? (ephemeralInstallerComponent == null)
2383                                    ? "resolver and installer"
2384                                    : "resolver"
2385                            : "installer";
2386                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2387                }
2388                mEphemeralResolverComponent = null;
2389                mEphemeralInstallerComponent = null;
2390                mEphemeralResolverConnection = null;
2391            }
2392        } // synchronized (mPackages)
2393        } // synchronized (mInstallLock)
2394
2395        // Now after opening every single application zip, make sure they
2396        // are all flushed.  Not really needed, but keeps things nice and
2397        // tidy.
2398        Runtime.getRuntime().gc();
2399
2400        // The initial scanning above does many calls into installd while
2401        // holding the mPackages lock, but we're mostly interested in yelling
2402        // once we have a booted system.
2403        mInstaller.setWarnIfHeld(mPackages);
2404
2405        // Expose private service for system components to use.
2406        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2407    }
2408
2409    @Override
2410    public boolean isFirstBoot() {
2411        return !mRestoredSettings;
2412    }
2413
2414    @Override
2415    public boolean isOnlyCoreApps() {
2416        return mOnlyCore;
2417    }
2418
2419    @Override
2420    public boolean isUpgrade() {
2421        return mIsUpgrade;
2422    }
2423
2424    private String getRequiredVerifierLPr() {
2425        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2426        // We only care about verifier that's installed under system user.
2427        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2428                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2429
2430        String requiredVerifier = null;
2431
2432        final int N = receivers.size();
2433        for (int i = 0; i < N; i++) {
2434            final ResolveInfo info = receivers.get(i);
2435
2436            if (info.activityInfo == null) {
2437                continue;
2438            }
2439
2440            final String packageName = info.activityInfo.packageName;
2441
2442            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2443                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2444                continue;
2445            }
2446
2447            if (requiredVerifier != null) {
2448                throw new RuntimeException("There can be only one required verifier");
2449            }
2450
2451            requiredVerifier = packageName;
2452        }
2453
2454        return requiredVerifier;
2455    }
2456
2457    private String getRequiredInstallerLPr() {
2458        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2459        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2460        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2461
2462        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2463                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2464
2465        String requiredInstaller = null;
2466
2467        final int N = installers.size();
2468        for (int i = 0; i < N; i++) {
2469            final ResolveInfo info = installers.get(i);
2470            final String packageName = info.activityInfo.packageName;
2471
2472            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2473                continue;
2474            }
2475
2476            if (requiredInstaller != null) {
2477                throw new RuntimeException("There must be one required installer");
2478            }
2479
2480            requiredInstaller = packageName;
2481        }
2482
2483        if (requiredInstaller == null) {
2484            throw new RuntimeException("There must be one required installer");
2485        }
2486
2487        return requiredInstaller;
2488    }
2489
2490    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2491        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2492        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2493                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2494
2495        ComponentName verifierComponentName = null;
2496
2497        int priority = -1000;
2498        final int N = receivers.size();
2499        for (int i = 0; i < N; i++) {
2500            final ResolveInfo info = receivers.get(i);
2501
2502            if (info.activityInfo == null) {
2503                continue;
2504            }
2505
2506            final String packageName = info.activityInfo.packageName;
2507
2508            final PackageSetting ps = mSettings.mPackages.get(packageName);
2509            if (ps == null) {
2510                continue;
2511            }
2512
2513            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2514                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2515                continue;
2516            }
2517
2518            // Select the IntentFilterVerifier with the highest priority
2519            if (priority < info.priority) {
2520                priority = info.priority;
2521                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2522                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2523                        + verifierComponentName + " with priority: " + info.priority);
2524            }
2525        }
2526
2527        return verifierComponentName;
2528    }
2529
2530    private ComponentName getEphemeralResolverLPr() {
2531        final String[] packageArray =
2532                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2533        if (packageArray.length == 0) {
2534            if (DEBUG_EPHEMERAL) {
2535                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2536            }
2537            return null;
2538        }
2539
2540        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2541        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2542                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2543
2544        final int N = resolvers.size();
2545        if (N == 0) {
2546            if (DEBUG_EPHEMERAL) {
2547                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2548            }
2549            return null;
2550        }
2551
2552        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2553        for (int i = 0; i < N; i++) {
2554            final ResolveInfo info = resolvers.get(i);
2555
2556            if (info.serviceInfo == null) {
2557                continue;
2558            }
2559
2560            final String packageName = info.serviceInfo.packageName;
2561            if (!possiblePackages.contains(packageName)) {
2562                if (DEBUG_EPHEMERAL) {
2563                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2564                            + " pkg: " + packageName + ", info:" + info);
2565                }
2566                continue;
2567            }
2568
2569            if (DEBUG_EPHEMERAL) {
2570                Slog.v(TAG, "Ephemeral resolver found;"
2571                        + " pkg: " + packageName + ", info:" + info);
2572            }
2573            return new ComponentName(packageName, info.serviceInfo.name);
2574        }
2575        if (DEBUG_EPHEMERAL) {
2576            Slog.v(TAG, "Ephemeral resolver NOT found");
2577        }
2578        return null;
2579    }
2580
2581    private ComponentName getEphemeralInstallerLPr() {
2582        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2583        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2584        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2585        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2586                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2587
2588        ComponentName ephemeralInstaller = null;
2589
2590        final int N = installers.size();
2591        for (int i = 0; i < N; i++) {
2592            final ResolveInfo info = installers.get(i);
2593            final String packageName = info.activityInfo.packageName;
2594
2595            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2596                if (DEBUG_EPHEMERAL) {
2597                    Slog.d(TAG, "Ephemeral installer is not system app;"
2598                            + " pkg: " + packageName + ", info:" + info);
2599                }
2600                continue;
2601            }
2602
2603            if (ephemeralInstaller != null) {
2604                throw new RuntimeException("There must only be one ephemeral installer");
2605            }
2606
2607            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2608        }
2609
2610        return ephemeralInstaller;
2611    }
2612
2613    private void primeDomainVerificationsLPw(int userId) {
2614        if (DEBUG_DOMAIN_VERIFICATION) {
2615            Slog.d(TAG, "Priming domain verifications in user " + userId);
2616        }
2617
2618        SystemConfig systemConfig = SystemConfig.getInstance();
2619        ArraySet<String> packages = systemConfig.getLinkedApps();
2620        ArraySet<String> domains = new ArraySet<String>();
2621
2622        for (String packageName : packages) {
2623            PackageParser.Package pkg = mPackages.get(packageName);
2624            if (pkg != null) {
2625                if (!pkg.isSystemApp()) {
2626                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2627                    continue;
2628                }
2629
2630                domains.clear();
2631                for (PackageParser.Activity a : pkg.activities) {
2632                    for (ActivityIntentInfo filter : a.intents) {
2633                        if (hasValidDomains(filter)) {
2634                            domains.addAll(filter.getHostsList());
2635                        }
2636                    }
2637                }
2638
2639                if (domains.size() > 0) {
2640                    if (DEBUG_DOMAIN_VERIFICATION) {
2641                        Slog.v(TAG, "      + " + packageName);
2642                    }
2643                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2644                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2645                    // and then 'always' in the per-user state actually used for intent resolution.
2646                    final IntentFilterVerificationInfo ivi;
2647                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2648                            new ArrayList<String>(domains));
2649                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2650                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2651                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2652                } else {
2653                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2654                            + "' does not handle web links");
2655                }
2656            } else {
2657                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2658            }
2659        }
2660
2661        scheduleWritePackageRestrictionsLocked(userId);
2662        scheduleWriteSettingsLocked();
2663    }
2664
2665    private void applyFactoryDefaultBrowserLPw(int userId) {
2666        // The default browser app's package name is stored in a string resource,
2667        // with a product-specific overlay used for vendor customization.
2668        String browserPkg = mContext.getResources().getString(
2669                com.android.internal.R.string.default_browser);
2670        if (!TextUtils.isEmpty(browserPkg)) {
2671            // non-empty string => required to be a known package
2672            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2673            if (ps == null) {
2674                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2675                browserPkg = null;
2676            } else {
2677                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2678            }
2679        }
2680
2681        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2682        // default.  If there's more than one, just leave everything alone.
2683        if (browserPkg == null) {
2684            calculateDefaultBrowserLPw(userId);
2685        }
2686    }
2687
2688    private void calculateDefaultBrowserLPw(int userId) {
2689        List<String> allBrowsers = resolveAllBrowserApps(userId);
2690        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2691        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2692    }
2693
2694    private List<String> resolveAllBrowserApps(int userId) {
2695        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2696        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2697                PackageManager.MATCH_ALL, userId);
2698
2699        final int count = list.size();
2700        List<String> result = new ArrayList<String>(count);
2701        for (int i=0; i<count; i++) {
2702            ResolveInfo info = list.get(i);
2703            if (info.activityInfo == null
2704                    || !info.handleAllWebDataURI
2705                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2706                    || result.contains(info.activityInfo.packageName)) {
2707                continue;
2708            }
2709            result.add(info.activityInfo.packageName);
2710        }
2711
2712        return result;
2713    }
2714
2715    private boolean packageIsBrowser(String packageName, int userId) {
2716        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2717                PackageManager.MATCH_ALL, userId);
2718        final int N = list.size();
2719        for (int i = 0; i < N; i++) {
2720            ResolveInfo info = list.get(i);
2721            if (packageName.equals(info.activityInfo.packageName)) {
2722                return true;
2723            }
2724        }
2725        return false;
2726    }
2727
2728    private void checkDefaultBrowser() {
2729        final int myUserId = UserHandle.myUserId();
2730        final String packageName = getDefaultBrowserPackageName(myUserId);
2731        if (packageName != null) {
2732            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2733            if (info == null) {
2734                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2735                synchronized (mPackages) {
2736                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2737                }
2738            }
2739        }
2740    }
2741
2742    @Override
2743    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2744            throws RemoteException {
2745        try {
2746            return super.onTransact(code, data, reply, flags);
2747        } catch (RuntimeException e) {
2748            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2749                Slog.wtf(TAG, "Package Manager Crash", e);
2750            }
2751            throw e;
2752        }
2753    }
2754
2755    void cleanupInstallFailedPackage(PackageSetting ps) {
2756        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2757
2758        removeDataDirsLI(ps.volumeUuid, ps.name);
2759        if (ps.codePath != null) {
2760            if (ps.codePath.isDirectory()) {
2761                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2762            } else {
2763                ps.codePath.delete();
2764            }
2765        }
2766        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2767            if (ps.resourcePath.isDirectory()) {
2768                FileUtils.deleteContents(ps.resourcePath);
2769            }
2770            ps.resourcePath.delete();
2771        }
2772        mSettings.removePackageLPw(ps.name);
2773    }
2774
2775    static int[] appendInts(int[] cur, int[] add) {
2776        if (add == null) return cur;
2777        if (cur == null) return add;
2778        final int N = add.length;
2779        for (int i=0; i<N; i++) {
2780            cur = appendInt(cur, add[i]);
2781        }
2782        return cur;
2783    }
2784
2785    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2786        if (!sUserManager.exists(userId)) return null;
2787        final PackageSetting ps = (PackageSetting) p.mExtras;
2788        if (ps == null) {
2789            return null;
2790        }
2791
2792        final PermissionsState permissionsState = ps.getPermissionsState();
2793
2794        final int[] gids = permissionsState.computeGids(userId);
2795        final Set<String> permissions = permissionsState.getPermissions(userId);
2796        final PackageUserState state = ps.readUserState(userId);
2797
2798        return PackageParser.generatePackageInfo(p, gids, flags,
2799                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2800    }
2801
2802    @Override
2803    public void checkPackageStartable(String packageName, int userId) {
2804        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2805
2806        synchronized (mPackages) {
2807            final PackageSetting ps = mSettings.mPackages.get(packageName);
2808            if (ps == null) {
2809                throw new SecurityException("Package " + packageName + " was not found!");
2810            }
2811
2812            if (ps.frozen) {
2813                throw new SecurityException("Package " + packageName + " is currently frozen!");
2814            }
2815
2816            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2817                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2818                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2819            }
2820        }
2821    }
2822
2823    @Override
2824    public boolean isPackageAvailable(String packageName, int userId) {
2825        if (!sUserManager.exists(userId)) return false;
2826        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2827        synchronized (mPackages) {
2828            PackageParser.Package p = mPackages.get(packageName);
2829            if (p != null) {
2830                final PackageSetting ps = (PackageSetting) p.mExtras;
2831                if (ps != null) {
2832                    final PackageUserState state = ps.readUserState(userId);
2833                    if (state != null) {
2834                        return PackageParser.isAvailable(state);
2835                    }
2836                }
2837            }
2838        }
2839        return false;
2840    }
2841
2842    @Override
2843    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2844        if (!sUserManager.exists(userId)) return null;
2845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2846        // reader
2847        synchronized (mPackages) {
2848            PackageParser.Package p = mPackages.get(packageName);
2849            if (DEBUG_PACKAGE_INFO)
2850                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2851            if (p != null) {
2852                return generatePackageInfo(p, flags, userId);
2853            }
2854            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2855                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2856            }
2857        }
2858        return null;
2859    }
2860
2861    @Override
2862    public String[] currentToCanonicalPackageNames(String[] names) {
2863        String[] out = new String[names.length];
2864        // reader
2865        synchronized (mPackages) {
2866            for (int i=names.length-1; i>=0; i--) {
2867                PackageSetting ps = mSettings.mPackages.get(names[i]);
2868                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2869            }
2870        }
2871        return out;
2872    }
2873
2874    @Override
2875    public String[] canonicalToCurrentPackageNames(String[] names) {
2876        String[] out = new String[names.length];
2877        // reader
2878        synchronized (mPackages) {
2879            for (int i=names.length-1; i>=0; i--) {
2880                String cur = mSettings.mRenamedPackages.get(names[i]);
2881                out[i] = cur != null ? cur : names[i];
2882            }
2883        }
2884        return out;
2885    }
2886
2887    @Override
2888    public int getPackageUid(String packageName, int userId) {
2889        return getPackageUidEtc(packageName, 0, userId);
2890    }
2891
2892    @Override
2893    public int getPackageUidEtc(String packageName, int flags, int userId) {
2894        if (!sUserManager.exists(userId)) return -1;
2895        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2896
2897        // reader
2898        synchronized (mPackages) {
2899            final PackageParser.Package p = mPackages.get(packageName);
2900            if (p != null) {
2901                return UserHandle.getUid(userId, p.applicationInfo.uid);
2902            }
2903            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2904                final PackageSetting ps = mSettings.mPackages.get(packageName);
2905                if (ps != null) {
2906                    return UserHandle.getUid(userId, ps.appId);
2907                }
2908            }
2909        }
2910
2911        return -1;
2912    }
2913
2914    @Override
2915    public int[] getPackageGids(String packageName, int userId) {
2916        return getPackageGidsEtc(packageName, 0, userId);
2917    }
2918
2919    @Override
2920    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2921        if (!sUserManager.exists(userId)) {
2922            return null;
2923        }
2924
2925        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2926                "getPackageGids");
2927
2928        // reader
2929        synchronized (mPackages) {
2930            final PackageParser.Package p = mPackages.get(packageName);
2931            if (p != null) {
2932                PackageSetting ps = (PackageSetting) p.mExtras;
2933                return ps.getPermissionsState().computeGids(userId);
2934            }
2935            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2936                final PackageSetting ps = mSettings.mPackages.get(packageName);
2937                if (ps != null) {
2938                    return ps.getPermissionsState().computeGids(userId);
2939                }
2940            }
2941        }
2942
2943        return null;
2944    }
2945
2946    static PermissionInfo generatePermissionInfo(
2947            BasePermission bp, int flags) {
2948        if (bp.perm != null) {
2949            return PackageParser.generatePermissionInfo(bp.perm, flags);
2950        }
2951        PermissionInfo pi = new PermissionInfo();
2952        pi.name = bp.name;
2953        pi.packageName = bp.sourcePackage;
2954        pi.nonLocalizedLabel = bp.name;
2955        pi.protectionLevel = bp.protectionLevel;
2956        return pi;
2957    }
2958
2959    @Override
2960    public PermissionInfo getPermissionInfo(String name, int flags) {
2961        // reader
2962        synchronized (mPackages) {
2963            final BasePermission p = mSettings.mPermissions.get(name);
2964            if (p != null) {
2965                return generatePermissionInfo(p, flags);
2966            }
2967            return null;
2968        }
2969    }
2970
2971    @Override
2972    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2973        // reader
2974        synchronized (mPackages) {
2975            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2976            for (BasePermission p : mSettings.mPermissions.values()) {
2977                if (group == null) {
2978                    if (p.perm == null || p.perm.info.group == null) {
2979                        out.add(generatePermissionInfo(p, flags));
2980                    }
2981                } else {
2982                    if (p.perm != null && group.equals(p.perm.info.group)) {
2983                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2984                    }
2985                }
2986            }
2987
2988            if (out.size() > 0) {
2989                return out;
2990            }
2991            return mPermissionGroups.containsKey(group) ? out : null;
2992        }
2993    }
2994
2995    @Override
2996    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2997        // reader
2998        synchronized (mPackages) {
2999            return PackageParser.generatePermissionGroupInfo(
3000                    mPermissionGroups.get(name), flags);
3001        }
3002    }
3003
3004    @Override
3005    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3006        // reader
3007        synchronized (mPackages) {
3008            final int N = mPermissionGroups.size();
3009            ArrayList<PermissionGroupInfo> out
3010                    = new ArrayList<PermissionGroupInfo>(N);
3011            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3012                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3013            }
3014            return out;
3015        }
3016    }
3017
3018    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3019            int userId) {
3020        if (!sUserManager.exists(userId)) return null;
3021        PackageSetting ps = mSettings.mPackages.get(packageName);
3022        if (ps != null) {
3023            if (ps.pkg == null) {
3024                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3025                        flags, userId);
3026                if (pInfo != null) {
3027                    return pInfo.applicationInfo;
3028                }
3029                return null;
3030            }
3031            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3032                    ps.readUserState(userId), userId);
3033        }
3034        return null;
3035    }
3036
3037    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3038            int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        PackageSetting ps = mSettings.mPackages.get(packageName);
3041        if (ps != null) {
3042            PackageParser.Package pkg = ps.pkg;
3043            if (pkg == null) {
3044                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3045                    return null;
3046                }
3047                // Only data remains, so we aren't worried about code paths
3048                pkg = new PackageParser.Package(packageName);
3049                pkg.applicationInfo.packageName = packageName;
3050                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3051                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3052                pkg.applicationInfo.uid = ps.appId;
3053                pkg.applicationInfo.initForUser(userId);
3054                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3055                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3056            }
3057            return generatePackageInfo(pkg, flags, userId);
3058        }
3059        return null;
3060    }
3061
3062    @Override
3063    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3064        if (!sUserManager.exists(userId)) return null;
3065        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3066        // writer
3067        synchronized (mPackages) {
3068            PackageParser.Package p = mPackages.get(packageName);
3069            if (DEBUG_PACKAGE_INFO) Log.v(
3070                    TAG, "getApplicationInfo " + packageName
3071                    + ": " + p);
3072            if (p != null) {
3073                PackageSetting ps = mSettings.mPackages.get(packageName);
3074                if (ps == null) return null;
3075                // Note: isEnabledLP() does not apply here - always return info
3076                return PackageParser.generateApplicationInfo(
3077                        p, flags, ps.readUserState(userId), userId);
3078            }
3079            if ("android".equals(packageName)||"system".equals(packageName)) {
3080                return mAndroidApplication;
3081            }
3082            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3083                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3084            }
3085        }
3086        return null;
3087    }
3088
3089    @Override
3090    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3091            final IPackageDataObserver observer) {
3092        mContext.enforceCallingOrSelfPermission(
3093                android.Manifest.permission.CLEAR_APP_CACHE, null);
3094        // Queue up an async operation since clearing cache may take a little while.
3095        mHandler.post(new Runnable() {
3096            public void run() {
3097                mHandler.removeCallbacks(this);
3098                int retCode = -1;
3099                synchronized (mInstallLock) {
3100                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3101                    if (retCode < 0) {
3102                        Slog.w(TAG, "Couldn't clear application caches");
3103                    }
3104                }
3105                if (observer != null) {
3106                    try {
3107                        observer.onRemoveCompleted(null, (retCode >= 0));
3108                    } catch (RemoteException e) {
3109                        Slog.w(TAG, "RemoveException when invoking call back");
3110                    }
3111                }
3112            }
3113        });
3114    }
3115
3116    @Override
3117    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3118            final IntentSender pi) {
3119        mContext.enforceCallingOrSelfPermission(
3120                android.Manifest.permission.CLEAR_APP_CACHE, null);
3121        // Queue up an async operation since clearing cache may take a little while.
3122        mHandler.post(new Runnable() {
3123            public void run() {
3124                mHandler.removeCallbacks(this);
3125                int retCode = -1;
3126                synchronized (mInstallLock) {
3127                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3128                    if (retCode < 0) {
3129                        Slog.w(TAG, "Couldn't clear application caches");
3130                    }
3131                }
3132                if(pi != null) {
3133                    try {
3134                        // Callback via pending intent
3135                        int code = (retCode >= 0) ? 1 : 0;
3136                        pi.sendIntent(null, code, null,
3137                                null, null);
3138                    } catch (SendIntentException e1) {
3139                        Slog.i(TAG, "Failed to send pending intent");
3140                    }
3141                }
3142            }
3143        });
3144    }
3145
3146    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3147        synchronized (mInstallLock) {
3148            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3149                throw new IOException("Failed to free enough space");
3150            }
3151        }
3152    }
3153
3154    /**
3155     * Return if the user key is currently unlocked.
3156     */
3157    private boolean isUserKeyUnlocked(int userId) {
3158        if (StorageManager.isFileBasedEncryptionEnabled()) {
3159            final IMountService mount = IMountService.Stub
3160                    .asInterface(ServiceManager.getService("mount"));
3161            if (mount == null) {
3162                Slog.w(TAG, "Early during boot, assuming locked");
3163                return false;
3164            }
3165            final long token = Binder.clearCallingIdentity();
3166            try {
3167                return mount.isUserKeyUnlocked(userId);
3168            } catch (RemoteException e) {
3169                throw e.rethrowAsRuntimeException();
3170            } finally {
3171                Binder.restoreCallingIdentity(token);
3172            }
3173        } else {
3174            return true;
3175        }
3176    }
3177
3178    /**
3179     * Augment the given flags depending on current user running state. This is
3180     * purposefully done before acquiring {@link #mPackages} lock.
3181     */
3182    private int augmentFlagsForUser(int flags, int userId) {
3183        if (!isUserKeyUnlocked(userId)) {
3184            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3185        }
3186        return flags;
3187    }
3188
3189    @Override
3190    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3191        if (!sUserManager.exists(userId)) return null;
3192        flags = augmentFlagsForUser(flags, userId);
3193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3194        synchronized (mPackages) {
3195            PackageParser.Activity a = mActivities.mActivities.get(component);
3196
3197            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3198            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3200                if (ps == null) return null;
3201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3202                        userId);
3203            }
3204            if (mResolveComponentName.equals(component)) {
3205                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3206                        new PackageUserState(), userId);
3207            }
3208        }
3209        return null;
3210    }
3211
3212    @Override
3213    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3214            String resolvedType) {
3215        synchronized (mPackages) {
3216            if (component.equals(mResolveComponentName)) {
3217                // The resolver supports EVERYTHING!
3218                return true;
3219            }
3220            PackageParser.Activity a = mActivities.mActivities.get(component);
3221            if (a == null) {
3222                return false;
3223            }
3224            for (int i=0; i<a.intents.size(); i++) {
3225                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3226                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3227                    return true;
3228                }
3229            }
3230            return false;
3231        }
3232    }
3233
3234    @Override
3235    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3236        if (!sUserManager.exists(userId)) return null;
3237        flags = augmentFlagsForUser(flags, userId);
3238        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3239        synchronized (mPackages) {
3240            PackageParser.Activity a = mReceivers.mActivities.get(component);
3241            if (DEBUG_PACKAGE_INFO) Log.v(
3242                TAG, "getReceiverInfo " + component + ": " + a);
3243            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3244                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3245                if (ps == null) return null;
3246                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3247                        userId);
3248            }
3249        }
3250        return null;
3251    }
3252
3253    @Override
3254    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3255        if (!sUserManager.exists(userId)) return null;
3256        flags = augmentFlagsForUser(flags, userId);
3257        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3258        synchronized (mPackages) {
3259            PackageParser.Service s = mServices.mServices.get(component);
3260            if (DEBUG_PACKAGE_INFO) Log.v(
3261                TAG, "getServiceInfo " + component + ": " + s);
3262            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3263                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3264                if (ps == null) return null;
3265                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3266                        userId);
3267            }
3268        }
3269        return null;
3270    }
3271
3272    @Override
3273    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3274        if (!sUserManager.exists(userId)) return null;
3275        flags = augmentFlagsForUser(flags, userId);
3276        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3277        synchronized (mPackages) {
3278            PackageParser.Provider p = mProviders.mProviders.get(component);
3279            if (DEBUG_PACKAGE_INFO) Log.v(
3280                TAG, "getProviderInfo " + component + ": " + p);
3281            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3282                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3283                if (ps == null) return null;
3284                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3285                        userId);
3286            }
3287        }
3288        return null;
3289    }
3290
3291    @Override
3292    public String[] getSystemSharedLibraryNames() {
3293        Set<String> libSet;
3294        synchronized (mPackages) {
3295            libSet = mSharedLibraries.keySet();
3296            int size = libSet.size();
3297            if (size > 0) {
3298                String[] libs = new String[size];
3299                libSet.toArray(libs);
3300                return libs;
3301            }
3302        }
3303        return null;
3304    }
3305
3306    /**
3307     * @hide
3308     */
3309    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3310        synchronized (mPackages) {
3311            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3312            if (lib != null && lib.apk != null) {
3313                return mPackages.get(lib.apk);
3314            }
3315        }
3316        return null;
3317    }
3318
3319    @Override
3320    public FeatureInfo[] getSystemAvailableFeatures() {
3321        Collection<FeatureInfo> featSet;
3322        synchronized (mPackages) {
3323            featSet = mAvailableFeatures.values();
3324            int size = featSet.size();
3325            if (size > 0) {
3326                FeatureInfo[] features = new FeatureInfo[size+1];
3327                featSet.toArray(features);
3328                FeatureInfo fi = new FeatureInfo();
3329                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3330                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3331                features[size] = fi;
3332                return features;
3333            }
3334        }
3335        return null;
3336    }
3337
3338    @Override
3339    public boolean hasSystemFeature(String name) {
3340        synchronized (mPackages) {
3341            return mAvailableFeatures.containsKey(name);
3342        }
3343    }
3344
3345    private void checkValidCaller(int uid, int userId) {
3346        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3347            return;
3348
3349        throw new SecurityException("Caller uid=" + uid
3350                + " is not privileged to communicate with user=" + userId);
3351    }
3352
3353    @Override
3354    public int checkPermission(String permName, String pkgName, int userId) {
3355        if (!sUserManager.exists(userId)) {
3356            return PackageManager.PERMISSION_DENIED;
3357        }
3358
3359        synchronized (mPackages) {
3360            final PackageParser.Package p = mPackages.get(pkgName);
3361            if (p != null && p.mExtras != null) {
3362                final PackageSetting ps = (PackageSetting) p.mExtras;
3363                final PermissionsState permissionsState = ps.getPermissionsState();
3364                if (permissionsState.hasPermission(permName, userId)) {
3365                    return PackageManager.PERMISSION_GRANTED;
3366                }
3367                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3368                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3369                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3370                    return PackageManager.PERMISSION_GRANTED;
3371                }
3372            }
3373        }
3374
3375        return PackageManager.PERMISSION_DENIED;
3376    }
3377
3378    @Override
3379    public int checkUidPermission(String permName, int uid) {
3380        final int userId = UserHandle.getUserId(uid);
3381
3382        if (!sUserManager.exists(userId)) {
3383            return PackageManager.PERMISSION_DENIED;
3384        }
3385
3386        synchronized (mPackages) {
3387            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3388            if (obj != null) {
3389                final SettingBase ps = (SettingBase) obj;
3390                final PermissionsState permissionsState = ps.getPermissionsState();
3391                if (permissionsState.hasPermission(permName, userId)) {
3392                    return PackageManager.PERMISSION_GRANTED;
3393                }
3394                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3395                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3396                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3397                    return PackageManager.PERMISSION_GRANTED;
3398                }
3399            } else {
3400                ArraySet<String> perms = mSystemPermissions.get(uid);
3401                if (perms != null) {
3402                    if (perms.contains(permName)) {
3403                        return PackageManager.PERMISSION_GRANTED;
3404                    }
3405                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3406                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3407                        return PackageManager.PERMISSION_GRANTED;
3408                    }
3409                }
3410            }
3411        }
3412
3413        return PackageManager.PERMISSION_DENIED;
3414    }
3415
3416    @Override
3417    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3418        if (UserHandle.getCallingUserId() != userId) {
3419            mContext.enforceCallingPermission(
3420                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3421                    "isPermissionRevokedByPolicy for user " + userId);
3422        }
3423
3424        if (checkPermission(permission, packageName, userId)
3425                == PackageManager.PERMISSION_GRANTED) {
3426            return false;
3427        }
3428
3429        final long identity = Binder.clearCallingIdentity();
3430        try {
3431            final int flags = getPermissionFlags(permission, packageName, userId);
3432            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3433        } finally {
3434            Binder.restoreCallingIdentity(identity);
3435        }
3436    }
3437
3438    @Override
3439    public String getPermissionControllerPackageName() {
3440        synchronized (mPackages) {
3441            return mRequiredInstallerPackage;
3442        }
3443    }
3444
3445    /**
3446     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3447     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3448     * @param checkShell TODO(yamasani):
3449     * @param message the message to log on security exception
3450     */
3451    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3452            boolean checkShell, String message) {
3453        if (userId < 0) {
3454            throw new IllegalArgumentException("Invalid userId " + userId);
3455        }
3456        if (checkShell) {
3457            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3458        }
3459        if (userId == UserHandle.getUserId(callingUid)) return;
3460        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3461            if (requireFullPermission) {
3462                mContext.enforceCallingOrSelfPermission(
3463                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3464            } else {
3465                try {
3466                    mContext.enforceCallingOrSelfPermission(
3467                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3468                } catch (SecurityException se) {
3469                    mContext.enforceCallingOrSelfPermission(
3470                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3471                }
3472            }
3473        }
3474    }
3475
3476    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3477        if (callingUid == Process.SHELL_UID) {
3478            if (userHandle >= 0
3479                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3480                throw new SecurityException("Shell does not have permission to access user "
3481                        + userHandle);
3482            } else if (userHandle < 0) {
3483                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3484                        + Debug.getCallers(3));
3485            }
3486        }
3487    }
3488
3489    private BasePermission findPermissionTreeLP(String permName) {
3490        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3491            if (permName.startsWith(bp.name) &&
3492                    permName.length() > bp.name.length() &&
3493                    permName.charAt(bp.name.length()) == '.') {
3494                return bp;
3495            }
3496        }
3497        return null;
3498    }
3499
3500    private BasePermission checkPermissionTreeLP(String permName) {
3501        if (permName != null) {
3502            BasePermission bp = findPermissionTreeLP(permName);
3503            if (bp != null) {
3504                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3505                    return bp;
3506                }
3507                throw new SecurityException("Calling uid "
3508                        + Binder.getCallingUid()
3509                        + " is not allowed to add to permission tree "
3510                        + bp.name + " owned by uid " + bp.uid);
3511            }
3512        }
3513        throw new SecurityException("No permission tree found for " + permName);
3514    }
3515
3516    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3517        if (s1 == null) {
3518            return s2 == null;
3519        }
3520        if (s2 == null) {
3521            return false;
3522        }
3523        if (s1.getClass() != s2.getClass()) {
3524            return false;
3525        }
3526        return s1.equals(s2);
3527    }
3528
3529    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3530        if (pi1.icon != pi2.icon) return false;
3531        if (pi1.logo != pi2.logo) return false;
3532        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3533        if (!compareStrings(pi1.name, pi2.name)) return false;
3534        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3535        // We'll take care of setting this one.
3536        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3537        // These are not currently stored in settings.
3538        //if (!compareStrings(pi1.group, pi2.group)) return false;
3539        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3540        //if (pi1.labelRes != pi2.labelRes) return false;
3541        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3542        return true;
3543    }
3544
3545    int permissionInfoFootprint(PermissionInfo info) {
3546        int size = info.name.length();
3547        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3548        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3549        return size;
3550    }
3551
3552    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3553        int size = 0;
3554        for (BasePermission perm : mSettings.mPermissions.values()) {
3555            if (perm.uid == tree.uid) {
3556                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3557            }
3558        }
3559        return size;
3560    }
3561
3562    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3563        // We calculate the max size of permissions defined by this uid and throw
3564        // if that plus the size of 'info' would exceed our stated maximum.
3565        if (tree.uid != Process.SYSTEM_UID) {
3566            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3567            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3568                throw new SecurityException("Permission tree size cap exceeded");
3569            }
3570        }
3571    }
3572
3573    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3574        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3575            throw new SecurityException("Label must be specified in permission");
3576        }
3577        BasePermission tree = checkPermissionTreeLP(info.name);
3578        BasePermission bp = mSettings.mPermissions.get(info.name);
3579        boolean added = bp == null;
3580        boolean changed = true;
3581        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3582        if (added) {
3583            enforcePermissionCapLocked(info, tree);
3584            bp = new BasePermission(info.name, tree.sourcePackage,
3585                    BasePermission.TYPE_DYNAMIC);
3586        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3587            throw new SecurityException(
3588                    "Not allowed to modify non-dynamic permission "
3589                    + info.name);
3590        } else {
3591            if (bp.protectionLevel == fixedLevel
3592                    && bp.perm.owner.equals(tree.perm.owner)
3593                    && bp.uid == tree.uid
3594                    && comparePermissionInfos(bp.perm.info, info)) {
3595                changed = false;
3596            }
3597        }
3598        bp.protectionLevel = fixedLevel;
3599        info = new PermissionInfo(info);
3600        info.protectionLevel = fixedLevel;
3601        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3602        bp.perm.info.packageName = tree.perm.info.packageName;
3603        bp.uid = tree.uid;
3604        if (added) {
3605            mSettings.mPermissions.put(info.name, bp);
3606        }
3607        if (changed) {
3608            if (!async) {
3609                mSettings.writeLPr();
3610            } else {
3611                scheduleWriteSettingsLocked();
3612            }
3613        }
3614        return added;
3615    }
3616
3617    @Override
3618    public boolean addPermission(PermissionInfo info) {
3619        synchronized (mPackages) {
3620            return addPermissionLocked(info, false);
3621        }
3622    }
3623
3624    @Override
3625    public boolean addPermissionAsync(PermissionInfo info) {
3626        synchronized (mPackages) {
3627            return addPermissionLocked(info, true);
3628        }
3629    }
3630
3631    @Override
3632    public void removePermission(String name) {
3633        synchronized (mPackages) {
3634            checkPermissionTreeLP(name);
3635            BasePermission bp = mSettings.mPermissions.get(name);
3636            if (bp != null) {
3637                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3638                    throw new SecurityException(
3639                            "Not allowed to modify non-dynamic permission "
3640                            + name);
3641                }
3642                mSettings.mPermissions.remove(name);
3643                mSettings.writeLPr();
3644            }
3645        }
3646    }
3647
3648    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3649            BasePermission bp) {
3650        int index = pkg.requestedPermissions.indexOf(bp.name);
3651        if (index == -1) {
3652            throw new SecurityException("Package " + pkg.packageName
3653                    + " has not requested permission " + bp.name);
3654        }
3655        if (!bp.isRuntime() && !bp.isDevelopment()) {
3656            throw new SecurityException("Permission " + bp.name
3657                    + " is not a changeable permission type");
3658        }
3659    }
3660
3661    @Override
3662    public void grantRuntimePermission(String packageName, String name, final int userId) {
3663        if (!sUserManager.exists(userId)) {
3664            Log.e(TAG, "No such user:" + userId);
3665            return;
3666        }
3667
3668        mContext.enforceCallingOrSelfPermission(
3669                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3670                "grantRuntimePermission");
3671
3672        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3673                "grantRuntimePermission");
3674
3675        final int uid;
3676        final SettingBase sb;
3677
3678        synchronized (mPackages) {
3679            final PackageParser.Package pkg = mPackages.get(packageName);
3680            if (pkg == null) {
3681                throw new IllegalArgumentException("Unknown package: " + packageName);
3682            }
3683
3684            final BasePermission bp = mSettings.mPermissions.get(name);
3685            if (bp == null) {
3686                throw new IllegalArgumentException("Unknown permission: " + name);
3687            }
3688
3689            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3690
3691            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3692            sb = (SettingBase) pkg.mExtras;
3693            if (sb == null) {
3694                throw new IllegalArgumentException("Unknown package: " + packageName);
3695            }
3696
3697            final PermissionsState permissionsState = sb.getPermissionsState();
3698
3699            final int flags = permissionsState.getPermissionFlags(name, userId);
3700            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3701                throw new SecurityException("Cannot grant system fixed permission: "
3702                        + name + " for package: " + packageName);
3703            }
3704
3705            if (bp.isDevelopment()) {
3706                // Development permissions must be handled specially, since they are not
3707                // normal runtime permissions.  For now they apply to all users.
3708                if (permissionsState.grantInstallPermission(bp) !=
3709                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3710                    scheduleWriteSettingsLocked();
3711                }
3712                return;
3713            }
3714
3715            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3716                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3717                return;
3718            }
3719
3720            final int result = permissionsState.grantRuntimePermission(bp, userId);
3721            switch (result) {
3722                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3723                    return;
3724                }
3725
3726                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3727                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3728                    mHandler.post(new Runnable() {
3729                        @Override
3730                        public void run() {
3731                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3732                        }
3733                    });
3734                }
3735                break;
3736            }
3737
3738            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3739
3740            // Not critical if that is lost - app has to request again.
3741            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3742        }
3743
3744        // Only need to do this if user is initialized. Otherwise it's a new user
3745        // and there are no processes running as the user yet and there's no need
3746        // to make an expensive call to remount processes for the changed permissions.
3747        if (READ_EXTERNAL_STORAGE.equals(name)
3748                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3749            final long token = Binder.clearCallingIdentity();
3750            try {
3751                if (sUserManager.isInitialized(userId)) {
3752                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3753                            MountServiceInternal.class);
3754                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3755                }
3756            } finally {
3757                Binder.restoreCallingIdentity(token);
3758            }
3759        }
3760    }
3761
3762    @Override
3763    public void revokeRuntimePermission(String packageName, String name, int userId) {
3764        if (!sUserManager.exists(userId)) {
3765            Log.e(TAG, "No such user:" + userId);
3766            return;
3767        }
3768
3769        mContext.enforceCallingOrSelfPermission(
3770                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3771                "revokeRuntimePermission");
3772
3773        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3774                "revokeRuntimePermission");
3775
3776        final int appId;
3777
3778        synchronized (mPackages) {
3779            final PackageParser.Package pkg = mPackages.get(packageName);
3780            if (pkg == null) {
3781                throw new IllegalArgumentException("Unknown package: " + packageName);
3782            }
3783
3784            final BasePermission bp = mSettings.mPermissions.get(name);
3785            if (bp == null) {
3786                throw new IllegalArgumentException("Unknown permission: " + name);
3787            }
3788
3789            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3790
3791            SettingBase sb = (SettingBase) pkg.mExtras;
3792            if (sb == null) {
3793                throw new IllegalArgumentException("Unknown package: " + packageName);
3794            }
3795
3796            final PermissionsState permissionsState = sb.getPermissionsState();
3797
3798            final int flags = permissionsState.getPermissionFlags(name, userId);
3799            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3800                throw new SecurityException("Cannot revoke system fixed permission: "
3801                        + name + " for package: " + packageName);
3802            }
3803
3804            if (bp.isDevelopment()) {
3805                // Development permissions must be handled specially, since they are not
3806                // normal runtime permissions.  For now they apply to all users.
3807                if (permissionsState.revokeInstallPermission(bp) !=
3808                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3809                    scheduleWriteSettingsLocked();
3810                }
3811                return;
3812            }
3813
3814            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3815                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3816                return;
3817            }
3818
3819            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3820
3821            // Critical, after this call app should never have the permission.
3822            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3823
3824            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3825        }
3826
3827        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3828    }
3829
3830    @Override
3831    public void resetRuntimePermissions() {
3832        mContext.enforceCallingOrSelfPermission(
3833                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3834                "revokeRuntimePermission");
3835
3836        int callingUid = Binder.getCallingUid();
3837        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3838            mContext.enforceCallingOrSelfPermission(
3839                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3840                    "resetRuntimePermissions");
3841        }
3842
3843        synchronized (mPackages) {
3844            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3845            for (int userId : UserManagerService.getInstance().getUserIds()) {
3846                final int packageCount = mPackages.size();
3847                for (int i = 0; i < packageCount; i++) {
3848                    PackageParser.Package pkg = mPackages.valueAt(i);
3849                    if (!(pkg.mExtras instanceof PackageSetting)) {
3850                        continue;
3851                    }
3852                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3853                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3854                }
3855            }
3856        }
3857    }
3858
3859    @Override
3860    public int getPermissionFlags(String name, String packageName, int userId) {
3861        if (!sUserManager.exists(userId)) {
3862            return 0;
3863        }
3864
3865        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3866
3867        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3868                "getPermissionFlags");
3869
3870        synchronized (mPackages) {
3871            final PackageParser.Package pkg = mPackages.get(packageName);
3872            if (pkg == null) {
3873                throw new IllegalArgumentException("Unknown package: " + packageName);
3874            }
3875
3876            final BasePermission bp = mSettings.mPermissions.get(name);
3877            if (bp == null) {
3878                throw new IllegalArgumentException("Unknown permission: " + name);
3879            }
3880
3881            SettingBase sb = (SettingBase) pkg.mExtras;
3882            if (sb == null) {
3883                throw new IllegalArgumentException("Unknown package: " + packageName);
3884            }
3885
3886            PermissionsState permissionsState = sb.getPermissionsState();
3887            return permissionsState.getPermissionFlags(name, userId);
3888        }
3889    }
3890
3891    @Override
3892    public void updatePermissionFlags(String name, String packageName, int flagMask,
3893            int flagValues, int userId) {
3894        if (!sUserManager.exists(userId)) {
3895            return;
3896        }
3897
3898        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3899
3900        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3901                "updatePermissionFlags");
3902
3903        // Only the system can change these flags and nothing else.
3904        if (getCallingUid() != Process.SYSTEM_UID) {
3905            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3906            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3907            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3908            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3909        }
3910
3911        synchronized (mPackages) {
3912            final PackageParser.Package pkg = mPackages.get(packageName);
3913            if (pkg == null) {
3914                throw new IllegalArgumentException("Unknown package: " + packageName);
3915            }
3916
3917            final BasePermission bp = mSettings.mPermissions.get(name);
3918            if (bp == null) {
3919                throw new IllegalArgumentException("Unknown permission: " + name);
3920            }
3921
3922            SettingBase sb = (SettingBase) pkg.mExtras;
3923            if (sb == null) {
3924                throw new IllegalArgumentException("Unknown package: " + packageName);
3925            }
3926
3927            PermissionsState permissionsState = sb.getPermissionsState();
3928
3929            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3930
3931            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3932                // Install and runtime permissions are stored in different places,
3933                // so figure out what permission changed and persist the change.
3934                if (permissionsState.getInstallPermissionState(name) != null) {
3935                    scheduleWriteSettingsLocked();
3936                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3937                        || hadState) {
3938                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3939                }
3940            }
3941        }
3942    }
3943
3944    /**
3945     * Update the permission flags for all packages and runtime permissions of a user in order
3946     * to allow device or profile owner to remove POLICY_FIXED.
3947     */
3948    @Override
3949    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3950        if (!sUserManager.exists(userId)) {
3951            return;
3952        }
3953
3954        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3955
3956        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3957                "updatePermissionFlagsForAllApps");
3958
3959        // Only the system can change system fixed flags.
3960        if (getCallingUid() != Process.SYSTEM_UID) {
3961            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3962            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3963        }
3964
3965        synchronized (mPackages) {
3966            boolean changed = false;
3967            final int packageCount = mPackages.size();
3968            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3969                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3970                SettingBase sb = (SettingBase) pkg.mExtras;
3971                if (sb == null) {
3972                    continue;
3973                }
3974                PermissionsState permissionsState = sb.getPermissionsState();
3975                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3976                        userId, flagMask, flagValues);
3977            }
3978            if (changed) {
3979                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3980            }
3981        }
3982    }
3983
3984    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3985        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3986                != PackageManager.PERMISSION_GRANTED
3987            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3988                != PackageManager.PERMISSION_GRANTED) {
3989            throw new SecurityException(message + " requires "
3990                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3991                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3992        }
3993    }
3994
3995    @Override
3996    public boolean shouldShowRequestPermissionRationale(String permissionName,
3997            String packageName, int userId) {
3998        if (UserHandle.getCallingUserId() != userId) {
3999            mContext.enforceCallingPermission(
4000                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4001                    "canShowRequestPermissionRationale for user " + userId);
4002        }
4003
4004        final int uid = getPackageUid(packageName, userId);
4005        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4006            return false;
4007        }
4008
4009        if (checkPermission(permissionName, packageName, userId)
4010                == PackageManager.PERMISSION_GRANTED) {
4011            return false;
4012        }
4013
4014        final int flags;
4015
4016        final long identity = Binder.clearCallingIdentity();
4017        try {
4018            flags = getPermissionFlags(permissionName,
4019                    packageName, userId);
4020        } finally {
4021            Binder.restoreCallingIdentity(identity);
4022        }
4023
4024        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4025                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4026                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4027
4028        if ((flags & fixedFlags) != 0) {
4029            return false;
4030        }
4031
4032        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4033    }
4034
4035    @Override
4036    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4037        mContext.enforceCallingOrSelfPermission(
4038                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4039                "addOnPermissionsChangeListener");
4040
4041        synchronized (mPackages) {
4042            mOnPermissionChangeListeners.addListenerLocked(listener);
4043        }
4044    }
4045
4046    @Override
4047    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4048        synchronized (mPackages) {
4049            mOnPermissionChangeListeners.removeListenerLocked(listener);
4050        }
4051    }
4052
4053    @Override
4054    public boolean isProtectedBroadcast(String actionName) {
4055        synchronized (mPackages) {
4056            return mProtectedBroadcasts.contains(actionName);
4057        }
4058    }
4059
4060    @Override
4061    public int checkSignatures(String pkg1, String pkg2) {
4062        synchronized (mPackages) {
4063            final PackageParser.Package p1 = mPackages.get(pkg1);
4064            final PackageParser.Package p2 = mPackages.get(pkg2);
4065            if (p1 == null || p1.mExtras == null
4066                    || p2 == null || p2.mExtras == null) {
4067                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4068            }
4069            return compareSignatures(p1.mSignatures, p2.mSignatures);
4070        }
4071    }
4072
4073    @Override
4074    public int checkUidSignatures(int uid1, int uid2) {
4075        // Map to base uids.
4076        uid1 = UserHandle.getAppId(uid1);
4077        uid2 = UserHandle.getAppId(uid2);
4078        // reader
4079        synchronized (mPackages) {
4080            Signature[] s1;
4081            Signature[] s2;
4082            Object obj = mSettings.getUserIdLPr(uid1);
4083            if (obj != null) {
4084                if (obj instanceof SharedUserSetting) {
4085                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4086                } else if (obj instanceof PackageSetting) {
4087                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4088                } else {
4089                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4090                }
4091            } else {
4092                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4093            }
4094            obj = mSettings.getUserIdLPr(uid2);
4095            if (obj != null) {
4096                if (obj instanceof SharedUserSetting) {
4097                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4098                } else if (obj instanceof PackageSetting) {
4099                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4100                } else {
4101                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4102                }
4103            } else {
4104                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4105            }
4106            return compareSignatures(s1, s2);
4107        }
4108    }
4109
4110    private void killUid(int appId, int userId, String reason) {
4111        final long identity = Binder.clearCallingIdentity();
4112        try {
4113            IActivityManager am = ActivityManagerNative.getDefault();
4114            if (am != null) {
4115                try {
4116                    am.killUid(appId, userId, reason);
4117                } catch (RemoteException e) {
4118                    /* ignore - same process */
4119                }
4120            }
4121        } finally {
4122            Binder.restoreCallingIdentity(identity);
4123        }
4124    }
4125
4126    /**
4127     * Compares two sets of signatures. Returns:
4128     * <br />
4129     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4130     * <br />
4131     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4132     * <br />
4133     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4134     * <br />
4135     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4136     * <br />
4137     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4138     */
4139    static int compareSignatures(Signature[] s1, Signature[] s2) {
4140        if (s1 == null) {
4141            return s2 == null
4142                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4143                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4144        }
4145
4146        if (s2 == null) {
4147            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4148        }
4149
4150        if (s1.length != s2.length) {
4151            return PackageManager.SIGNATURE_NO_MATCH;
4152        }
4153
4154        // Since both signature sets are of size 1, we can compare without HashSets.
4155        if (s1.length == 1) {
4156            return s1[0].equals(s2[0]) ?
4157                    PackageManager.SIGNATURE_MATCH :
4158                    PackageManager.SIGNATURE_NO_MATCH;
4159        }
4160
4161        ArraySet<Signature> set1 = new ArraySet<Signature>();
4162        for (Signature sig : s1) {
4163            set1.add(sig);
4164        }
4165        ArraySet<Signature> set2 = new ArraySet<Signature>();
4166        for (Signature sig : s2) {
4167            set2.add(sig);
4168        }
4169        // Make sure s2 contains all signatures in s1.
4170        if (set1.equals(set2)) {
4171            return PackageManager.SIGNATURE_MATCH;
4172        }
4173        return PackageManager.SIGNATURE_NO_MATCH;
4174    }
4175
4176    /**
4177     * If the database version for this type of package (internal storage or
4178     * external storage) is less than the version where package signatures
4179     * were updated, return true.
4180     */
4181    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4182        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4183        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4184    }
4185
4186    /**
4187     * Used for backward compatibility to make sure any packages with
4188     * certificate chains get upgraded to the new style. {@code existingSigs}
4189     * will be in the old format (since they were stored on disk from before the
4190     * system upgrade) and {@code scannedSigs} will be in the newer format.
4191     */
4192    private int compareSignaturesCompat(PackageSignatures existingSigs,
4193            PackageParser.Package scannedPkg) {
4194        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4195            return PackageManager.SIGNATURE_NO_MATCH;
4196        }
4197
4198        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4199        for (Signature sig : existingSigs.mSignatures) {
4200            existingSet.add(sig);
4201        }
4202        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4203        for (Signature sig : scannedPkg.mSignatures) {
4204            try {
4205                Signature[] chainSignatures = sig.getChainSignatures();
4206                for (Signature chainSig : chainSignatures) {
4207                    scannedCompatSet.add(chainSig);
4208                }
4209            } catch (CertificateEncodingException e) {
4210                scannedCompatSet.add(sig);
4211            }
4212        }
4213        /*
4214         * Make sure the expanded scanned set contains all signatures in the
4215         * existing one.
4216         */
4217        if (scannedCompatSet.equals(existingSet)) {
4218            // Migrate the old signatures to the new scheme.
4219            existingSigs.assignSignatures(scannedPkg.mSignatures);
4220            // The new KeySets will be re-added later in the scanning process.
4221            synchronized (mPackages) {
4222                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4223            }
4224            return PackageManager.SIGNATURE_MATCH;
4225        }
4226        return PackageManager.SIGNATURE_NO_MATCH;
4227    }
4228
4229    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4230        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4231        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4232    }
4233
4234    private int compareSignaturesRecover(PackageSignatures existingSigs,
4235            PackageParser.Package scannedPkg) {
4236        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4237            return PackageManager.SIGNATURE_NO_MATCH;
4238        }
4239
4240        String msg = null;
4241        try {
4242            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4243                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4244                        + scannedPkg.packageName);
4245                return PackageManager.SIGNATURE_MATCH;
4246            }
4247        } catch (CertificateException e) {
4248            msg = e.getMessage();
4249        }
4250
4251        logCriticalInfo(Log.INFO,
4252                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4253        return PackageManager.SIGNATURE_NO_MATCH;
4254    }
4255
4256    @Override
4257    public String[] getPackagesForUid(int uid) {
4258        uid = UserHandle.getAppId(uid);
4259        // reader
4260        synchronized (mPackages) {
4261            Object obj = mSettings.getUserIdLPr(uid);
4262            if (obj instanceof SharedUserSetting) {
4263                final SharedUserSetting sus = (SharedUserSetting) obj;
4264                final int N = sus.packages.size();
4265                final String[] res = new String[N];
4266                final Iterator<PackageSetting> it = sus.packages.iterator();
4267                int i = 0;
4268                while (it.hasNext()) {
4269                    res[i++] = it.next().name;
4270                }
4271                return res;
4272            } else if (obj instanceof PackageSetting) {
4273                final PackageSetting ps = (PackageSetting) obj;
4274                return new String[] { ps.name };
4275            }
4276        }
4277        return null;
4278    }
4279
4280    @Override
4281    public String getNameForUid(int uid) {
4282        // reader
4283        synchronized (mPackages) {
4284            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4285            if (obj instanceof SharedUserSetting) {
4286                final SharedUserSetting sus = (SharedUserSetting) obj;
4287                return sus.name + ":" + sus.userId;
4288            } else if (obj instanceof PackageSetting) {
4289                final PackageSetting ps = (PackageSetting) obj;
4290                return ps.name;
4291            }
4292        }
4293        return null;
4294    }
4295
4296    @Override
4297    public int getUidForSharedUser(String sharedUserName) {
4298        if(sharedUserName == null) {
4299            return -1;
4300        }
4301        // reader
4302        synchronized (mPackages) {
4303            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4304            if (suid == null) {
4305                return -1;
4306            }
4307            return suid.userId;
4308        }
4309    }
4310
4311    @Override
4312    public int getFlagsForUid(int uid) {
4313        synchronized (mPackages) {
4314            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4315            if (obj instanceof SharedUserSetting) {
4316                final SharedUserSetting sus = (SharedUserSetting) obj;
4317                return sus.pkgFlags;
4318            } else if (obj instanceof PackageSetting) {
4319                final PackageSetting ps = (PackageSetting) obj;
4320                return ps.pkgFlags;
4321            }
4322        }
4323        return 0;
4324    }
4325
4326    @Override
4327    public int getPrivateFlagsForUid(int uid) {
4328        synchronized (mPackages) {
4329            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4330            if (obj instanceof SharedUserSetting) {
4331                final SharedUserSetting sus = (SharedUserSetting) obj;
4332                return sus.pkgPrivateFlags;
4333            } else if (obj instanceof PackageSetting) {
4334                final PackageSetting ps = (PackageSetting) obj;
4335                return ps.pkgPrivateFlags;
4336            }
4337        }
4338        return 0;
4339    }
4340
4341    @Override
4342    public boolean isUidPrivileged(int uid) {
4343        uid = UserHandle.getAppId(uid);
4344        // reader
4345        synchronized (mPackages) {
4346            Object obj = mSettings.getUserIdLPr(uid);
4347            if (obj instanceof SharedUserSetting) {
4348                final SharedUserSetting sus = (SharedUserSetting) obj;
4349                final Iterator<PackageSetting> it = sus.packages.iterator();
4350                while (it.hasNext()) {
4351                    if (it.next().isPrivileged()) {
4352                        return true;
4353                    }
4354                }
4355            } else if (obj instanceof PackageSetting) {
4356                final PackageSetting ps = (PackageSetting) obj;
4357                return ps.isPrivileged();
4358            }
4359        }
4360        return false;
4361    }
4362
4363    @Override
4364    public String[] getAppOpPermissionPackages(String permissionName) {
4365        synchronized (mPackages) {
4366            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4367            if (pkgs == null) {
4368                return null;
4369            }
4370            return pkgs.toArray(new String[pkgs.size()]);
4371        }
4372    }
4373
4374    @Override
4375    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4376            int flags, int userId) {
4377        if (!sUserManager.exists(userId)) return null;
4378        flags = augmentFlagsForUser(flags, userId);
4379        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4380        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4381        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4382    }
4383
4384    @Override
4385    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4386            IntentFilter filter, int match, ComponentName activity) {
4387        final int userId = UserHandle.getCallingUserId();
4388        if (DEBUG_PREFERRED) {
4389            Log.v(TAG, "setLastChosenActivity intent=" + intent
4390                + " resolvedType=" + resolvedType
4391                + " flags=" + flags
4392                + " filter=" + filter
4393                + " match=" + match
4394                + " activity=" + activity);
4395            filter.dump(new PrintStreamPrinter(System.out), "    ");
4396        }
4397        intent.setComponent(null);
4398        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4399        // Find any earlier preferred or last chosen entries and nuke them
4400        findPreferredActivity(intent, resolvedType,
4401                flags, query, 0, false, true, false, userId);
4402        // Add the new activity as the last chosen for this filter
4403        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4404                "Setting last chosen");
4405    }
4406
4407    @Override
4408    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4409        final int userId = UserHandle.getCallingUserId();
4410        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4411        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4412        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4413                false, false, false, userId);
4414    }
4415
4416    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4417        MessageDigest digest = null;
4418        try {
4419            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4420        } catch (NoSuchAlgorithmException e) {
4421            // If we can't create a digest, ignore ephemeral apps.
4422            return false;
4423        }
4424
4425        final byte[] hostBytes = intent.getData().getHost().getBytes();
4426        final byte[] digestBytes = digest.digest(hostBytes);
4427        int shaPrefix =
4428                digestBytes[0] << 24
4429                | digestBytes[1] << 16
4430                | digestBytes[2] << 8
4431                | digestBytes[3] << 0;
4432        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4433                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4434        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4435            // No hash prefix match; there are no ephemeral apps for this domain.
4436            return false;
4437        }
4438        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4439            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4440            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4441                continue;
4442            }
4443            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4444            // No filters; this should never happen.
4445            if (filters.isEmpty()) {
4446                continue;
4447            }
4448            // We have a domain match; resolve the filters to see if anything matches.
4449            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4450            for (int j = filters.size() - 1; j >= 0; --j) {
4451                ephemeralResolver.addFilter(filters.get(j));
4452            }
4453            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4454                    intent, resolvedType, false /*defaultOnly*/, userId);
4455            return !ephemeralResolveList.isEmpty();
4456        }
4457        // Hash or filter mis-match; no ephemeral apps for this domain.
4458        return false;
4459    }
4460
4461    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4462            int flags, List<ResolveInfo> query, int userId) {
4463        final boolean isWebUri = hasWebURI(intent);
4464        // Check whether or not an ephemeral app exists to handle the URI.
4465        if (isWebUri && mEphemeralResolverConnection != null) {
4466            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4467            boolean hasAlwaysHandler = false;
4468            synchronized (mPackages) {
4469                final int count = query.size();
4470                for (int n=0; n<count; n++) {
4471                    ResolveInfo info = query.get(n);
4472                    String packageName = info.activityInfo.packageName;
4473                    PackageSetting ps = mSettings.mPackages.get(packageName);
4474                    if (ps != null) {
4475                        // Try to get the status from User settings first
4476                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4477                        int status = (int) (packedStatus >> 32);
4478                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4479                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4480                            hasAlwaysHandler = true;
4481                            break;
4482                        }
4483                    }
4484                }
4485            }
4486
4487            // Only consider installing an ephemeral app if there isn't already a verified handler.
4488            // We've determined that there's an ephemeral app available for the URI, ignore any
4489            // ResolveInfo's and just return the ephemeral installer
4490            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4491                if (DEBUG_EPHEMERAL) {
4492                    Slog.v(TAG, "Resolving to the ephemeral installer");
4493                }
4494                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4495                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4496                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4497                // make a deep copy of the applicationInfo
4498                ri.activityInfo.applicationInfo = new ApplicationInfo(
4499                        ri.activityInfo.applicationInfo);
4500                if (userId != 0) {
4501                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4502                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4503                }
4504                return ri;
4505            }
4506        }
4507        if (query != null) {
4508            final int N = query.size();
4509            if (N == 1) {
4510                return query.get(0);
4511            } else if (N > 1) {
4512                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4513                // If there is more than one activity with the same priority,
4514                // then let the user decide between them.
4515                ResolveInfo r0 = query.get(0);
4516                ResolveInfo r1 = query.get(1);
4517                if (DEBUG_INTENT_MATCHING || debug) {
4518                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4519                            + r1.activityInfo.name + "=" + r1.priority);
4520                }
4521                // If the first activity has a higher priority, or a different
4522                // default, then it is always desireable to pick it.
4523                if (r0.priority != r1.priority
4524                        || r0.preferredOrder != r1.preferredOrder
4525                        || r0.isDefault != r1.isDefault) {
4526                    return query.get(0);
4527                }
4528                // If we have saved a preference for a preferred activity for
4529                // this Intent, use that.
4530                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4531                        flags, query, r0.priority, true, false, debug, userId);
4532                if (ri != null) {
4533                    return ri;
4534                }
4535                ri = new ResolveInfo(mResolveInfo);
4536                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4537                ri.activityInfo.applicationInfo = new ApplicationInfo(
4538                        ri.activityInfo.applicationInfo);
4539                if (userId != 0) {
4540                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4541                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4542                }
4543                // Make sure that the resolver is displayable in car mode
4544                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4545                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4546                return ri;
4547            }
4548        }
4549        return null;
4550    }
4551
4552    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4553            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4554        final int N = query.size();
4555        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4556                .get(userId);
4557        // Get the list of persistent preferred activities that handle the intent
4558        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4559        List<PersistentPreferredActivity> pprefs = ppir != null
4560                ? ppir.queryIntent(intent, resolvedType,
4561                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4562                : null;
4563        if (pprefs != null && pprefs.size() > 0) {
4564            final int M = pprefs.size();
4565            for (int i=0; i<M; i++) {
4566                final PersistentPreferredActivity ppa = pprefs.get(i);
4567                if (DEBUG_PREFERRED || debug) {
4568                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4569                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4570                            + "\n  component=" + ppa.mComponent);
4571                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4572                }
4573                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4574                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4575                if (DEBUG_PREFERRED || debug) {
4576                    Slog.v(TAG, "Found persistent preferred activity:");
4577                    if (ai != null) {
4578                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4579                    } else {
4580                        Slog.v(TAG, "  null");
4581                    }
4582                }
4583                if (ai == null) {
4584                    // This previously registered persistent preferred activity
4585                    // component is no longer known. Ignore it and do NOT remove it.
4586                    continue;
4587                }
4588                for (int j=0; j<N; j++) {
4589                    final ResolveInfo ri = query.get(j);
4590                    if (!ri.activityInfo.applicationInfo.packageName
4591                            .equals(ai.applicationInfo.packageName)) {
4592                        continue;
4593                    }
4594                    if (!ri.activityInfo.name.equals(ai.name)) {
4595                        continue;
4596                    }
4597                    //  Found a persistent preference that can handle the intent.
4598                    if (DEBUG_PREFERRED || debug) {
4599                        Slog.v(TAG, "Returning persistent preferred activity: " +
4600                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4601                    }
4602                    return ri;
4603                }
4604            }
4605        }
4606        return null;
4607    }
4608
4609    // TODO: handle preferred activities missing while user has amnesia
4610    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4611            List<ResolveInfo> query, int priority, boolean always,
4612            boolean removeMatches, boolean debug, int userId) {
4613        if (!sUserManager.exists(userId)) return null;
4614        flags = augmentFlagsForUser(flags, userId);
4615        // writer
4616        synchronized (mPackages) {
4617            if (intent.getSelector() != null) {
4618                intent = intent.getSelector();
4619            }
4620            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4621
4622            // Try to find a matching persistent preferred activity.
4623            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4624                    debug, userId);
4625
4626            // If a persistent preferred activity matched, use it.
4627            if (pri != null) {
4628                return pri;
4629            }
4630
4631            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4632            // Get the list of preferred activities that handle the intent
4633            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4634            List<PreferredActivity> prefs = pir != null
4635                    ? pir.queryIntent(intent, resolvedType,
4636                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4637                    : null;
4638            if (prefs != null && prefs.size() > 0) {
4639                boolean changed = false;
4640                try {
4641                    // First figure out how good the original match set is.
4642                    // We will only allow preferred activities that came
4643                    // from the same match quality.
4644                    int match = 0;
4645
4646                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4647
4648                    final int N = query.size();
4649                    for (int j=0; j<N; j++) {
4650                        final ResolveInfo ri = query.get(j);
4651                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4652                                + ": 0x" + Integer.toHexString(match));
4653                        if (ri.match > match) {
4654                            match = ri.match;
4655                        }
4656                    }
4657
4658                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4659                            + Integer.toHexString(match));
4660
4661                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4662                    final int M = prefs.size();
4663                    for (int i=0; i<M; i++) {
4664                        final PreferredActivity pa = prefs.get(i);
4665                        if (DEBUG_PREFERRED || debug) {
4666                            Slog.v(TAG, "Checking PreferredActivity ds="
4667                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4668                                    + "\n  component=" + pa.mPref.mComponent);
4669                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4670                        }
4671                        if (pa.mPref.mMatch != match) {
4672                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4673                                    + Integer.toHexString(pa.mPref.mMatch));
4674                            continue;
4675                        }
4676                        // If it's not an "always" type preferred activity and that's what we're
4677                        // looking for, skip it.
4678                        if (always && !pa.mPref.mAlways) {
4679                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4680                            continue;
4681                        }
4682                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4683                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4684                        if (DEBUG_PREFERRED || debug) {
4685                            Slog.v(TAG, "Found preferred activity:");
4686                            if (ai != null) {
4687                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4688                            } else {
4689                                Slog.v(TAG, "  null");
4690                            }
4691                        }
4692                        if (ai == null) {
4693                            // This previously registered preferred activity
4694                            // component is no longer known.  Most likely an update
4695                            // to the app was installed and in the new version this
4696                            // component no longer exists.  Clean it up by removing
4697                            // it from the preferred activities list, and skip it.
4698                            Slog.w(TAG, "Removing dangling preferred activity: "
4699                                    + pa.mPref.mComponent);
4700                            pir.removeFilter(pa);
4701                            changed = true;
4702                            continue;
4703                        }
4704                        for (int j=0; j<N; j++) {
4705                            final ResolveInfo ri = query.get(j);
4706                            if (!ri.activityInfo.applicationInfo.packageName
4707                                    .equals(ai.applicationInfo.packageName)) {
4708                                continue;
4709                            }
4710                            if (!ri.activityInfo.name.equals(ai.name)) {
4711                                continue;
4712                            }
4713
4714                            if (removeMatches) {
4715                                pir.removeFilter(pa);
4716                                changed = true;
4717                                if (DEBUG_PREFERRED) {
4718                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4719                                }
4720                                break;
4721                            }
4722
4723                            // Okay we found a previously set preferred or last chosen app.
4724                            // If the result set is different from when this
4725                            // was created, we need to clear it and re-ask the
4726                            // user their preference, if we're looking for an "always" type entry.
4727                            if (always && !pa.mPref.sameSet(query)) {
4728                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4729                                        + intent + " type " + resolvedType);
4730                                if (DEBUG_PREFERRED) {
4731                                    Slog.v(TAG, "Removing preferred activity since set changed "
4732                                            + pa.mPref.mComponent);
4733                                }
4734                                pir.removeFilter(pa);
4735                                // Re-add the filter as a "last chosen" entry (!always)
4736                                PreferredActivity lastChosen = new PreferredActivity(
4737                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4738                                pir.addFilter(lastChosen);
4739                                changed = true;
4740                                return null;
4741                            }
4742
4743                            // Yay! Either the set matched or we're looking for the last chosen
4744                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4745                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4746                            return ri;
4747                        }
4748                    }
4749                } finally {
4750                    if (changed) {
4751                        if (DEBUG_PREFERRED) {
4752                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4753                        }
4754                        scheduleWritePackageRestrictionsLocked(userId);
4755                    }
4756                }
4757            }
4758        }
4759        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4760        return null;
4761    }
4762
4763    /*
4764     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4765     */
4766    @Override
4767    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4768            int targetUserId) {
4769        mContext.enforceCallingOrSelfPermission(
4770                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4771        List<CrossProfileIntentFilter> matches =
4772                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4773        if (matches != null) {
4774            int size = matches.size();
4775            for (int i = 0; i < size; i++) {
4776                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4777            }
4778        }
4779        if (hasWebURI(intent)) {
4780            // cross-profile app linking works only towards the parent.
4781            final UserInfo parent = getProfileParent(sourceUserId);
4782            synchronized(mPackages) {
4783                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4784                        intent, resolvedType, 0, sourceUserId, parent.id);
4785                return xpDomainInfo != null;
4786            }
4787        }
4788        return false;
4789    }
4790
4791    private UserInfo getProfileParent(int userId) {
4792        final long identity = Binder.clearCallingIdentity();
4793        try {
4794            return sUserManager.getProfileParent(userId);
4795        } finally {
4796            Binder.restoreCallingIdentity(identity);
4797        }
4798    }
4799
4800    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4801            String resolvedType, int userId) {
4802        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4803        if (resolver != null) {
4804            return resolver.queryIntent(intent, resolvedType, false, userId);
4805        }
4806        return null;
4807    }
4808
4809    @Override
4810    public List<ResolveInfo> queryIntentActivities(Intent intent,
4811            String resolvedType, int flags, int userId) {
4812        if (!sUserManager.exists(userId)) return Collections.emptyList();
4813        flags = augmentFlagsForUser(flags, userId);
4814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4815        ComponentName comp = intent.getComponent();
4816        if (comp == null) {
4817            if (intent.getSelector() != null) {
4818                intent = intent.getSelector();
4819                comp = intent.getComponent();
4820            }
4821        }
4822
4823        if (comp != null) {
4824            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4825            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4826            if (ai != null) {
4827                final ResolveInfo ri = new ResolveInfo();
4828                ri.activityInfo = ai;
4829                list.add(ri);
4830            }
4831            return list;
4832        }
4833
4834        // reader
4835        synchronized (mPackages) {
4836            final String pkgName = intent.getPackage();
4837            if (pkgName == null) {
4838                List<CrossProfileIntentFilter> matchingFilters =
4839                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4840                // Check for results that need to skip the current profile.
4841                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4842                        resolvedType, flags, userId);
4843                if (xpResolveInfo != null) {
4844                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4845                    result.add(xpResolveInfo);
4846                    return filterIfNotSystemUser(result, userId);
4847                }
4848
4849                // Check for results in the current profile.
4850                List<ResolveInfo> result = mActivities.queryIntent(
4851                        intent, resolvedType, flags, userId);
4852
4853                // Check for cross profile results.
4854                xpResolveInfo = queryCrossProfileIntents(
4855                        matchingFilters, intent, resolvedType, flags, userId);
4856                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4857                    result.add(xpResolveInfo);
4858                    Collections.sort(result, mResolvePrioritySorter);
4859                }
4860                result = filterIfNotSystemUser(result, userId);
4861                if (hasWebURI(intent)) {
4862                    CrossProfileDomainInfo xpDomainInfo = null;
4863                    final UserInfo parent = getProfileParent(userId);
4864                    if (parent != null) {
4865                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4866                                flags, userId, parent.id);
4867                    }
4868                    if (xpDomainInfo != null) {
4869                        if (xpResolveInfo != null) {
4870                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4871                            // in the result.
4872                            result.remove(xpResolveInfo);
4873                        }
4874                        if (result.size() == 0) {
4875                            result.add(xpDomainInfo.resolveInfo);
4876                            return result;
4877                        }
4878                    } else if (result.size() <= 1) {
4879                        return result;
4880                    }
4881                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4882                            xpDomainInfo, userId);
4883                    Collections.sort(result, mResolvePrioritySorter);
4884                }
4885                return result;
4886            }
4887            final PackageParser.Package pkg = mPackages.get(pkgName);
4888            if (pkg != null) {
4889                return filterIfNotSystemUser(
4890                        mActivities.queryIntentForPackage(
4891                                intent, resolvedType, flags, pkg.activities, userId),
4892                        userId);
4893            }
4894            return new ArrayList<ResolveInfo>();
4895        }
4896    }
4897
4898    private static class CrossProfileDomainInfo {
4899        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4900        ResolveInfo resolveInfo;
4901        /* Best domain verification status of the activities found in the other profile */
4902        int bestDomainVerificationStatus;
4903    }
4904
4905    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4906            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4907        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4908                sourceUserId)) {
4909            return null;
4910        }
4911        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4912                resolvedType, flags, parentUserId);
4913
4914        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4915            return null;
4916        }
4917        CrossProfileDomainInfo result = null;
4918        int size = resultTargetUser.size();
4919        for (int i = 0; i < size; i++) {
4920            ResolveInfo riTargetUser = resultTargetUser.get(i);
4921            // Intent filter verification is only for filters that specify a host. So don't return
4922            // those that handle all web uris.
4923            if (riTargetUser.handleAllWebDataURI) {
4924                continue;
4925            }
4926            String packageName = riTargetUser.activityInfo.packageName;
4927            PackageSetting ps = mSettings.mPackages.get(packageName);
4928            if (ps == null) {
4929                continue;
4930            }
4931            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4932            int status = (int)(verificationState >> 32);
4933            if (result == null) {
4934                result = new CrossProfileDomainInfo();
4935                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4936                        sourceUserId, parentUserId);
4937                result.bestDomainVerificationStatus = status;
4938            } else {
4939                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4940                        result.bestDomainVerificationStatus);
4941            }
4942        }
4943        // Don't consider matches with status NEVER across profiles.
4944        if (result != null && result.bestDomainVerificationStatus
4945                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4946            return null;
4947        }
4948        return result;
4949    }
4950
4951    /**
4952     * Verification statuses are ordered from the worse to the best, except for
4953     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4954     */
4955    private int bestDomainVerificationStatus(int status1, int status2) {
4956        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4957            return status2;
4958        }
4959        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4960            return status1;
4961        }
4962        return (int) MathUtils.max(status1, status2);
4963    }
4964
4965    private boolean isUserEnabled(int userId) {
4966        long callingId = Binder.clearCallingIdentity();
4967        try {
4968            UserInfo userInfo = sUserManager.getUserInfo(userId);
4969            return userInfo != null && userInfo.isEnabled();
4970        } finally {
4971            Binder.restoreCallingIdentity(callingId);
4972        }
4973    }
4974
4975    /**
4976     * Filter out activities with systemUserOnly flag set, when current user is not System.
4977     *
4978     * @return filtered list
4979     */
4980    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4981        if (userId == UserHandle.USER_SYSTEM) {
4982            return resolveInfos;
4983        }
4984        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4985            ResolveInfo info = resolveInfos.get(i);
4986            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4987                resolveInfos.remove(i);
4988            }
4989        }
4990        return resolveInfos;
4991    }
4992
4993    private static boolean hasWebURI(Intent intent) {
4994        if (intent.getData() == null) {
4995            return false;
4996        }
4997        final String scheme = intent.getScheme();
4998        if (TextUtils.isEmpty(scheme)) {
4999            return false;
5000        }
5001        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5002    }
5003
5004    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5005            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5006            int userId) {
5007        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5008
5009        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5010            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5011                    candidates.size());
5012        }
5013
5014        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5015        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5016        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5017        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5018        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5019        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5020
5021        synchronized (mPackages) {
5022            final int count = candidates.size();
5023            // First, try to use linked apps. Partition the candidates into four lists:
5024            // one for the final results, one for the "do not use ever", one for "undefined status"
5025            // and finally one for "browser app type".
5026            for (int n=0; n<count; n++) {
5027                ResolveInfo info = candidates.get(n);
5028                String packageName = info.activityInfo.packageName;
5029                PackageSetting ps = mSettings.mPackages.get(packageName);
5030                if (ps != null) {
5031                    // Add to the special match all list (Browser use case)
5032                    if (info.handleAllWebDataURI) {
5033                        matchAllList.add(info);
5034                        continue;
5035                    }
5036                    // Try to get the status from User settings first
5037                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5038                    int status = (int)(packedStatus >> 32);
5039                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5040                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5041                        if (DEBUG_DOMAIN_VERIFICATION) {
5042                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5043                                    + " : linkgen=" + linkGeneration);
5044                        }
5045                        // Use link-enabled generation as preferredOrder, i.e.
5046                        // prefer newly-enabled over earlier-enabled.
5047                        info.preferredOrder = linkGeneration;
5048                        alwaysList.add(info);
5049                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5050                        if (DEBUG_DOMAIN_VERIFICATION) {
5051                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5052                        }
5053                        neverList.add(info);
5054                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5055                        if (DEBUG_DOMAIN_VERIFICATION) {
5056                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5057                        }
5058                        alwaysAskList.add(info);
5059                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5060                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5061                        if (DEBUG_DOMAIN_VERIFICATION) {
5062                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5063                        }
5064                        undefinedList.add(info);
5065                    }
5066                }
5067            }
5068
5069            // We'll want to include browser possibilities in a few cases
5070            boolean includeBrowser = false;
5071
5072            // First try to add the "always" resolution(s) for the current user, if any
5073            if (alwaysList.size() > 0) {
5074                result.addAll(alwaysList);
5075            } else {
5076                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5077                result.addAll(undefinedList);
5078                // Maybe add one for the other profile.
5079                if (xpDomainInfo != null && (
5080                        xpDomainInfo.bestDomainVerificationStatus
5081                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5082                    result.add(xpDomainInfo.resolveInfo);
5083                }
5084                includeBrowser = true;
5085            }
5086
5087            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5088            // If there were 'always' entries their preferred order has been set, so we also
5089            // back that off to make the alternatives equivalent
5090            if (alwaysAskList.size() > 0) {
5091                for (ResolveInfo i : result) {
5092                    i.preferredOrder = 0;
5093                }
5094                result.addAll(alwaysAskList);
5095                includeBrowser = true;
5096            }
5097
5098            if (includeBrowser) {
5099                // Also add browsers (all of them or only the default one)
5100                if (DEBUG_DOMAIN_VERIFICATION) {
5101                    Slog.v(TAG, "   ...including browsers in candidate set");
5102                }
5103                if ((matchFlags & MATCH_ALL) != 0) {
5104                    result.addAll(matchAllList);
5105                } else {
5106                    // Browser/generic handling case.  If there's a default browser, go straight
5107                    // to that (but only if there is no other higher-priority match).
5108                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5109                    int maxMatchPrio = 0;
5110                    ResolveInfo defaultBrowserMatch = null;
5111                    final int numCandidates = matchAllList.size();
5112                    for (int n = 0; n < numCandidates; n++) {
5113                        ResolveInfo info = matchAllList.get(n);
5114                        // track the highest overall match priority...
5115                        if (info.priority > maxMatchPrio) {
5116                            maxMatchPrio = info.priority;
5117                        }
5118                        // ...and the highest-priority default browser match
5119                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5120                            if (defaultBrowserMatch == null
5121                                    || (defaultBrowserMatch.priority < info.priority)) {
5122                                if (debug) {
5123                                    Slog.v(TAG, "Considering default browser match " + info);
5124                                }
5125                                defaultBrowserMatch = info;
5126                            }
5127                        }
5128                    }
5129                    if (defaultBrowserMatch != null
5130                            && defaultBrowserMatch.priority >= maxMatchPrio
5131                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5132                    {
5133                        if (debug) {
5134                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5135                        }
5136                        result.add(defaultBrowserMatch);
5137                    } else {
5138                        result.addAll(matchAllList);
5139                    }
5140                }
5141
5142                // If there is nothing selected, add all candidates and remove the ones that the user
5143                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5144                if (result.size() == 0) {
5145                    result.addAll(candidates);
5146                    result.removeAll(neverList);
5147                }
5148            }
5149        }
5150        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5151            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5152                    result.size());
5153            for (ResolveInfo info : result) {
5154                Slog.v(TAG, "  + " + info.activityInfo);
5155            }
5156        }
5157        return result;
5158    }
5159
5160    // Returns a packed value as a long:
5161    //
5162    // high 'int'-sized word: link status: undefined/ask/never/always.
5163    // low 'int'-sized word: relative priority among 'always' results.
5164    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5165        long result = ps.getDomainVerificationStatusForUser(userId);
5166        // if none available, get the master status
5167        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5168            if (ps.getIntentFilterVerificationInfo() != null) {
5169                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5170            }
5171        }
5172        return result;
5173    }
5174
5175    private ResolveInfo querySkipCurrentProfileIntents(
5176            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5177            int flags, int sourceUserId) {
5178        if (matchingFilters != null) {
5179            int size = matchingFilters.size();
5180            for (int i = 0; i < size; i ++) {
5181                CrossProfileIntentFilter filter = matchingFilters.get(i);
5182                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5183                    // Checking if there are activities in the target user that can handle the
5184                    // intent.
5185                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5186                            resolvedType, flags, sourceUserId);
5187                    if (resolveInfo != null) {
5188                        return resolveInfo;
5189                    }
5190                }
5191            }
5192        }
5193        return null;
5194    }
5195
5196    // Return matching ResolveInfo if any for skip current profile intent filters.
5197    private ResolveInfo queryCrossProfileIntents(
5198            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5199            int flags, int sourceUserId) {
5200        if (matchingFilters != null) {
5201            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5202            // match the same intent. For performance reasons, it is better not to
5203            // run queryIntent twice for the same userId
5204            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5205            int size = matchingFilters.size();
5206            for (int i = 0; i < size; i++) {
5207                CrossProfileIntentFilter filter = matchingFilters.get(i);
5208                int targetUserId = filter.getTargetUserId();
5209                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
5210                        && !alreadyTriedUserIds.get(targetUserId)) {
5211                    // Checking if there are activities in the target user that can handle the
5212                    // intent.
5213                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5214                            resolvedType, flags, sourceUserId);
5215                    if (resolveInfo != null) return resolveInfo;
5216                    alreadyTriedUserIds.put(targetUserId, true);
5217                }
5218            }
5219        }
5220        return null;
5221    }
5222
5223    /**
5224     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5225     * will forward the intent to the filter's target user.
5226     * Otherwise, returns null.
5227     */
5228    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5229            String resolvedType, int flags, int sourceUserId) {
5230        int targetUserId = filter.getTargetUserId();
5231        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5232                resolvedType, flags, targetUserId);
5233        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5234                && isUserEnabled(targetUserId)) {
5235            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5236        }
5237        return null;
5238    }
5239
5240    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5241            int sourceUserId, int targetUserId) {
5242        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5243        long ident = Binder.clearCallingIdentity();
5244        boolean targetIsProfile;
5245        try {
5246            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5247        } finally {
5248            Binder.restoreCallingIdentity(ident);
5249        }
5250        String className;
5251        if (targetIsProfile) {
5252            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5253        } else {
5254            className = FORWARD_INTENT_TO_PARENT;
5255        }
5256        ComponentName forwardingActivityComponentName = new ComponentName(
5257                mAndroidApplication.packageName, className);
5258        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5259                sourceUserId);
5260        if (!targetIsProfile) {
5261            forwardingActivityInfo.showUserIcon = targetUserId;
5262            forwardingResolveInfo.noResourceId = true;
5263        }
5264        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5265        forwardingResolveInfo.priority = 0;
5266        forwardingResolveInfo.preferredOrder = 0;
5267        forwardingResolveInfo.match = 0;
5268        forwardingResolveInfo.isDefault = true;
5269        forwardingResolveInfo.filter = filter;
5270        forwardingResolveInfo.targetUserId = targetUserId;
5271        return forwardingResolveInfo;
5272    }
5273
5274    @Override
5275    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5276            Intent[] specifics, String[] specificTypes, Intent intent,
5277            String resolvedType, int flags, int userId) {
5278        if (!sUserManager.exists(userId)) return Collections.emptyList();
5279        flags = augmentFlagsForUser(flags, userId);
5280        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5281                false, "query intent activity options");
5282        final String resultsAction = intent.getAction();
5283
5284        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5285                | PackageManager.GET_RESOLVED_FILTER, userId);
5286
5287        if (DEBUG_INTENT_MATCHING) {
5288            Log.v(TAG, "Query " + intent + ": " + results);
5289        }
5290
5291        int specificsPos = 0;
5292        int N;
5293
5294        // todo: note that the algorithm used here is O(N^2).  This
5295        // isn't a problem in our current environment, but if we start running
5296        // into situations where we have more than 5 or 10 matches then this
5297        // should probably be changed to something smarter...
5298
5299        // First we go through and resolve each of the specific items
5300        // that were supplied, taking care of removing any corresponding
5301        // duplicate items in the generic resolve list.
5302        if (specifics != null) {
5303            for (int i=0; i<specifics.length; i++) {
5304                final Intent sintent = specifics[i];
5305                if (sintent == null) {
5306                    continue;
5307                }
5308
5309                if (DEBUG_INTENT_MATCHING) {
5310                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5311                }
5312
5313                String action = sintent.getAction();
5314                if (resultsAction != null && resultsAction.equals(action)) {
5315                    // If this action was explicitly requested, then don't
5316                    // remove things that have it.
5317                    action = null;
5318                }
5319
5320                ResolveInfo ri = null;
5321                ActivityInfo ai = null;
5322
5323                ComponentName comp = sintent.getComponent();
5324                if (comp == null) {
5325                    ri = resolveIntent(
5326                        sintent,
5327                        specificTypes != null ? specificTypes[i] : null,
5328                            flags, userId);
5329                    if (ri == null) {
5330                        continue;
5331                    }
5332                    if (ri == mResolveInfo) {
5333                        // ACK!  Must do something better with this.
5334                    }
5335                    ai = ri.activityInfo;
5336                    comp = new ComponentName(ai.applicationInfo.packageName,
5337                            ai.name);
5338                } else {
5339                    ai = getActivityInfo(comp, flags, userId);
5340                    if (ai == null) {
5341                        continue;
5342                    }
5343                }
5344
5345                // Look for any generic query activities that are duplicates
5346                // of this specific one, and remove them from the results.
5347                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5348                N = results.size();
5349                int j;
5350                for (j=specificsPos; j<N; j++) {
5351                    ResolveInfo sri = results.get(j);
5352                    if ((sri.activityInfo.name.equals(comp.getClassName())
5353                            && sri.activityInfo.applicationInfo.packageName.equals(
5354                                    comp.getPackageName()))
5355                        || (action != null && sri.filter.matchAction(action))) {
5356                        results.remove(j);
5357                        if (DEBUG_INTENT_MATCHING) Log.v(
5358                            TAG, "Removing duplicate item from " + j
5359                            + " due to specific " + specificsPos);
5360                        if (ri == null) {
5361                            ri = sri;
5362                        }
5363                        j--;
5364                        N--;
5365                    }
5366                }
5367
5368                // Add this specific item to its proper place.
5369                if (ri == null) {
5370                    ri = new ResolveInfo();
5371                    ri.activityInfo = ai;
5372                }
5373                results.add(specificsPos, ri);
5374                ri.specificIndex = i;
5375                specificsPos++;
5376            }
5377        }
5378
5379        // Now we go through the remaining generic results and remove any
5380        // duplicate actions that are found here.
5381        N = results.size();
5382        for (int i=specificsPos; i<N-1; i++) {
5383            final ResolveInfo rii = results.get(i);
5384            if (rii.filter == null) {
5385                continue;
5386            }
5387
5388            // Iterate over all of the actions of this result's intent
5389            // filter...  typically this should be just one.
5390            final Iterator<String> it = rii.filter.actionsIterator();
5391            if (it == null) {
5392                continue;
5393            }
5394            while (it.hasNext()) {
5395                final String action = it.next();
5396                if (resultsAction != null && resultsAction.equals(action)) {
5397                    // If this action was explicitly requested, then don't
5398                    // remove things that have it.
5399                    continue;
5400                }
5401                for (int j=i+1; j<N; j++) {
5402                    final ResolveInfo rij = results.get(j);
5403                    if (rij.filter != null && rij.filter.hasAction(action)) {
5404                        results.remove(j);
5405                        if (DEBUG_INTENT_MATCHING) Log.v(
5406                            TAG, "Removing duplicate item from " + j
5407                            + " due to action " + action + " at " + i);
5408                        j--;
5409                        N--;
5410                    }
5411                }
5412            }
5413
5414            // If the caller didn't request filter information, drop it now
5415            // so we don't have to marshall/unmarshall it.
5416            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5417                rii.filter = null;
5418            }
5419        }
5420
5421        // Filter out the caller activity if so requested.
5422        if (caller != null) {
5423            N = results.size();
5424            for (int i=0; i<N; i++) {
5425                ActivityInfo ainfo = results.get(i).activityInfo;
5426                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5427                        && caller.getClassName().equals(ainfo.name)) {
5428                    results.remove(i);
5429                    break;
5430                }
5431            }
5432        }
5433
5434        // If the caller didn't request filter information,
5435        // drop them now so we don't have to
5436        // marshall/unmarshall it.
5437        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5438            N = results.size();
5439            for (int i=0; i<N; i++) {
5440                results.get(i).filter = null;
5441            }
5442        }
5443
5444        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5445        return results;
5446    }
5447
5448    @Override
5449    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5450            int userId) {
5451        if (!sUserManager.exists(userId)) return Collections.emptyList();
5452        flags = augmentFlagsForUser(flags, userId);
5453        ComponentName comp = intent.getComponent();
5454        if (comp == null) {
5455            if (intent.getSelector() != null) {
5456                intent = intent.getSelector();
5457                comp = intent.getComponent();
5458            }
5459        }
5460        if (comp != null) {
5461            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5462            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5463            if (ai != null) {
5464                ResolveInfo ri = new ResolveInfo();
5465                ri.activityInfo = ai;
5466                list.add(ri);
5467            }
5468            return list;
5469        }
5470
5471        // reader
5472        synchronized (mPackages) {
5473            String pkgName = intent.getPackage();
5474            if (pkgName == null) {
5475                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5476            }
5477            final PackageParser.Package pkg = mPackages.get(pkgName);
5478            if (pkg != null) {
5479                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5480                        userId);
5481            }
5482            return null;
5483        }
5484    }
5485
5486    @Override
5487    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5488        if (!sUserManager.exists(userId)) return null;
5489        flags = augmentFlagsForUser(flags, userId);
5490        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5491        if (query != null) {
5492            if (query.size() >= 1) {
5493                // If there is more than one service with the same priority,
5494                // just arbitrarily pick the first one.
5495                return query.get(0);
5496            }
5497        }
5498        return null;
5499    }
5500
5501    @Override
5502    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5503            int userId) {
5504        if (!sUserManager.exists(userId)) return Collections.emptyList();
5505        flags = augmentFlagsForUser(flags, userId);
5506        ComponentName comp = intent.getComponent();
5507        if (comp == null) {
5508            if (intent.getSelector() != null) {
5509                intent = intent.getSelector();
5510                comp = intent.getComponent();
5511            }
5512        }
5513        if (comp != null) {
5514            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5515            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5516            if (si != null) {
5517                final ResolveInfo ri = new ResolveInfo();
5518                ri.serviceInfo = si;
5519                list.add(ri);
5520            }
5521            return list;
5522        }
5523
5524        // reader
5525        synchronized (mPackages) {
5526            String pkgName = intent.getPackage();
5527            if (pkgName == null) {
5528                return mServices.queryIntent(intent, resolvedType, flags, userId);
5529            }
5530            final PackageParser.Package pkg = mPackages.get(pkgName);
5531            if (pkg != null) {
5532                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5533                        userId);
5534            }
5535            return null;
5536        }
5537    }
5538
5539    @Override
5540    public List<ResolveInfo> queryIntentContentProviders(
5541            Intent intent, String resolvedType, int flags, int userId) {
5542        if (!sUserManager.exists(userId)) return Collections.emptyList();
5543        flags = augmentFlagsForUser(flags, userId);
5544        ComponentName comp = intent.getComponent();
5545        if (comp == null) {
5546            if (intent.getSelector() != null) {
5547                intent = intent.getSelector();
5548                comp = intent.getComponent();
5549            }
5550        }
5551        if (comp != null) {
5552            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5553            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5554            if (pi != null) {
5555                final ResolveInfo ri = new ResolveInfo();
5556                ri.providerInfo = pi;
5557                list.add(ri);
5558            }
5559            return list;
5560        }
5561
5562        // reader
5563        synchronized (mPackages) {
5564            String pkgName = intent.getPackage();
5565            if (pkgName == null) {
5566                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5567            }
5568            final PackageParser.Package pkg = mPackages.get(pkgName);
5569            if (pkg != null) {
5570                return mProviders.queryIntentForPackage(
5571                        intent, resolvedType, flags, pkg.providers, userId);
5572            }
5573            return null;
5574        }
5575    }
5576
5577    @Override
5578    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5579        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5580
5581        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5582
5583        // writer
5584        synchronized (mPackages) {
5585            ArrayList<PackageInfo> list;
5586            if (listUninstalled) {
5587                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5588                for (PackageSetting ps : mSettings.mPackages.values()) {
5589                    PackageInfo pi;
5590                    if (ps.pkg != null) {
5591                        pi = generatePackageInfo(ps.pkg, flags, userId);
5592                    } else {
5593                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5594                    }
5595                    if (pi != null) {
5596                        list.add(pi);
5597                    }
5598                }
5599            } else {
5600                list = new ArrayList<PackageInfo>(mPackages.size());
5601                for (PackageParser.Package p : mPackages.values()) {
5602                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5603                    if (pi != null) {
5604                        list.add(pi);
5605                    }
5606                }
5607            }
5608
5609            return new ParceledListSlice<PackageInfo>(list);
5610        }
5611    }
5612
5613    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5614            String[] permissions, boolean[] tmp, int flags, int userId) {
5615        int numMatch = 0;
5616        final PermissionsState permissionsState = ps.getPermissionsState();
5617        for (int i=0; i<permissions.length; i++) {
5618            final String permission = permissions[i];
5619            if (permissionsState.hasPermission(permission, userId)) {
5620                tmp[i] = true;
5621                numMatch++;
5622            } else {
5623                tmp[i] = false;
5624            }
5625        }
5626        if (numMatch == 0) {
5627            return;
5628        }
5629        PackageInfo pi;
5630        if (ps.pkg != null) {
5631            pi = generatePackageInfo(ps.pkg, flags, userId);
5632        } else {
5633            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5634        }
5635        // The above might return null in cases of uninstalled apps or install-state
5636        // skew across users/profiles.
5637        if (pi != null) {
5638            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5639                if (numMatch == permissions.length) {
5640                    pi.requestedPermissions = permissions;
5641                } else {
5642                    pi.requestedPermissions = new String[numMatch];
5643                    numMatch = 0;
5644                    for (int i=0; i<permissions.length; i++) {
5645                        if (tmp[i]) {
5646                            pi.requestedPermissions[numMatch] = permissions[i];
5647                            numMatch++;
5648                        }
5649                    }
5650                }
5651            }
5652            list.add(pi);
5653        }
5654    }
5655
5656    @Override
5657    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5658            String[] permissions, int flags, int userId) {
5659        if (!sUserManager.exists(userId)) return null;
5660        flags = augmentFlagsForUser(flags, userId);
5661        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5662
5663        // writer
5664        synchronized (mPackages) {
5665            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5666            boolean[] tmpBools = new boolean[permissions.length];
5667            if (listUninstalled) {
5668                for (PackageSetting ps : mSettings.mPackages.values()) {
5669                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5670                }
5671            } else {
5672                for (PackageParser.Package pkg : mPackages.values()) {
5673                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5674                    if (ps != null) {
5675                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5676                                userId);
5677                    }
5678                }
5679            }
5680
5681            return new ParceledListSlice<PackageInfo>(list);
5682        }
5683    }
5684
5685    @Override
5686    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5687        if (!sUserManager.exists(userId)) return null;
5688        flags = augmentFlagsForUser(flags, userId);
5689        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5690
5691        // writer
5692        synchronized (mPackages) {
5693            ArrayList<ApplicationInfo> list;
5694            if (listUninstalled) {
5695                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5696                for (PackageSetting ps : mSettings.mPackages.values()) {
5697                    ApplicationInfo ai;
5698                    if (ps.pkg != null) {
5699                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5700                                ps.readUserState(userId), userId);
5701                    } else {
5702                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5703                    }
5704                    if (ai != null) {
5705                        list.add(ai);
5706                    }
5707                }
5708            } else {
5709                list = new ArrayList<ApplicationInfo>(mPackages.size());
5710                for (PackageParser.Package p : mPackages.values()) {
5711                    if (p.mExtras != null) {
5712                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5713                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5714                        if (ai != null) {
5715                            list.add(ai);
5716                        }
5717                    }
5718                }
5719            }
5720
5721            return new ParceledListSlice<ApplicationInfo>(list);
5722        }
5723    }
5724
5725    public List<ApplicationInfo> getPersistentApplications(int flags) {
5726        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5727
5728        // reader
5729        synchronized (mPackages) {
5730            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5731            final int userId = UserHandle.getCallingUserId();
5732            while (i.hasNext()) {
5733                final PackageParser.Package p = i.next();
5734                if (p.applicationInfo != null
5735                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5736                        && (!mSafeMode || isSystemApp(p))) {
5737                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5738                    if (ps != null) {
5739                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5740                                ps.readUserState(userId), userId);
5741                        if (ai != null) {
5742                            finalList.add(ai);
5743                        }
5744                    }
5745                }
5746            }
5747        }
5748
5749        return finalList;
5750    }
5751
5752    @Override
5753    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5754        if (!sUserManager.exists(userId)) return null;
5755        flags = augmentFlagsForUser(flags, userId);
5756        // reader
5757        synchronized (mPackages) {
5758            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5759            PackageSetting ps = provider != null
5760                    ? mSettings.mPackages.get(provider.owner.packageName)
5761                    : null;
5762            return ps != null
5763                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5764                    && (!mSafeMode || (provider.info.applicationInfo.flags
5765                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5766                    ? PackageParser.generateProviderInfo(provider, flags,
5767                            ps.readUserState(userId), userId)
5768                    : null;
5769        }
5770    }
5771
5772    /**
5773     * @deprecated
5774     */
5775    @Deprecated
5776    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5777        // reader
5778        synchronized (mPackages) {
5779            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5780                    .entrySet().iterator();
5781            final int userId = UserHandle.getCallingUserId();
5782            while (i.hasNext()) {
5783                Map.Entry<String, PackageParser.Provider> entry = i.next();
5784                PackageParser.Provider p = entry.getValue();
5785                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5786
5787                if (ps != null && p.syncable
5788                        && (!mSafeMode || (p.info.applicationInfo.flags
5789                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5790                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5791                            ps.readUserState(userId), userId);
5792                    if (info != null) {
5793                        outNames.add(entry.getKey());
5794                        outInfo.add(info);
5795                    }
5796                }
5797            }
5798        }
5799    }
5800
5801    @Override
5802    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5803            int uid, int flags) {
5804        final int userId = processName != null ? UserHandle.getUserId(uid)
5805                : UserHandle.getCallingUserId();
5806        if (!sUserManager.exists(userId)) return null;
5807        flags = augmentFlagsForUser(flags, userId);
5808
5809        ArrayList<ProviderInfo> finalList = null;
5810        // reader
5811        synchronized (mPackages) {
5812            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5813            while (i.hasNext()) {
5814                final PackageParser.Provider p = i.next();
5815                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5816                if (ps != null && p.info.authority != null
5817                        && (processName == null
5818                                || (p.info.processName.equals(processName)
5819                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5820                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5821                        && (!mSafeMode
5822                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5823                    if (finalList == null) {
5824                        finalList = new ArrayList<ProviderInfo>(3);
5825                    }
5826                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5827                            ps.readUserState(userId), userId);
5828                    if (info != null) {
5829                        finalList.add(info);
5830                    }
5831                }
5832            }
5833        }
5834
5835        if (finalList != null) {
5836            Collections.sort(finalList, mProviderInitOrderSorter);
5837            return new ParceledListSlice<ProviderInfo>(finalList);
5838        }
5839
5840        return null;
5841    }
5842
5843    @Override
5844    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5845            int flags) {
5846        // reader
5847        synchronized (mPackages) {
5848            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5849            return PackageParser.generateInstrumentationInfo(i, flags);
5850        }
5851    }
5852
5853    @Override
5854    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5855            int flags) {
5856        ArrayList<InstrumentationInfo> finalList =
5857            new ArrayList<InstrumentationInfo>();
5858
5859        // reader
5860        synchronized (mPackages) {
5861            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5862            while (i.hasNext()) {
5863                final PackageParser.Instrumentation p = i.next();
5864                if (targetPackage == null
5865                        || targetPackage.equals(p.info.targetPackage)) {
5866                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5867                            flags);
5868                    if (ii != null) {
5869                        finalList.add(ii);
5870                    }
5871                }
5872            }
5873        }
5874
5875        return finalList;
5876    }
5877
5878    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5879        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5880        if (overlays == null) {
5881            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5882            return;
5883        }
5884        for (PackageParser.Package opkg : overlays.values()) {
5885            // Not much to do if idmap fails: we already logged the error
5886            // and we certainly don't want to abort installation of pkg simply
5887            // because an overlay didn't fit properly. For these reasons,
5888            // ignore the return value of createIdmapForPackagePairLI.
5889            createIdmapForPackagePairLI(pkg, opkg);
5890        }
5891    }
5892
5893    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5894            PackageParser.Package opkg) {
5895        if (!opkg.mTrustedOverlay) {
5896            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5897                    opkg.baseCodePath + ": overlay not trusted");
5898            return false;
5899        }
5900        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5901        if (overlaySet == null) {
5902            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5903                    opkg.baseCodePath + " but target package has no known overlays");
5904            return false;
5905        }
5906        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5907        // TODO: generate idmap for split APKs
5908        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5909            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5910                    + opkg.baseCodePath);
5911            return false;
5912        }
5913        PackageParser.Package[] overlayArray =
5914            overlaySet.values().toArray(new PackageParser.Package[0]);
5915        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5916            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5917                return p1.mOverlayPriority - p2.mOverlayPriority;
5918            }
5919        };
5920        Arrays.sort(overlayArray, cmp);
5921
5922        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5923        int i = 0;
5924        for (PackageParser.Package p : overlayArray) {
5925            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5926        }
5927        return true;
5928    }
5929
5930    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5931        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5932        try {
5933            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5934        } finally {
5935            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5936        }
5937    }
5938
5939    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5940        final File[] files = dir.listFiles();
5941        if (ArrayUtils.isEmpty(files)) {
5942            Log.d(TAG, "No files in app dir " + dir);
5943            return;
5944        }
5945
5946        if (DEBUG_PACKAGE_SCANNING) {
5947            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5948                    + " flags=0x" + Integer.toHexString(parseFlags));
5949        }
5950
5951        for (File file : files) {
5952            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5953                    && !PackageInstallerService.isStageName(file.getName());
5954            if (!isPackage) {
5955                // Ignore entries which are not packages
5956                continue;
5957            }
5958            try {
5959                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5960                        scanFlags, currentTime, null);
5961            } catch (PackageManagerException e) {
5962                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5963
5964                // Delete invalid userdata apps
5965                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5966                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5967                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5968                    if (file.isDirectory()) {
5969                        mInstaller.rmPackageDir(file.getAbsolutePath());
5970                    } else {
5971                        file.delete();
5972                    }
5973                }
5974            }
5975        }
5976    }
5977
5978    private static File getSettingsProblemFile() {
5979        File dataDir = Environment.getDataDirectory();
5980        File systemDir = new File(dataDir, "system");
5981        File fname = new File(systemDir, "uiderrors.txt");
5982        return fname;
5983    }
5984
5985    static void reportSettingsProblem(int priority, String msg) {
5986        logCriticalInfo(priority, msg);
5987    }
5988
5989    static void logCriticalInfo(int priority, String msg) {
5990        Slog.println(priority, TAG, msg);
5991        EventLogTags.writePmCriticalInfo(msg);
5992        try {
5993            File fname = getSettingsProblemFile();
5994            FileOutputStream out = new FileOutputStream(fname, true);
5995            PrintWriter pw = new FastPrintWriter(out);
5996            SimpleDateFormat formatter = new SimpleDateFormat();
5997            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5998            pw.println(dateString + ": " + msg);
5999            pw.close();
6000            FileUtils.setPermissions(
6001                    fname.toString(),
6002                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6003                    -1, -1);
6004        } catch (java.io.IOException e) {
6005        }
6006    }
6007
6008    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6009            PackageParser.Package pkg, File srcFile, int parseFlags)
6010            throws PackageManagerException {
6011        if (ps != null
6012                && ps.codePath.equals(srcFile)
6013                && ps.timeStamp == srcFile.lastModified()
6014                && !isCompatSignatureUpdateNeeded(pkg)
6015                && !isRecoverSignatureUpdateNeeded(pkg)) {
6016            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6017            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6018            ArraySet<PublicKey> signingKs;
6019            synchronized (mPackages) {
6020                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6021            }
6022            if (ps.signatures.mSignatures != null
6023                    && ps.signatures.mSignatures.length != 0
6024                    && signingKs != null) {
6025                // Optimization: reuse the existing cached certificates
6026                // if the package appears to be unchanged.
6027                pkg.mSignatures = ps.signatures.mSignatures;
6028                pkg.mSigningKeys = signingKs;
6029                return;
6030            }
6031
6032            Slog.w(TAG, "PackageSetting for " + ps.name
6033                    + " is missing signatures.  Collecting certs again to recover them.");
6034        } else {
6035            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6036        }
6037
6038        try {
6039            pp.collectCertificates(pkg, parseFlags);
6040            pp.collectManifestDigest(pkg);
6041        } catch (PackageParserException e) {
6042            throw PackageManagerException.from(e);
6043        }
6044    }
6045
6046    /**
6047     *  Traces a package scan.
6048     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6049     */
6050    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6051            long currentTime, UserHandle user) throws PackageManagerException {
6052        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6053        try {
6054            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6055        } finally {
6056            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6057        }
6058    }
6059
6060    /**
6061     *  Scans a package and returns the newly parsed package.
6062     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6063     */
6064    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6065            long currentTime, UserHandle user) throws PackageManagerException {
6066        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6067        parseFlags |= mDefParseFlags;
6068        PackageParser pp = new PackageParser();
6069        pp.setSeparateProcesses(mSeparateProcesses);
6070        pp.setOnlyCoreApps(mOnlyCore);
6071        pp.setDisplayMetrics(mMetrics);
6072
6073        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6074            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6075        }
6076
6077        final PackageParser.Package pkg;
6078        try {
6079            pkg = pp.parsePackage(scanFile, parseFlags);
6080        } catch (PackageParserException e) {
6081            throw PackageManagerException.from(e);
6082        }
6083
6084        PackageSetting ps = null;
6085        PackageSetting updatedPkg;
6086        // reader
6087        synchronized (mPackages) {
6088            // Look to see if we already know about this package.
6089            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6090            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6091                // This package has been renamed to its original name.  Let's
6092                // use that.
6093                ps = mSettings.peekPackageLPr(oldName);
6094            }
6095            // If there was no original package, see one for the real package name.
6096            if (ps == null) {
6097                ps = mSettings.peekPackageLPr(pkg.packageName);
6098            }
6099            // Check to see if this package could be hiding/updating a system
6100            // package.  Must look for it either under the original or real
6101            // package name depending on our state.
6102            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6103            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6104        }
6105        boolean updatedPkgBetter = false;
6106        // First check if this is a system package that may involve an update
6107        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6108            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6109            // it needs to drop FLAG_PRIVILEGED.
6110            if (locationIsPrivileged(scanFile)) {
6111                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6112            } else {
6113                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6114            }
6115
6116            if (ps != null && !ps.codePath.equals(scanFile)) {
6117                // The path has changed from what was last scanned...  check the
6118                // version of the new path against what we have stored to determine
6119                // what to do.
6120                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6121                if (pkg.mVersionCode <= ps.versionCode) {
6122                    // The system package has been updated and the code path does not match
6123                    // Ignore entry. Skip it.
6124                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6125                            + " ignored: updated version " + ps.versionCode
6126                            + " better than this " + pkg.mVersionCode);
6127                    if (!updatedPkg.codePath.equals(scanFile)) {
6128                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6129                                + ps.name + " changing from " + updatedPkg.codePathString
6130                                + " to " + scanFile);
6131                        updatedPkg.codePath = scanFile;
6132                        updatedPkg.codePathString = scanFile.toString();
6133                        updatedPkg.resourcePath = scanFile;
6134                        updatedPkg.resourcePathString = scanFile.toString();
6135                    }
6136                    updatedPkg.pkg = pkg;
6137                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6138                            "Package " + ps.name + " at " + scanFile
6139                                    + " ignored: updated version " + ps.versionCode
6140                                    + " better than this " + pkg.mVersionCode);
6141                } else {
6142                    // The current app on the system partition is better than
6143                    // what we have updated to on the data partition; switch
6144                    // back to the system partition version.
6145                    // At this point, its safely assumed that package installation for
6146                    // apps in system partition will go through. If not there won't be a working
6147                    // version of the app
6148                    // writer
6149                    synchronized (mPackages) {
6150                        // Just remove the loaded entries from package lists.
6151                        mPackages.remove(ps.name);
6152                    }
6153
6154                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6155                            + " reverting from " + ps.codePathString
6156                            + ": new version " + pkg.mVersionCode
6157                            + " better than installed " + ps.versionCode);
6158
6159                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6160                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6161                    synchronized (mInstallLock) {
6162                        args.cleanUpResourcesLI();
6163                    }
6164                    synchronized (mPackages) {
6165                        mSettings.enableSystemPackageLPw(ps.name);
6166                    }
6167                    updatedPkgBetter = true;
6168                }
6169            }
6170        }
6171
6172        if (updatedPkg != null) {
6173            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6174            // initially
6175            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6176
6177            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6178            // flag set initially
6179            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6180                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6181            }
6182        }
6183
6184        // Verify certificates against what was last scanned
6185        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6186
6187        /*
6188         * A new system app appeared, but we already had a non-system one of the
6189         * same name installed earlier.
6190         */
6191        boolean shouldHideSystemApp = false;
6192        if (updatedPkg == null && ps != null
6193                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6194            /*
6195             * Check to make sure the signatures match first. If they don't,
6196             * wipe the installed application and its data.
6197             */
6198            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6199                    != PackageManager.SIGNATURE_MATCH) {
6200                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6201                        + " signatures don't match existing userdata copy; removing");
6202                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6203                ps = null;
6204            } else {
6205                /*
6206                 * If the newly-added system app is an older version than the
6207                 * already installed version, hide it. It will be scanned later
6208                 * and re-added like an update.
6209                 */
6210                if (pkg.mVersionCode <= ps.versionCode) {
6211                    shouldHideSystemApp = true;
6212                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6213                            + " but new version " + pkg.mVersionCode + " better than installed "
6214                            + ps.versionCode + "; hiding system");
6215                } else {
6216                    /*
6217                     * The newly found system app is a newer version that the
6218                     * one previously installed. Simply remove the
6219                     * already-installed application and replace it with our own
6220                     * while keeping the application data.
6221                     */
6222                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6223                            + " reverting from " + ps.codePathString + ": new version "
6224                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6225                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6226                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6227                    synchronized (mInstallLock) {
6228                        args.cleanUpResourcesLI();
6229                    }
6230                }
6231            }
6232        }
6233
6234        // The apk is forward locked (not public) if its code and resources
6235        // are kept in different files. (except for app in either system or
6236        // vendor path).
6237        // TODO grab this value from PackageSettings
6238        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6239            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6240                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6241            }
6242        }
6243
6244        // TODO: extend to support forward-locked splits
6245        String resourcePath = null;
6246        String baseResourcePath = null;
6247        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6248            if (ps != null && ps.resourcePathString != null) {
6249                resourcePath = ps.resourcePathString;
6250                baseResourcePath = ps.resourcePathString;
6251            } else {
6252                // Should not happen at all. Just log an error.
6253                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6254            }
6255        } else {
6256            resourcePath = pkg.codePath;
6257            baseResourcePath = pkg.baseCodePath;
6258        }
6259
6260        // Set application objects path explicitly.
6261        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6262        pkg.applicationInfo.setCodePath(pkg.codePath);
6263        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6264        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6265        pkg.applicationInfo.setResourcePath(resourcePath);
6266        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6267        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6268
6269        // Note that we invoke the following method only if we are about to unpack an application
6270        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6271                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6272
6273        /*
6274         * If the system app should be overridden by a previously installed
6275         * data, hide the system app now and let the /data/app scan pick it up
6276         * again.
6277         */
6278        if (shouldHideSystemApp) {
6279            synchronized (mPackages) {
6280                mSettings.disableSystemPackageLPw(pkg.packageName);
6281            }
6282        }
6283
6284        return scannedPkg;
6285    }
6286
6287    private static String fixProcessName(String defProcessName,
6288            String processName, int uid) {
6289        if (processName == null) {
6290            return defProcessName;
6291        }
6292        return processName;
6293    }
6294
6295    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6296            throws PackageManagerException {
6297        if (pkgSetting.signatures.mSignatures != null) {
6298            // Already existing package. Make sure signatures match
6299            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6300                    == PackageManager.SIGNATURE_MATCH;
6301            if (!match) {
6302                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6303                        == PackageManager.SIGNATURE_MATCH;
6304            }
6305            if (!match) {
6306                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6307                        == PackageManager.SIGNATURE_MATCH;
6308            }
6309            if (!match) {
6310                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6311                        + pkg.packageName + " signatures do not match the "
6312                        + "previously installed version; ignoring!");
6313            }
6314        }
6315
6316        // Check for shared user signatures
6317        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6318            // Already existing package. Make sure signatures match
6319            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6320                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6321            if (!match) {
6322                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6323                        == PackageManager.SIGNATURE_MATCH;
6324            }
6325            if (!match) {
6326                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6327                        == PackageManager.SIGNATURE_MATCH;
6328            }
6329            if (!match) {
6330                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6331                        "Package " + pkg.packageName
6332                        + " has no signatures that match those in shared user "
6333                        + pkgSetting.sharedUser.name + "; ignoring!");
6334            }
6335        }
6336    }
6337
6338    /**
6339     * Enforces that only the system UID or root's UID can call a method exposed
6340     * via Binder.
6341     *
6342     * @param message used as message if SecurityException is thrown
6343     * @throws SecurityException if the caller is not system or root
6344     */
6345    private static final void enforceSystemOrRoot(String message) {
6346        final int uid = Binder.getCallingUid();
6347        if (uid != Process.SYSTEM_UID && uid != 0) {
6348            throw new SecurityException(message);
6349        }
6350    }
6351
6352    @Override
6353    public void performFstrimIfNeeded() {
6354        enforceSystemOrRoot("Only the system can request fstrim");
6355
6356        // Before everything else, see whether we need to fstrim.
6357        try {
6358            IMountService ms = PackageHelper.getMountService();
6359            if (ms != null) {
6360                final boolean isUpgrade = isUpgrade();
6361                boolean doTrim = isUpgrade;
6362                if (doTrim) {
6363                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6364                } else {
6365                    final long interval = android.provider.Settings.Global.getLong(
6366                            mContext.getContentResolver(),
6367                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6368                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6369                    if (interval > 0) {
6370                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6371                        if (timeSinceLast > interval) {
6372                            doTrim = true;
6373                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6374                                    + "; running immediately");
6375                        }
6376                    }
6377                }
6378                if (doTrim) {
6379                    if (!isFirstBoot()) {
6380                        try {
6381                            ActivityManagerNative.getDefault().showBootMessage(
6382                                    mContext.getResources().getString(
6383                                            R.string.android_upgrading_fstrim), true);
6384                        } catch (RemoteException e) {
6385                        }
6386                    }
6387                    ms.runMaintenance();
6388                }
6389            } else {
6390                Slog.e(TAG, "Mount service unavailable!");
6391            }
6392        } catch (RemoteException e) {
6393            // Can't happen; MountService is local
6394        }
6395    }
6396
6397    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6398        List<ResolveInfo> ris = null;
6399        try {
6400            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6401                    intent, null, 0, userId);
6402        } catch (RemoteException e) {
6403        }
6404        ArraySet<String> pkgNames = new ArraySet<String>();
6405        if (ris != null) {
6406            for (ResolveInfo ri : ris) {
6407                pkgNames.add(ri.activityInfo.packageName);
6408            }
6409        }
6410        return pkgNames;
6411    }
6412
6413    @Override
6414    public void notifyPackageUse(String packageName) {
6415        synchronized (mPackages) {
6416            PackageParser.Package p = mPackages.get(packageName);
6417            if (p == null) {
6418                return;
6419            }
6420            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6421        }
6422    }
6423
6424    @Override
6425    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6426        return performDexOptTraced(packageName, instructionSet);
6427    }
6428
6429    public boolean performDexOpt(String packageName, String instructionSet) {
6430        return performDexOptTraced(packageName, instructionSet);
6431    }
6432
6433    private boolean performDexOptTraced(String packageName, String instructionSet) {
6434        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6435        try {
6436            return performDexOptInternal(packageName, instructionSet);
6437        } finally {
6438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6439        }
6440    }
6441
6442    private boolean performDexOptInternal(String packageName, String instructionSet) {
6443        PackageParser.Package p;
6444        final String targetInstructionSet;
6445        synchronized (mPackages) {
6446            p = mPackages.get(packageName);
6447            if (p == null) {
6448                return false;
6449            }
6450            mPackageUsage.write(false);
6451
6452            targetInstructionSet = instructionSet != null ? instructionSet :
6453                    getPrimaryInstructionSet(p.applicationInfo);
6454            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6455                return false;
6456            }
6457        }
6458        long callingId = Binder.clearCallingIdentity();
6459        try {
6460            synchronized (mInstallLock) {
6461                final String[] instructionSets = new String[] { targetInstructionSet };
6462                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6463                        true /* inclDependencies */);
6464                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6465            }
6466        } finally {
6467            Binder.restoreCallingIdentity(callingId);
6468        }
6469    }
6470
6471    public ArraySet<String> getPackagesThatNeedDexOpt() {
6472        ArraySet<String> pkgs = null;
6473        synchronized (mPackages) {
6474            for (PackageParser.Package p : mPackages.values()) {
6475                if (DEBUG_DEXOPT) {
6476                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6477                }
6478                if (!p.mDexOptPerformed.isEmpty()) {
6479                    continue;
6480                }
6481                if (pkgs == null) {
6482                    pkgs = new ArraySet<String>();
6483                }
6484                pkgs.add(p.packageName);
6485            }
6486        }
6487        return pkgs;
6488    }
6489
6490    public void shutdown() {
6491        mPackageUsage.write(true);
6492    }
6493
6494    @Override
6495    public void forceDexOpt(String packageName) {
6496        enforceSystemOrRoot("forceDexOpt");
6497
6498        PackageParser.Package pkg;
6499        synchronized (mPackages) {
6500            pkg = mPackages.get(packageName);
6501            if (pkg == null) {
6502                throw new IllegalArgumentException("Missing package: " + packageName);
6503            }
6504        }
6505
6506        synchronized (mInstallLock) {
6507            final String[] instructionSets = new String[] {
6508                    getPrimaryInstructionSet(pkg.applicationInfo) };
6509
6510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6511
6512            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6513                    true /* inclDependencies */);
6514
6515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6516            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6517                throw new IllegalStateException("Failed to dexopt: " + res);
6518            }
6519        }
6520    }
6521
6522    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6523        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6524            Slog.w(TAG, "Unable to update from " + oldPkg.name
6525                    + " to " + newPkg.packageName
6526                    + ": old package not in system partition");
6527            return false;
6528        } else if (mPackages.get(oldPkg.name) != null) {
6529            Slog.w(TAG, "Unable to update from " + oldPkg.name
6530                    + " to " + newPkg.packageName
6531                    + ": old package still exists");
6532            return false;
6533        }
6534        return true;
6535    }
6536
6537    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6538            throws PackageManagerException {
6539        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6540        if (res != 0) {
6541            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6542                    "Failed to install " + packageName + ": " + res);
6543        }
6544
6545        final int[] users = sUserManager.getUserIds();
6546        for (int user : users) {
6547            if (user != 0) {
6548                res = mInstaller.createUserData(volumeUuid, packageName,
6549                        UserHandle.getUid(user, uid), user, seinfo);
6550                if (res != 0) {
6551                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6552                            "Failed to createUserData " + packageName + ": " + res);
6553                }
6554            }
6555        }
6556    }
6557
6558    private int removeDataDirsLI(String volumeUuid, String packageName) {
6559        int[] users = sUserManager.getUserIds();
6560        int res = 0;
6561        for (int user : users) {
6562            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6563            if (resInner < 0) {
6564                res = resInner;
6565            }
6566        }
6567
6568        return res;
6569    }
6570
6571    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6572        int[] users = sUserManager.getUserIds();
6573        int res = 0;
6574        for (int user : users) {
6575            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6576            if (resInner < 0) {
6577                res = resInner;
6578            }
6579        }
6580        return res;
6581    }
6582
6583    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6584            PackageParser.Package changingLib) {
6585        if (file.path != null) {
6586            usesLibraryFiles.add(file.path);
6587            return;
6588        }
6589        PackageParser.Package p = mPackages.get(file.apk);
6590        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6591            // If we are doing this while in the middle of updating a library apk,
6592            // then we need to make sure to use that new apk for determining the
6593            // dependencies here.  (We haven't yet finished committing the new apk
6594            // to the package manager state.)
6595            if (p == null || p.packageName.equals(changingLib.packageName)) {
6596                p = changingLib;
6597            }
6598        }
6599        if (p != null) {
6600            usesLibraryFiles.addAll(p.getAllCodePaths());
6601        }
6602    }
6603
6604    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6605            PackageParser.Package changingLib) throws PackageManagerException {
6606        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6607            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6608            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6609            for (int i=0; i<N; i++) {
6610                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6611                if (file == null) {
6612                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6613                            "Package " + pkg.packageName + " requires unavailable shared library "
6614                            + pkg.usesLibraries.get(i) + "; failing!");
6615                }
6616                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6617            }
6618            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6619            for (int i=0; i<N; i++) {
6620                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6621                if (file == null) {
6622                    Slog.w(TAG, "Package " + pkg.packageName
6623                            + " desires unavailable shared library "
6624                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6625                } else {
6626                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6627                }
6628            }
6629            N = usesLibraryFiles.size();
6630            if (N > 0) {
6631                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6632            } else {
6633                pkg.usesLibraryFiles = null;
6634            }
6635        }
6636    }
6637
6638    private static boolean hasString(List<String> list, List<String> which) {
6639        if (list == null) {
6640            return false;
6641        }
6642        for (int i=list.size()-1; i>=0; i--) {
6643            for (int j=which.size()-1; j>=0; j--) {
6644                if (which.get(j).equals(list.get(i))) {
6645                    return true;
6646                }
6647            }
6648        }
6649        return false;
6650    }
6651
6652    private void updateAllSharedLibrariesLPw() {
6653        for (PackageParser.Package pkg : mPackages.values()) {
6654            try {
6655                updateSharedLibrariesLPw(pkg, null);
6656            } catch (PackageManagerException e) {
6657                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6658            }
6659        }
6660    }
6661
6662    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6663            PackageParser.Package changingPkg) {
6664        ArrayList<PackageParser.Package> res = null;
6665        for (PackageParser.Package pkg : mPackages.values()) {
6666            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6667                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6668                if (res == null) {
6669                    res = new ArrayList<PackageParser.Package>();
6670                }
6671                res.add(pkg);
6672                try {
6673                    updateSharedLibrariesLPw(pkg, changingPkg);
6674                } catch (PackageManagerException e) {
6675                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6676                }
6677            }
6678        }
6679        return res;
6680    }
6681
6682    /**
6683     * Derive the value of the {@code cpuAbiOverride} based on the provided
6684     * value and an optional stored value from the package settings.
6685     */
6686    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6687        String cpuAbiOverride = null;
6688
6689        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6690            cpuAbiOverride = null;
6691        } else if (abiOverride != null) {
6692            cpuAbiOverride = abiOverride;
6693        } else if (settings != null) {
6694            cpuAbiOverride = settings.cpuAbiOverrideString;
6695        }
6696
6697        return cpuAbiOverride;
6698    }
6699
6700    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6701            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6702        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6703        try {
6704            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6705        } finally {
6706            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6707        }
6708    }
6709
6710    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6711            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6712        boolean success = false;
6713        try {
6714            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6715                    currentTime, user);
6716            success = true;
6717            return res;
6718        } finally {
6719            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6720                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6721            }
6722        }
6723    }
6724
6725    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6726            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6727        final File scanFile = new File(pkg.codePath);
6728        if (pkg.applicationInfo.getCodePath() == null ||
6729                pkg.applicationInfo.getResourcePath() == null) {
6730            // Bail out. The resource and code paths haven't been set.
6731            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6732                    "Code and resource paths haven't been set correctly");
6733        }
6734
6735        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6736            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6737        } else {
6738            // Only allow system apps to be flagged as core apps.
6739            pkg.coreApp = false;
6740        }
6741
6742        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6743            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6744        }
6745
6746        if (mCustomResolverComponentName != null &&
6747                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6748            setUpCustomResolverActivity(pkg);
6749        }
6750
6751        if (pkg.packageName.equals("android")) {
6752            synchronized (mPackages) {
6753                if (mAndroidApplication != null) {
6754                    Slog.w(TAG, "*************************************************");
6755                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6756                    Slog.w(TAG, " file=" + scanFile);
6757                    Slog.w(TAG, "*************************************************");
6758                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6759                            "Core android package being redefined.  Skipping.");
6760                }
6761
6762                // Set up information for our fall-back user intent resolution activity.
6763                mPlatformPackage = pkg;
6764                pkg.mVersionCode = mSdkVersion;
6765                mAndroidApplication = pkg.applicationInfo;
6766
6767                if (!mResolverReplaced) {
6768                    mResolveActivity.applicationInfo = mAndroidApplication;
6769                    mResolveActivity.name = ResolverActivity.class.getName();
6770                    mResolveActivity.packageName = mAndroidApplication.packageName;
6771                    mResolveActivity.processName = "system:ui";
6772                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6773                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6774                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6775                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6776                    mResolveActivity.exported = true;
6777                    mResolveActivity.enabled = true;
6778                    mResolveInfo.activityInfo = mResolveActivity;
6779                    mResolveInfo.priority = 0;
6780                    mResolveInfo.preferredOrder = 0;
6781                    mResolveInfo.match = 0;
6782                    mResolveComponentName = new ComponentName(
6783                            mAndroidApplication.packageName, mResolveActivity.name);
6784                }
6785            }
6786        }
6787
6788        if (DEBUG_PACKAGE_SCANNING) {
6789            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6790                Log.d(TAG, "Scanning package " + pkg.packageName);
6791        }
6792
6793        if (mPackages.containsKey(pkg.packageName)
6794                || mSharedLibraries.containsKey(pkg.packageName)) {
6795            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6796                    "Application package " + pkg.packageName
6797                    + " already installed.  Skipping duplicate.");
6798        }
6799
6800        // If we're only installing presumed-existing packages, require that the
6801        // scanned APK is both already known and at the path previously established
6802        // for it.  Previously unknown packages we pick up normally, but if we have an
6803        // a priori expectation about this package's install presence, enforce it.
6804        // With a singular exception for new system packages. When an OTA contains
6805        // a new system package, we allow the codepath to change from a system location
6806        // to the user-installed location. If we don't allow this change, any newer,
6807        // user-installed version of the application will be ignored.
6808        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6809            if (mExpectingBetter.containsKey(pkg.packageName)) {
6810                logCriticalInfo(Log.WARN,
6811                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6812            } else {
6813                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6814                if (known != null) {
6815                    if (DEBUG_PACKAGE_SCANNING) {
6816                        Log.d(TAG, "Examining " + pkg.codePath
6817                                + " and requiring known paths " + known.codePathString
6818                                + " & " + known.resourcePathString);
6819                    }
6820                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6821                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6822                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6823                                "Application package " + pkg.packageName
6824                                + " found at " + pkg.applicationInfo.getCodePath()
6825                                + " but expected at " + known.codePathString + "; ignoring.");
6826                    }
6827                }
6828            }
6829        }
6830
6831        // Initialize package source and resource directories
6832        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6833        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6834
6835        SharedUserSetting suid = null;
6836        PackageSetting pkgSetting = null;
6837
6838        if (!isSystemApp(pkg)) {
6839            // Only system apps can use these features.
6840            pkg.mOriginalPackages = null;
6841            pkg.mRealPackage = null;
6842            pkg.mAdoptPermissions = null;
6843        }
6844
6845        // writer
6846        synchronized (mPackages) {
6847            if (pkg.mSharedUserId != null) {
6848                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6849                if (suid == null) {
6850                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6851                            "Creating application package " + pkg.packageName
6852                            + " for shared user failed");
6853                }
6854                if (DEBUG_PACKAGE_SCANNING) {
6855                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6856                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6857                                + "): packages=" + suid.packages);
6858                }
6859            }
6860
6861            // Check if we are renaming from an original package name.
6862            PackageSetting origPackage = null;
6863            String realName = null;
6864            if (pkg.mOriginalPackages != null) {
6865                // This package may need to be renamed to a previously
6866                // installed name.  Let's check on that...
6867                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6868                if (pkg.mOriginalPackages.contains(renamed)) {
6869                    // This package had originally been installed as the
6870                    // original name, and we have already taken care of
6871                    // transitioning to the new one.  Just update the new
6872                    // one to continue using the old name.
6873                    realName = pkg.mRealPackage;
6874                    if (!pkg.packageName.equals(renamed)) {
6875                        // Callers into this function may have already taken
6876                        // care of renaming the package; only do it here if
6877                        // it is not already done.
6878                        pkg.setPackageName(renamed);
6879                    }
6880
6881                } else {
6882                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6883                        if ((origPackage = mSettings.peekPackageLPr(
6884                                pkg.mOriginalPackages.get(i))) != null) {
6885                            // We do have the package already installed under its
6886                            // original name...  should we use it?
6887                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6888                                // New package is not compatible with original.
6889                                origPackage = null;
6890                                continue;
6891                            } else if (origPackage.sharedUser != null) {
6892                                // Make sure uid is compatible between packages.
6893                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6894                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6895                                            + " to " + pkg.packageName + ": old uid "
6896                                            + origPackage.sharedUser.name
6897                                            + " differs from " + pkg.mSharedUserId);
6898                                    origPackage = null;
6899                                    continue;
6900                                }
6901                            } else {
6902                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6903                                        + pkg.packageName + " to old name " + origPackage.name);
6904                            }
6905                            break;
6906                        }
6907                    }
6908                }
6909            }
6910
6911            if (mTransferedPackages.contains(pkg.packageName)) {
6912                Slog.w(TAG, "Package " + pkg.packageName
6913                        + " was transferred to another, but its .apk remains");
6914            }
6915
6916            // Just create the setting, don't add it yet. For already existing packages
6917            // the PkgSetting exists already and doesn't have to be created.
6918            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6919                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6920                    pkg.applicationInfo.primaryCpuAbi,
6921                    pkg.applicationInfo.secondaryCpuAbi,
6922                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6923                    user, false);
6924            if (pkgSetting == null) {
6925                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6926                        "Creating application package " + pkg.packageName + " failed");
6927            }
6928
6929            if (pkgSetting.origPackage != null) {
6930                // If we are first transitioning from an original package,
6931                // fix up the new package's name now.  We need to do this after
6932                // looking up the package under its new name, so getPackageLP
6933                // can take care of fiddling things correctly.
6934                pkg.setPackageName(origPackage.name);
6935
6936                // File a report about this.
6937                String msg = "New package " + pkgSetting.realName
6938                        + " renamed to replace old package " + pkgSetting.name;
6939                reportSettingsProblem(Log.WARN, msg);
6940
6941                // Make a note of it.
6942                mTransferedPackages.add(origPackage.name);
6943
6944                // No longer need to retain this.
6945                pkgSetting.origPackage = null;
6946            }
6947
6948            if (realName != null) {
6949                // Make a note of it.
6950                mTransferedPackages.add(pkg.packageName);
6951            }
6952
6953            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6954                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6955            }
6956
6957            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6958                // Check all shared libraries and map to their actual file path.
6959                // We only do this here for apps not on a system dir, because those
6960                // are the only ones that can fail an install due to this.  We
6961                // will take care of the system apps by updating all of their
6962                // library paths after the scan is done.
6963                updateSharedLibrariesLPw(pkg, null);
6964            }
6965
6966            if (mFoundPolicyFile) {
6967                SELinuxMMAC.assignSeinfoValue(pkg);
6968            }
6969
6970            pkg.applicationInfo.uid = pkgSetting.appId;
6971            pkg.mExtras = pkgSetting;
6972            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6973                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6974                    // We just determined the app is signed correctly, so bring
6975                    // over the latest parsed certs.
6976                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6977                } else {
6978                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6979                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6980                                "Package " + pkg.packageName + " upgrade keys do not match the "
6981                                + "previously installed version");
6982                    } else {
6983                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6984                        String msg = "System package " + pkg.packageName
6985                            + " signature changed; retaining data.";
6986                        reportSettingsProblem(Log.WARN, msg);
6987                    }
6988                }
6989            } else {
6990                try {
6991                    verifySignaturesLP(pkgSetting, pkg);
6992                    // We just determined the app is signed correctly, so bring
6993                    // over the latest parsed certs.
6994                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6995                } catch (PackageManagerException e) {
6996                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6997                        throw e;
6998                    }
6999                    // The signature has changed, but this package is in the system
7000                    // image...  let's recover!
7001                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7002                    // However...  if this package is part of a shared user, but it
7003                    // doesn't match the signature of the shared user, let's fail.
7004                    // What this means is that you can't change the signatures
7005                    // associated with an overall shared user, which doesn't seem all
7006                    // that unreasonable.
7007                    if (pkgSetting.sharedUser != null) {
7008                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7009                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7010                            throw new PackageManagerException(
7011                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7012                                            "Signature mismatch for shared user : "
7013                                            + pkgSetting.sharedUser);
7014                        }
7015                    }
7016                    // File a report about this.
7017                    String msg = "System package " + pkg.packageName
7018                        + " signature changed; retaining data.";
7019                    reportSettingsProblem(Log.WARN, msg);
7020                }
7021            }
7022            // Verify that this new package doesn't have any content providers
7023            // that conflict with existing packages.  Only do this if the
7024            // package isn't already installed, since we don't want to break
7025            // things that are installed.
7026            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7027                final int N = pkg.providers.size();
7028                int i;
7029                for (i=0; i<N; i++) {
7030                    PackageParser.Provider p = pkg.providers.get(i);
7031                    if (p.info.authority != null) {
7032                        String names[] = p.info.authority.split(";");
7033                        for (int j = 0; j < names.length; j++) {
7034                            if (mProvidersByAuthority.containsKey(names[j])) {
7035                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7036                                final String otherPackageName =
7037                                        ((other != null && other.getComponentName() != null) ?
7038                                                other.getComponentName().getPackageName() : "?");
7039                                throw new PackageManagerException(
7040                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7041                                                "Can't install because provider name " + names[j]
7042                                                + " (in package " + pkg.applicationInfo.packageName
7043                                                + ") is already used by " + otherPackageName);
7044                            }
7045                        }
7046                    }
7047                }
7048            }
7049
7050            if (pkg.mAdoptPermissions != null) {
7051                // This package wants to adopt ownership of permissions from
7052                // another package.
7053                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7054                    final String origName = pkg.mAdoptPermissions.get(i);
7055                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7056                    if (orig != null) {
7057                        if (verifyPackageUpdateLPr(orig, pkg)) {
7058                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7059                                    + pkg.packageName);
7060                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7061                        }
7062                    }
7063                }
7064            }
7065        }
7066
7067        final String pkgName = pkg.packageName;
7068
7069        final long scanFileTime = scanFile.lastModified();
7070        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7071        pkg.applicationInfo.processName = fixProcessName(
7072                pkg.applicationInfo.packageName,
7073                pkg.applicationInfo.processName,
7074                pkg.applicationInfo.uid);
7075
7076        if (pkg != mPlatformPackage) {
7077            // This is a normal package, need to make its data directory.
7078            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7079                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7080
7081            boolean uidError = false;
7082            if (dataPath.exists()) {
7083                int currentUid = 0;
7084                try {
7085                    StructStat stat = Os.stat(dataPath.getPath());
7086                    currentUid = stat.st_uid;
7087                } catch (ErrnoException e) {
7088                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7089                }
7090
7091                // If we have mismatched owners for the data path, we have a problem.
7092                if (currentUid != pkg.applicationInfo.uid) {
7093                    boolean recovered = false;
7094                    if (currentUid == 0) {
7095                        // The directory somehow became owned by root.  Wow.
7096                        // This is probably because the system was stopped while
7097                        // installd was in the middle of messing with its libs
7098                        // directory.  Ask installd to fix that.
7099                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7100                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7101                        if (ret >= 0) {
7102                            recovered = true;
7103                            String msg = "Package " + pkg.packageName
7104                                    + " unexpectedly changed to uid 0; recovered to " +
7105                                    + pkg.applicationInfo.uid;
7106                            reportSettingsProblem(Log.WARN, msg);
7107                        }
7108                    }
7109                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7110                            || (scanFlags&SCAN_BOOTING) != 0)) {
7111                        // If this is a system app, we can at least delete its
7112                        // current data so the application will still work.
7113                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7114                        if (ret >= 0) {
7115                            // TODO: Kill the processes first
7116                            // Old data gone!
7117                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7118                                    ? "System package " : "Third party package ";
7119                            String msg = prefix + pkg.packageName
7120                                    + " has changed from uid: "
7121                                    + currentUid + " to "
7122                                    + pkg.applicationInfo.uid + "; old data erased";
7123                            reportSettingsProblem(Log.WARN, msg);
7124                            recovered = true;
7125                        }
7126                        if (!recovered) {
7127                            mHasSystemUidErrors = true;
7128                        }
7129                    } else if (!recovered) {
7130                        // If we allow this install to proceed, we will be broken.
7131                        // Abort, abort!
7132                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7133                                "scanPackageLI");
7134                    }
7135                    if (!recovered) {
7136                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7137                            + pkg.applicationInfo.uid + "/fs_"
7138                            + currentUid;
7139                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7140                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7141                        String msg = "Package " + pkg.packageName
7142                                + " has mismatched uid: "
7143                                + currentUid + " on disk, "
7144                                + pkg.applicationInfo.uid + " in settings";
7145                        // writer
7146                        synchronized (mPackages) {
7147                            mSettings.mReadMessages.append(msg);
7148                            mSettings.mReadMessages.append('\n');
7149                            uidError = true;
7150                            if (!pkgSetting.uidError) {
7151                                reportSettingsProblem(Log.ERROR, msg);
7152                            }
7153                        }
7154                    }
7155                }
7156
7157                // Ensure that directories are prepared
7158                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7159                        pkg.applicationInfo.seinfo);
7160
7161                if (mShouldRestoreconData) {
7162                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7163                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7164                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7165                }
7166            } else {
7167                if (DEBUG_PACKAGE_SCANNING) {
7168                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7169                        Log.v(TAG, "Want this data dir: " + dataPath);
7170                }
7171                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7172                        pkg.applicationInfo.seinfo);
7173            }
7174
7175            // Get all of our default paths setup
7176            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7177
7178            pkgSetting.uidError = uidError;
7179        }
7180
7181        final String path = scanFile.getPath();
7182        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7183
7184        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7185            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7186
7187            // Some system apps still use directory structure for native libraries
7188            // in which case we might end up not detecting abi solely based on apk
7189            // structure. Try to detect abi based on directory structure.
7190            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7191                    pkg.applicationInfo.primaryCpuAbi == null) {
7192                setBundledAppAbisAndRoots(pkg, pkgSetting);
7193                setNativeLibraryPaths(pkg);
7194            }
7195
7196        } else {
7197            if ((scanFlags & SCAN_MOVE) != 0) {
7198                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7199                // but we already have this packages package info in the PackageSetting. We just
7200                // use that and derive the native library path based on the new codepath.
7201                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7202                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7203            }
7204
7205            // Set native library paths again. For moves, the path will be updated based on the
7206            // ABIs we've determined above. For non-moves, the path will be updated based on the
7207            // ABIs we determined during compilation, but the path will depend on the final
7208            // package path (after the rename away from the stage path).
7209            setNativeLibraryPaths(pkg);
7210        }
7211
7212        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7213        final int[] userIds = sUserManager.getUserIds();
7214        synchronized (mInstallLock) {
7215            // Make sure all user data directories are ready to roll; we're okay
7216            // if they already exist
7217            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7218                for (int userId : userIds) {
7219                    if (userId != UserHandle.USER_SYSTEM) {
7220                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7221                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7222                                pkg.applicationInfo.seinfo);
7223                    }
7224                }
7225            }
7226
7227            // Create a native library symlink only if we have native libraries
7228            // and if the native libraries are 32 bit libraries. We do not provide
7229            // this symlink for 64 bit libraries.
7230            if (pkg.applicationInfo.primaryCpuAbi != null &&
7231                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7232                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7233                try {
7234                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7235                    for (int userId : userIds) {
7236                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7237                                nativeLibPath, userId) < 0) {
7238                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7239                                    "Failed linking native library dir (user=" + userId + ")");
7240                        }
7241                    }
7242                } finally {
7243                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7244                }
7245            }
7246        }
7247
7248        // This is a special case for the "system" package, where the ABI is
7249        // dictated by the zygote configuration (and init.rc). We should keep track
7250        // of this ABI so that we can deal with "normal" applications that run under
7251        // the same UID correctly.
7252        if (mPlatformPackage == pkg) {
7253            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7254                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7255        }
7256
7257        // If there's a mismatch between the abi-override in the package setting
7258        // and the abiOverride specified for the install. Warn about this because we
7259        // would've already compiled the app without taking the package setting into
7260        // account.
7261        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7262            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7263                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7264                        " for package: " + pkg.packageName);
7265            }
7266        }
7267
7268        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7269        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7270        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7271
7272        // Copy the derived override back to the parsed package, so that we can
7273        // update the package settings accordingly.
7274        pkg.cpuAbiOverride = cpuAbiOverride;
7275
7276        if (DEBUG_ABI_SELECTION) {
7277            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7278                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7279                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7280        }
7281
7282        // Push the derived path down into PackageSettings so we know what to
7283        // clean up at uninstall time.
7284        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7285
7286        if (DEBUG_ABI_SELECTION) {
7287            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7288                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7289                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7290        }
7291
7292        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7293            // We don't do this here during boot because we can do it all
7294            // at once after scanning all existing packages.
7295            //
7296            // We also do this *before* we perform dexopt on this package, so that
7297            // we can avoid redundant dexopts, and also to make sure we've got the
7298            // code and package path correct.
7299            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7300                    pkg, true /* boot complete */);
7301        }
7302
7303        if (mFactoryTest && pkg.requestedPermissions.contains(
7304                android.Manifest.permission.FACTORY_TEST)) {
7305            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7306        }
7307
7308        ArrayList<PackageParser.Package> clientLibPkgs = null;
7309
7310        // writer
7311        synchronized (mPackages) {
7312            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7313                // Only system apps can add new shared libraries.
7314                if (pkg.libraryNames != null) {
7315                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7316                        String name = pkg.libraryNames.get(i);
7317                        boolean allowed = false;
7318                        if (pkg.isUpdatedSystemApp()) {
7319                            // New library entries can only be added through the
7320                            // system image.  This is important to get rid of a lot
7321                            // of nasty edge cases: for example if we allowed a non-
7322                            // system update of the app to add a library, then uninstalling
7323                            // the update would make the library go away, and assumptions
7324                            // we made such as through app install filtering would now
7325                            // have allowed apps on the device which aren't compatible
7326                            // with it.  Better to just have the restriction here, be
7327                            // conservative, and create many fewer cases that can negatively
7328                            // impact the user experience.
7329                            final PackageSetting sysPs = mSettings
7330                                    .getDisabledSystemPkgLPr(pkg.packageName);
7331                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7332                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7333                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7334                                        allowed = true;
7335                                        break;
7336                                    }
7337                                }
7338                            }
7339                        } else {
7340                            allowed = true;
7341                        }
7342                        if (allowed) {
7343                            if (!mSharedLibraries.containsKey(name)) {
7344                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7345                            } else if (!name.equals(pkg.packageName)) {
7346                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7347                                        + name + " already exists; skipping");
7348                            }
7349                        } else {
7350                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7351                                    + name + " that is not declared on system image; skipping");
7352                        }
7353                    }
7354                    if ((scanFlags & SCAN_BOOTING) == 0) {
7355                        // If we are not booting, we need to update any applications
7356                        // that are clients of our shared library.  If we are booting,
7357                        // this will all be done once the scan is complete.
7358                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7359                    }
7360                }
7361            }
7362        }
7363
7364        // Request the ActivityManager to kill the process(only for existing packages)
7365        // so that we do not end up in a confused state while the user is still using the older
7366        // version of the application while the new one gets installed.
7367        if ((scanFlags & SCAN_REPLACING) != 0) {
7368            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7369
7370            killApplication(pkg.applicationInfo.packageName,
7371                        pkg.applicationInfo.uid, "replace pkg");
7372
7373            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7374        }
7375
7376        // Also need to kill any apps that are dependent on the library.
7377        if (clientLibPkgs != null) {
7378            for (int i=0; i<clientLibPkgs.size(); i++) {
7379                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7380                killApplication(clientPkg.applicationInfo.packageName,
7381                        clientPkg.applicationInfo.uid, "update lib");
7382            }
7383        }
7384
7385        // Make sure we're not adding any bogus keyset info
7386        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7387        ksms.assertScannedPackageValid(pkg);
7388
7389        // writer
7390        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7391
7392        boolean createIdmapFailed = false;
7393        synchronized (mPackages) {
7394            // We don't expect installation to fail beyond this point
7395
7396            // Add the new setting to mSettings
7397            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7398            // Add the new setting to mPackages
7399            mPackages.put(pkg.applicationInfo.packageName, pkg);
7400            // Make sure we don't accidentally delete its data.
7401            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7402            while (iter.hasNext()) {
7403                PackageCleanItem item = iter.next();
7404                if (pkgName.equals(item.packageName)) {
7405                    iter.remove();
7406                }
7407            }
7408
7409            // Take care of first install / last update times.
7410            if (currentTime != 0) {
7411                if (pkgSetting.firstInstallTime == 0) {
7412                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7413                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7414                    pkgSetting.lastUpdateTime = currentTime;
7415                }
7416            } else if (pkgSetting.firstInstallTime == 0) {
7417                // We need *something*.  Take time time stamp of the file.
7418                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7419            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7420                if (scanFileTime != pkgSetting.timeStamp) {
7421                    // A package on the system image has changed; consider this
7422                    // to be an update.
7423                    pkgSetting.lastUpdateTime = scanFileTime;
7424                }
7425            }
7426
7427            // Add the package's KeySets to the global KeySetManagerService
7428            ksms.addScannedPackageLPw(pkg);
7429
7430            int N = pkg.providers.size();
7431            StringBuilder r = null;
7432            int i;
7433            for (i=0; i<N; i++) {
7434                PackageParser.Provider p = pkg.providers.get(i);
7435                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7436                        p.info.processName, pkg.applicationInfo.uid);
7437                mProviders.addProvider(p);
7438                p.syncable = p.info.isSyncable;
7439                if (p.info.authority != null) {
7440                    String names[] = p.info.authority.split(";");
7441                    p.info.authority = null;
7442                    for (int j = 0; j < names.length; j++) {
7443                        if (j == 1 && p.syncable) {
7444                            // We only want the first authority for a provider to possibly be
7445                            // syncable, so if we already added this provider using a different
7446                            // authority clear the syncable flag. We copy the provider before
7447                            // changing it because the mProviders object contains a reference
7448                            // to a provider that we don't want to change.
7449                            // Only do this for the second authority since the resulting provider
7450                            // object can be the same for all future authorities for this provider.
7451                            p = new PackageParser.Provider(p);
7452                            p.syncable = false;
7453                        }
7454                        if (!mProvidersByAuthority.containsKey(names[j])) {
7455                            mProvidersByAuthority.put(names[j], p);
7456                            if (p.info.authority == null) {
7457                                p.info.authority = names[j];
7458                            } else {
7459                                p.info.authority = p.info.authority + ";" + names[j];
7460                            }
7461                            if (DEBUG_PACKAGE_SCANNING) {
7462                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7463                                    Log.d(TAG, "Registered content provider: " + names[j]
7464                                            + ", className = " + p.info.name + ", isSyncable = "
7465                                            + p.info.isSyncable);
7466                            }
7467                        } else {
7468                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7469                            Slog.w(TAG, "Skipping provider name " + names[j] +
7470                                    " (in package " + pkg.applicationInfo.packageName +
7471                                    "): name already used by "
7472                                    + ((other != null && other.getComponentName() != null)
7473                                            ? other.getComponentName().getPackageName() : "?"));
7474                        }
7475                    }
7476                }
7477                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7478                    if (r == null) {
7479                        r = new StringBuilder(256);
7480                    } else {
7481                        r.append(' ');
7482                    }
7483                    r.append(p.info.name);
7484                }
7485            }
7486            if (r != null) {
7487                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7488            }
7489
7490            N = pkg.services.size();
7491            r = null;
7492            for (i=0; i<N; i++) {
7493                PackageParser.Service s = pkg.services.get(i);
7494                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7495                        s.info.processName, pkg.applicationInfo.uid);
7496                mServices.addService(s);
7497                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7498                    if (r == null) {
7499                        r = new StringBuilder(256);
7500                    } else {
7501                        r.append(' ');
7502                    }
7503                    r.append(s.info.name);
7504                }
7505            }
7506            if (r != null) {
7507                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7508            }
7509
7510            N = pkg.receivers.size();
7511            r = null;
7512            for (i=0; i<N; i++) {
7513                PackageParser.Activity a = pkg.receivers.get(i);
7514                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7515                        a.info.processName, pkg.applicationInfo.uid);
7516                mReceivers.addActivity(a, "receiver");
7517                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7518                    if (r == null) {
7519                        r = new StringBuilder(256);
7520                    } else {
7521                        r.append(' ');
7522                    }
7523                    r.append(a.info.name);
7524                }
7525            }
7526            if (r != null) {
7527                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7528            }
7529
7530            N = pkg.activities.size();
7531            r = null;
7532            for (i=0; i<N; i++) {
7533                PackageParser.Activity a = pkg.activities.get(i);
7534                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7535                        a.info.processName, pkg.applicationInfo.uid);
7536                mActivities.addActivity(a, "activity");
7537                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7538                    if (r == null) {
7539                        r = new StringBuilder(256);
7540                    } else {
7541                        r.append(' ');
7542                    }
7543                    r.append(a.info.name);
7544                }
7545            }
7546            if (r != null) {
7547                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7548            }
7549
7550            N = pkg.permissionGroups.size();
7551            r = null;
7552            for (i=0; i<N; i++) {
7553                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7554                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7555                if (cur == null) {
7556                    mPermissionGroups.put(pg.info.name, pg);
7557                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7558                        if (r == null) {
7559                            r = new StringBuilder(256);
7560                        } else {
7561                            r.append(' ');
7562                        }
7563                        r.append(pg.info.name);
7564                    }
7565                } else {
7566                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7567                            + pg.info.packageName + " ignored: original from "
7568                            + cur.info.packageName);
7569                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7570                        if (r == null) {
7571                            r = new StringBuilder(256);
7572                        } else {
7573                            r.append(' ');
7574                        }
7575                        r.append("DUP:");
7576                        r.append(pg.info.name);
7577                    }
7578                }
7579            }
7580            if (r != null) {
7581                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7582            }
7583
7584            N = pkg.permissions.size();
7585            r = null;
7586            for (i=0; i<N; i++) {
7587                PackageParser.Permission p = pkg.permissions.get(i);
7588
7589                // Assume by default that we did not install this permission into the system.
7590                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7591
7592                // Now that permission groups have a special meaning, we ignore permission
7593                // groups for legacy apps to prevent unexpected behavior. In particular,
7594                // permissions for one app being granted to someone just becuase they happen
7595                // to be in a group defined by another app (before this had no implications).
7596                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7597                    p.group = mPermissionGroups.get(p.info.group);
7598                    // Warn for a permission in an unknown group.
7599                    if (p.info.group != null && p.group == null) {
7600                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7601                                + p.info.packageName + " in an unknown group " + p.info.group);
7602                    }
7603                }
7604
7605                ArrayMap<String, BasePermission> permissionMap =
7606                        p.tree ? mSettings.mPermissionTrees
7607                                : mSettings.mPermissions;
7608                BasePermission bp = permissionMap.get(p.info.name);
7609
7610                // Allow system apps to redefine non-system permissions
7611                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7612                    final boolean currentOwnerIsSystem = (bp.perm != null
7613                            && isSystemApp(bp.perm.owner));
7614                    if (isSystemApp(p.owner)) {
7615                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7616                            // It's a built-in permission and no owner, take ownership now
7617                            bp.packageSetting = pkgSetting;
7618                            bp.perm = p;
7619                            bp.uid = pkg.applicationInfo.uid;
7620                            bp.sourcePackage = p.info.packageName;
7621                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7622                        } else if (!currentOwnerIsSystem) {
7623                            String msg = "New decl " + p.owner + " of permission  "
7624                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7625                            reportSettingsProblem(Log.WARN, msg);
7626                            bp = null;
7627                        }
7628                    }
7629                }
7630
7631                if (bp == null) {
7632                    bp = new BasePermission(p.info.name, p.info.packageName,
7633                            BasePermission.TYPE_NORMAL);
7634                    permissionMap.put(p.info.name, bp);
7635                }
7636
7637                if (bp.perm == null) {
7638                    if (bp.sourcePackage == null
7639                            || bp.sourcePackage.equals(p.info.packageName)) {
7640                        BasePermission tree = findPermissionTreeLP(p.info.name);
7641                        if (tree == null
7642                                || tree.sourcePackage.equals(p.info.packageName)) {
7643                            bp.packageSetting = pkgSetting;
7644                            bp.perm = p;
7645                            bp.uid = pkg.applicationInfo.uid;
7646                            bp.sourcePackage = p.info.packageName;
7647                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7648                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7649                                if (r == null) {
7650                                    r = new StringBuilder(256);
7651                                } else {
7652                                    r.append(' ');
7653                                }
7654                                r.append(p.info.name);
7655                            }
7656                        } else {
7657                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7658                                    + p.info.packageName + " ignored: base tree "
7659                                    + tree.name + " is from package "
7660                                    + tree.sourcePackage);
7661                        }
7662                    } else {
7663                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7664                                + p.info.packageName + " ignored: original from "
7665                                + bp.sourcePackage);
7666                    }
7667                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7668                    if (r == null) {
7669                        r = new StringBuilder(256);
7670                    } else {
7671                        r.append(' ');
7672                    }
7673                    r.append("DUP:");
7674                    r.append(p.info.name);
7675                }
7676                if (bp.perm == p) {
7677                    bp.protectionLevel = p.info.protectionLevel;
7678                }
7679            }
7680
7681            if (r != null) {
7682                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7683            }
7684
7685            N = pkg.instrumentation.size();
7686            r = null;
7687            for (i=0; i<N; i++) {
7688                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7689                a.info.packageName = pkg.applicationInfo.packageName;
7690                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7691                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7692                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7693                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7694                a.info.dataDir = pkg.applicationInfo.dataDir;
7695                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7696                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7697
7698                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7699                // need other information about the application, like the ABI and what not ?
7700                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7701                mInstrumentation.put(a.getComponentName(), a);
7702                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7703                    if (r == null) {
7704                        r = new StringBuilder(256);
7705                    } else {
7706                        r.append(' ');
7707                    }
7708                    r.append(a.info.name);
7709                }
7710            }
7711            if (r != null) {
7712                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7713            }
7714
7715            if (pkg.protectedBroadcasts != null) {
7716                N = pkg.protectedBroadcasts.size();
7717                for (i=0; i<N; i++) {
7718                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7719                }
7720            }
7721
7722            pkgSetting.setTimeStamp(scanFileTime);
7723
7724            // Create idmap files for pairs of (packages, overlay packages).
7725            // Note: "android", ie framework-res.apk, is handled by native layers.
7726            if (pkg.mOverlayTarget != null) {
7727                // This is an overlay package.
7728                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7729                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7730                        mOverlays.put(pkg.mOverlayTarget,
7731                                new ArrayMap<String, PackageParser.Package>());
7732                    }
7733                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7734                    map.put(pkg.packageName, pkg);
7735                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7736                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7737                        createIdmapFailed = true;
7738                    }
7739                }
7740            } else if (mOverlays.containsKey(pkg.packageName) &&
7741                    !pkg.packageName.equals("android")) {
7742                // This is a regular package, with one or more known overlay packages.
7743                createIdmapsForPackageLI(pkg);
7744            }
7745        }
7746
7747        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7748
7749        if (createIdmapFailed) {
7750            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7751                    "scanPackageLI failed to createIdmap");
7752        }
7753        return pkg;
7754    }
7755
7756    /**
7757     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7758     * is derived purely on the basis of the contents of {@code scanFile} and
7759     * {@code cpuAbiOverride}.
7760     *
7761     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7762     */
7763    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7764                                 String cpuAbiOverride, boolean extractLibs)
7765            throws PackageManagerException {
7766        // TODO: We can probably be smarter about this stuff. For installed apps,
7767        // we can calculate this information at install time once and for all. For
7768        // system apps, we can probably assume that this information doesn't change
7769        // after the first boot scan. As things stand, we do lots of unnecessary work.
7770
7771        // Give ourselves some initial paths; we'll come back for another
7772        // pass once we've determined ABI below.
7773        setNativeLibraryPaths(pkg);
7774
7775        // We would never need to extract libs for forward-locked and external packages,
7776        // since the container service will do it for us. We shouldn't attempt to
7777        // extract libs from system app when it was not updated.
7778        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7779                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7780            extractLibs = false;
7781        }
7782
7783        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7784        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7785
7786        NativeLibraryHelper.Handle handle = null;
7787        try {
7788            handle = NativeLibraryHelper.Handle.create(pkg);
7789            // TODO(multiArch): This can be null for apps that didn't go through the
7790            // usual installation process. We can calculate it again, like we
7791            // do during install time.
7792            //
7793            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7794            // unnecessary.
7795            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7796
7797            // Null out the abis so that they can be recalculated.
7798            pkg.applicationInfo.primaryCpuAbi = null;
7799            pkg.applicationInfo.secondaryCpuAbi = null;
7800            if (isMultiArch(pkg.applicationInfo)) {
7801                // Warn if we've set an abiOverride for multi-lib packages..
7802                // By definition, we need to copy both 32 and 64 bit libraries for
7803                // such packages.
7804                if (pkg.cpuAbiOverride != null
7805                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7806                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7807                }
7808
7809                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7810                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7811                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7812                    if (extractLibs) {
7813                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7814                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7815                                useIsaSpecificSubdirs);
7816                    } else {
7817                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7818                    }
7819                }
7820
7821                maybeThrowExceptionForMultiArchCopy(
7822                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7823
7824                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7825                    if (extractLibs) {
7826                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7827                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7828                                useIsaSpecificSubdirs);
7829                    } else {
7830                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7831                    }
7832                }
7833
7834                maybeThrowExceptionForMultiArchCopy(
7835                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7836
7837                if (abi64 >= 0) {
7838                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7839                }
7840
7841                if (abi32 >= 0) {
7842                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7843                    if (abi64 >= 0) {
7844                        pkg.applicationInfo.secondaryCpuAbi = abi;
7845                    } else {
7846                        pkg.applicationInfo.primaryCpuAbi = abi;
7847                    }
7848                }
7849            } else {
7850                String[] abiList = (cpuAbiOverride != null) ?
7851                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7852
7853                // Enable gross and lame hacks for apps that are built with old
7854                // SDK tools. We must scan their APKs for renderscript bitcode and
7855                // not launch them if it's present. Don't bother checking on devices
7856                // that don't have 64 bit support.
7857                boolean needsRenderScriptOverride = false;
7858                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7859                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7860                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7861                    needsRenderScriptOverride = true;
7862                }
7863
7864                final int copyRet;
7865                if (extractLibs) {
7866                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7867                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7868                } else {
7869                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7870                }
7871
7872                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7873                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7874                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7875                }
7876
7877                if (copyRet >= 0) {
7878                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7879                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7880                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7881                } else if (needsRenderScriptOverride) {
7882                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7883                }
7884            }
7885        } catch (IOException ioe) {
7886            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7887        } finally {
7888            IoUtils.closeQuietly(handle);
7889        }
7890
7891        // Now that we've calculated the ABIs and determined if it's an internal app,
7892        // we will go ahead and populate the nativeLibraryPath.
7893        setNativeLibraryPaths(pkg);
7894    }
7895
7896    /**
7897     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7898     * i.e, so that all packages can be run inside a single process if required.
7899     *
7900     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7901     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7902     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7903     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7904     * updating a package that belongs to a shared user.
7905     *
7906     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7907     * adds unnecessary complexity.
7908     */
7909    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7910            PackageParser.Package scannedPackage, boolean bootComplete) {
7911        String requiredInstructionSet = null;
7912        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7913            requiredInstructionSet = VMRuntime.getInstructionSet(
7914                     scannedPackage.applicationInfo.primaryCpuAbi);
7915        }
7916
7917        PackageSetting requirer = null;
7918        for (PackageSetting ps : packagesForUser) {
7919            // If packagesForUser contains scannedPackage, we skip it. This will happen
7920            // when scannedPackage is an update of an existing package. Without this check,
7921            // we will never be able to change the ABI of any package belonging to a shared
7922            // user, even if it's compatible with other packages.
7923            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7924                if (ps.primaryCpuAbiString == null) {
7925                    continue;
7926                }
7927
7928                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7929                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7930                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7931                    // this but there's not much we can do.
7932                    String errorMessage = "Instruction set mismatch, "
7933                            + ((requirer == null) ? "[caller]" : requirer)
7934                            + " requires " + requiredInstructionSet + " whereas " + ps
7935                            + " requires " + instructionSet;
7936                    Slog.w(TAG, errorMessage);
7937                }
7938
7939                if (requiredInstructionSet == null) {
7940                    requiredInstructionSet = instructionSet;
7941                    requirer = ps;
7942                }
7943            }
7944        }
7945
7946        if (requiredInstructionSet != null) {
7947            String adjustedAbi;
7948            if (requirer != null) {
7949                // requirer != null implies that either scannedPackage was null or that scannedPackage
7950                // did not require an ABI, in which case we have to adjust scannedPackage to match
7951                // the ABI of the set (which is the same as requirer's ABI)
7952                adjustedAbi = requirer.primaryCpuAbiString;
7953                if (scannedPackage != null) {
7954                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7955                }
7956            } else {
7957                // requirer == null implies that we're updating all ABIs in the set to
7958                // match scannedPackage.
7959                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7960            }
7961
7962            for (PackageSetting ps : packagesForUser) {
7963                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7964                    if (ps.primaryCpuAbiString != null) {
7965                        continue;
7966                    }
7967
7968                    ps.primaryCpuAbiString = adjustedAbi;
7969                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7970                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7971                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7972                        mInstaller.rmdex(ps.codePathString,
7973                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7974                    }
7975                }
7976            }
7977        }
7978    }
7979
7980    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7981        synchronized (mPackages) {
7982            mResolverReplaced = true;
7983            // Set up information for custom user intent resolution activity.
7984            mResolveActivity.applicationInfo = pkg.applicationInfo;
7985            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7986            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7987            mResolveActivity.processName = pkg.applicationInfo.packageName;
7988            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7989            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7990                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7991            mResolveActivity.theme = 0;
7992            mResolveActivity.exported = true;
7993            mResolveActivity.enabled = true;
7994            mResolveInfo.activityInfo = mResolveActivity;
7995            mResolveInfo.priority = 0;
7996            mResolveInfo.preferredOrder = 0;
7997            mResolveInfo.match = 0;
7998            mResolveComponentName = mCustomResolverComponentName;
7999            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8000                    mResolveComponentName);
8001        }
8002    }
8003
8004    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8005        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8006
8007        // Set up information for ephemeral installer activity
8008        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8009        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8010        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8011        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8012        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8013        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8014                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8015        mEphemeralInstallerActivity.theme = 0;
8016        mEphemeralInstallerActivity.exported = true;
8017        mEphemeralInstallerActivity.enabled = true;
8018        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8019        mEphemeralInstallerInfo.priority = 0;
8020        mEphemeralInstallerInfo.preferredOrder = 0;
8021        mEphemeralInstallerInfo.match = 0;
8022
8023        if (DEBUG_EPHEMERAL) {
8024            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8025        }
8026    }
8027
8028    private static String calculateBundledApkRoot(final String codePathString) {
8029        final File codePath = new File(codePathString);
8030        final File codeRoot;
8031        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8032            codeRoot = Environment.getRootDirectory();
8033        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8034            codeRoot = Environment.getOemDirectory();
8035        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8036            codeRoot = Environment.getVendorDirectory();
8037        } else {
8038            // Unrecognized code path; take its top real segment as the apk root:
8039            // e.g. /something/app/blah.apk => /something
8040            try {
8041                File f = codePath.getCanonicalFile();
8042                File parent = f.getParentFile();    // non-null because codePath is a file
8043                File tmp;
8044                while ((tmp = parent.getParentFile()) != null) {
8045                    f = parent;
8046                    parent = tmp;
8047                }
8048                codeRoot = f;
8049                Slog.w(TAG, "Unrecognized code path "
8050                        + codePath + " - using " + codeRoot);
8051            } catch (IOException e) {
8052                // Can't canonicalize the code path -- shenanigans?
8053                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8054                return Environment.getRootDirectory().getPath();
8055            }
8056        }
8057        return codeRoot.getPath();
8058    }
8059
8060    /**
8061     * Derive and set the location of native libraries for the given package,
8062     * which varies depending on where and how the package was installed.
8063     */
8064    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8065        final ApplicationInfo info = pkg.applicationInfo;
8066        final String codePath = pkg.codePath;
8067        final File codeFile = new File(codePath);
8068        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8069        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8070
8071        info.nativeLibraryRootDir = null;
8072        info.nativeLibraryRootRequiresIsa = false;
8073        info.nativeLibraryDir = null;
8074        info.secondaryNativeLibraryDir = null;
8075
8076        if (isApkFile(codeFile)) {
8077            // Monolithic install
8078            if (bundledApp) {
8079                // If "/system/lib64/apkname" exists, assume that is the per-package
8080                // native library directory to use; otherwise use "/system/lib/apkname".
8081                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8082                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8083                        getPrimaryInstructionSet(info));
8084
8085                // This is a bundled system app so choose the path based on the ABI.
8086                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8087                // is just the default path.
8088                final String apkName = deriveCodePathName(codePath);
8089                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8090                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8091                        apkName).getAbsolutePath();
8092
8093                if (info.secondaryCpuAbi != null) {
8094                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8095                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8096                            secondaryLibDir, apkName).getAbsolutePath();
8097                }
8098            } else if (asecApp) {
8099                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8100                        .getAbsolutePath();
8101            } else {
8102                final String apkName = deriveCodePathName(codePath);
8103                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8104                        .getAbsolutePath();
8105            }
8106
8107            info.nativeLibraryRootRequiresIsa = false;
8108            info.nativeLibraryDir = info.nativeLibraryRootDir;
8109        } else {
8110            // Cluster install
8111            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8112            info.nativeLibraryRootRequiresIsa = true;
8113
8114            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8115                    getPrimaryInstructionSet(info)).getAbsolutePath();
8116
8117            if (info.secondaryCpuAbi != null) {
8118                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8119                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8120            }
8121        }
8122    }
8123
8124    /**
8125     * Calculate the abis and roots for a bundled app. These can uniquely
8126     * be determined from the contents of the system partition, i.e whether
8127     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8128     * of this information, and instead assume that the system was built
8129     * sensibly.
8130     */
8131    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8132                                           PackageSetting pkgSetting) {
8133        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8134
8135        // If "/system/lib64/apkname" exists, assume that is the per-package
8136        // native library directory to use; otherwise use "/system/lib/apkname".
8137        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8138        setBundledAppAbi(pkg, apkRoot, apkName);
8139        // pkgSetting might be null during rescan following uninstall of updates
8140        // to a bundled app, so accommodate that possibility.  The settings in
8141        // that case will be established later from the parsed package.
8142        //
8143        // If the settings aren't null, sync them up with what we've just derived.
8144        // note that apkRoot isn't stored in the package settings.
8145        if (pkgSetting != null) {
8146            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8147            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8148        }
8149    }
8150
8151    /**
8152     * Deduces the ABI of a bundled app and sets the relevant fields on the
8153     * parsed pkg object.
8154     *
8155     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8156     *        under which system libraries are installed.
8157     * @param apkName the name of the installed package.
8158     */
8159    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8160        final File codeFile = new File(pkg.codePath);
8161
8162        final boolean has64BitLibs;
8163        final boolean has32BitLibs;
8164        if (isApkFile(codeFile)) {
8165            // Monolithic install
8166            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8167            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8168        } else {
8169            // Cluster install
8170            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8171            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8172                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8173                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8174                has64BitLibs = (new File(rootDir, isa)).exists();
8175            } else {
8176                has64BitLibs = false;
8177            }
8178            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8179                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8180                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8181                has32BitLibs = (new File(rootDir, isa)).exists();
8182            } else {
8183                has32BitLibs = false;
8184            }
8185        }
8186
8187        if (has64BitLibs && !has32BitLibs) {
8188            // The package has 64 bit libs, but not 32 bit libs. Its primary
8189            // ABI should be 64 bit. We can safely assume here that the bundled
8190            // native libraries correspond to the most preferred ABI in the list.
8191
8192            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8193            pkg.applicationInfo.secondaryCpuAbi = null;
8194        } else if (has32BitLibs && !has64BitLibs) {
8195            // The package has 32 bit libs but not 64 bit libs. Its primary
8196            // ABI should be 32 bit.
8197
8198            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8199            pkg.applicationInfo.secondaryCpuAbi = null;
8200        } else if (has32BitLibs && has64BitLibs) {
8201            // The application has both 64 and 32 bit bundled libraries. We check
8202            // here that the app declares multiArch support, and warn if it doesn't.
8203            //
8204            // We will be lenient here and record both ABIs. The primary will be the
8205            // ABI that's higher on the list, i.e, a device that's configured to prefer
8206            // 64 bit apps will see a 64 bit primary ABI,
8207
8208            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8209                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8210            }
8211
8212            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8213                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8214                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8215            } else {
8216                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8217                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8218            }
8219        } else {
8220            pkg.applicationInfo.primaryCpuAbi = null;
8221            pkg.applicationInfo.secondaryCpuAbi = null;
8222        }
8223    }
8224
8225    private void killApplication(String pkgName, int appId, String reason) {
8226        // Request the ActivityManager to kill the process(only for existing packages)
8227        // so that we do not end up in a confused state while the user is still using the older
8228        // version of the application while the new one gets installed.
8229        IActivityManager am = ActivityManagerNative.getDefault();
8230        if (am != null) {
8231            try {
8232                am.killApplicationWithAppId(pkgName, appId, reason);
8233            } catch (RemoteException e) {
8234            }
8235        }
8236    }
8237
8238    void removePackageLI(PackageSetting ps, boolean chatty) {
8239        if (DEBUG_INSTALL) {
8240            if (chatty)
8241                Log.d(TAG, "Removing package " + ps.name);
8242        }
8243
8244        // writer
8245        synchronized (mPackages) {
8246            mPackages.remove(ps.name);
8247            final PackageParser.Package pkg = ps.pkg;
8248            if (pkg != null) {
8249                cleanPackageDataStructuresLILPw(pkg, chatty);
8250            }
8251        }
8252    }
8253
8254    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8255        if (DEBUG_INSTALL) {
8256            if (chatty)
8257                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8258        }
8259
8260        // writer
8261        synchronized (mPackages) {
8262            mPackages.remove(pkg.applicationInfo.packageName);
8263            cleanPackageDataStructuresLILPw(pkg, chatty);
8264        }
8265    }
8266
8267    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8268        int N = pkg.providers.size();
8269        StringBuilder r = null;
8270        int i;
8271        for (i=0; i<N; i++) {
8272            PackageParser.Provider p = pkg.providers.get(i);
8273            mProviders.removeProvider(p);
8274            if (p.info.authority == null) {
8275
8276                /* There was another ContentProvider with this authority when
8277                 * this app was installed so this authority is null,
8278                 * Ignore it as we don't have to unregister the provider.
8279                 */
8280                continue;
8281            }
8282            String names[] = p.info.authority.split(";");
8283            for (int j = 0; j < names.length; j++) {
8284                if (mProvidersByAuthority.get(names[j]) == p) {
8285                    mProvidersByAuthority.remove(names[j]);
8286                    if (DEBUG_REMOVE) {
8287                        if (chatty)
8288                            Log.d(TAG, "Unregistered content provider: " + names[j]
8289                                    + ", className = " + p.info.name + ", isSyncable = "
8290                                    + p.info.isSyncable);
8291                    }
8292                }
8293            }
8294            if (DEBUG_REMOVE && chatty) {
8295                if (r == null) {
8296                    r = new StringBuilder(256);
8297                } else {
8298                    r.append(' ');
8299                }
8300                r.append(p.info.name);
8301            }
8302        }
8303        if (r != null) {
8304            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8305        }
8306
8307        N = pkg.services.size();
8308        r = null;
8309        for (i=0; i<N; i++) {
8310            PackageParser.Service s = pkg.services.get(i);
8311            mServices.removeService(s);
8312            if (chatty) {
8313                if (r == null) {
8314                    r = new StringBuilder(256);
8315                } else {
8316                    r.append(' ');
8317                }
8318                r.append(s.info.name);
8319            }
8320        }
8321        if (r != null) {
8322            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8323        }
8324
8325        N = pkg.receivers.size();
8326        r = null;
8327        for (i=0; i<N; i++) {
8328            PackageParser.Activity a = pkg.receivers.get(i);
8329            mReceivers.removeActivity(a, "receiver");
8330            if (DEBUG_REMOVE && chatty) {
8331                if (r == null) {
8332                    r = new StringBuilder(256);
8333                } else {
8334                    r.append(' ');
8335                }
8336                r.append(a.info.name);
8337            }
8338        }
8339        if (r != null) {
8340            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8341        }
8342
8343        N = pkg.activities.size();
8344        r = null;
8345        for (i=0; i<N; i++) {
8346            PackageParser.Activity a = pkg.activities.get(i);
8347            mActivities.removeActivity(a, "activity");
8348            if (DEBUG_REMOVE && chatty) {
8349                if (r == null) {
8350                    r = new StringBuilder(256);
8351                } else {
8352                    r.append(' ');
8353                }
8354                r.append(a.info.name);
8355            }
8356        }
8357        if (r != null) {
8358            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8359        }
8360
8361        N = pkg.permissions.size();
8362        r = null;
8363        for (i=0; i<N; i++) {
8364            PackageParser.Permission p = pkg.permissions.get(i);
8365            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8366            if (bp == null) {
8367                bp = mSettings.mPermissionTrees.get(p.info.name);
8368            }
8369            if (bp != null && bp.perm == p) {
8370                bp.perm = null;
8371                if (DEBUG_REMOVE && chatty) {
8372                    if (r == null) {
8373                        r = new StringBuilder(256);
8374                    } else {
8375                        r.append(' ');
8376                    }
8377                    r.append(p.info.name);
8378                }
8379            }
8380            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8381                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8382                if (appOpPerms != null) {
8383                    appOpPerms.remove(pkg.packageName);
8384                }
8385            }
8386        }
8387        if (r != null) {
8388            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8389        }
8390
8391        N = pkg.requestedPermissions.size();
8392        r = null;
8393        for (i=0; i<N; i++) {
8394            String perm = pkg.requestedPermissions.get(i);
8395            BasePermission bp = mSettings.mPermissions.get(perm);
8396            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8397                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8398                if (appOpPerms != null) {
8399                    appOpPerms.remove(pkg.packageName);
8400                    if (appOpPerms.isEmpty()) {
8401                        mAppOpPermissionPackages.remove(perm);
8402                    }
8403                }
8404            }
8405        }
8406        if (r != null) {
8407            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8408        }
8409
8410        N = pkg.instrumentation.size();
8411        r = null;
8412        for (i=0; i<N; i++) {
8413            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8414            mInstrumentation.remove(a.getComponentName());
8415            if (DEBUG_REMOVE && chatty) {
8416                if (r == null) {
8417                    r = new StringBuilder(256);
8418                } else {
8419                    r.append(' ');
8420                }
8421                r.append(a.info.name);
8422            }
8423        }
8424        if (r != null) {
8425            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8426        }
8427
8428        r = null;
8429        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8430            // Only system apps can hold shared libraries.
8431            if (pkg.libraryNames != null) {
8432                for (i=0; i<pkg.libraryNames.size(); i++) {
8433                    String name = pkg.libraryNames.get(i);
8434                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8435                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8436                        mSharedLibraries.remove(name);
8437                        if (DEBUG_REMOVE && chatty) {
8438                            if (r == null) {
8439                                r = new StringBuilder(256);
8440                            } else {
8441                                r.append(' ');
8442                            }
8443                            r.append(name);
8444                        }
8445                    }
8446                }
8447            }
8448        }
8449        if (r != null) {
8450            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8451        }
8452    }
8453
8454    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8455        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8456            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8457                return true;
8458            }
8459        }
8460        return false;
8461    }
8462
8463    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8464    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8465    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8466
8467    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8468            int flags) {
8469        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8470        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8471    }
8472
8473    private void updatePermissionsLPw(String changingPkg,
8474            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8475        // Make sure there are no dangling permission trees.
8476        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8477        while (it.hasNext()) {
8478            final BasePermission bp = it.next();
8479            if (bp.packageSetting == null) {
8480                // We may not yet have parsed the package, so just see if
8481                // we still know about its settings.
8482                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8483            }
8484            if (bp.packageSetting == null) {
8485                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8486                        + " from package " + bp.sourcePackage);
8487                it.remove();
8488            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8489                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8490                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8491                            + " from package " + bp.sourcePackage);
8492                    flags |= UPDATE_PERMISSIONS_ALL;
8493                    it.remove();
8494                }
8495            }
8496        }
8497
8498        // Make sure all dynamic permissions have been assigned to a package,
8499        // and make sure there are no dangling permissions.
8500        it = mSettings.mPermissions.values().iterator();
8501        while (it.hasNext()) {
8502            final BasePermission bp = it.next();
8503            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8504                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8505                        + bp.name + " pkg=" + bp.sourcePackage
8506                        + " info=" + bp.pendingInfo);
8507                if (bp.packageSetting == null && bp.pendingInfo != null) {
8508                    final BasePermission tree = findPermissionTreeLP(bp.name);
8509                    if (tree != null && tree.perm != null) {
8510                        bp.packageSetting = tree.packageSetting;
8511                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8512                                new PermissionInfo(bp.pendingInfo));
8513                        bp.perm.info.packageName = tree.perm.info.packageName;
8514                        bp.perm.info.name = bp.name;
8515                        bp.uid = tree.uid;
8516                    }
8517                }
8518            }
8519            if (bp.packageSetting == null) {
8520                // We may not yet have parsed the package, so just see if
8521                // we still know about its settings.
8522                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8523            }
8524            if (bp.packageSetting == null) {
8525                Slog.w(TAG, "Removing dangling permission: " + bp.name
8526                        + " from package " + bp.sourcePackage);
8527                it.remove();
8528            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8529                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8530                    Slog.i(TAG, "Removing old permission: " + bp.name
8531                            + " from package " + bp.sourcePackage);
8532                    flags |= UPDATE_PERMISSIONS_ALL;
8533                    it.remove();
8534                }
8535            }
8536        }
8537
8538        // Now update the permissions for all packages, in particular
8539        // replace the granted permissions of the system packages.
8540        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8541            for (PackageParser.Package pkg : mPackages.values()) {
8542                if (pkg != pkgInfo) {
8543                    // Only replace for packages on requested volume
8544                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8545                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8546                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8547                    grantPermissionsLPw(pkg, replace, changingPkg);
8548                }
8549            }
8550        }
8551
8552        if (pkgInfo != null) {
8553            // Only replace for packages on requested volume
8554            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8555            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8556                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8557            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8558        }
8559    }
8560
8561    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8562            String packageOfInterest) {
8563        // IMPORTANT: There are two types of permissions: install and runtime.
8564        // Install time permissions are granted when the app is installed to
8565        // all device users and users added in the future. Runtime permissions
8566        // are granted at runtime explicitly to specific users. Normal and signature
8567        // protected permissions are install time permissions. Dangerous permissions
8568        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8569        // otherwise they are runtime permissions. This function does not manage
8570        // runtime permissions except for the case an app targeting Lollipop MR1
8571        // being upgraded to target a newer SDK, in which case dangerous permissions
8572        // are transformed from install time to runtime ones.
8573
8574        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8575        if (ps == null) {
8576            return;
8577        }
8578
8579        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8580
8581        PermissionsState permissionsState = ps.getPermissionsState();
8582        PermissionsState origPermissions = permissionsState;
8583
8584        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8585
8586        boolean runtimePermissionsRevoked = false;
8587        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8588
8589        boolean changedInstallPermission = false;
8590
8591        if (replace) {
8592            ps.installPermissionsFixed = false;
8593            if (!ps.isSharedUser()) {
8594                origPermissions = new PermissionsState(permissionsState);
8595                permissionsState.reset();
8596            } else {
8597                // We need to know only about runtime permission changes since the
8598                // calling code always writes the install permissions state but
8599                // the runtime ones are written only if changed. The only cases of
8600                // changed runtime permissions here are promotion of an install to
8601                // runtime and revocation of a runtime from a shared user.
8602                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8603                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8604                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8605                    runtimePermissionsRevoked = true;
8606                }
8607            }
8608        }
8609
8610        permissionsState.setGlobalGids(mGlobalGids);
8611
8612        final int N = pkg.requestedPermissions.size();
8613        for (int i=0; i<N; i++) {
8614            final String name = pkg.requestedPermissions.get(i);
8615            final BasePermission bp = mSettings.mPermissions.get(name);
8616
8617            if (DEBUG_INSTALL) {
8618                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8619            }
8620
8621            if (bp == null || bp.packageSetting == null) {
8622                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8623                    Slog.w(TAG, "Unknown permission " + name
8624                            + " in package " + pkg.packageName);
8625                }
8626                continue;
8627            }
8628
8629            final String perm = bp.name;
8630            boolean allowedSig = false;
8631            int grant = GRANT_DENIED;
8632
8633            // Keep track of app op permissions.
8634            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8635                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8636                if (pkgs == null) {
8637                    pkgs = new ArraySet<>();
8638                    mAppOpPermissionPackages.put(bp.name, pkgs);
8639                }
8640                pkgs.add(pkg.packageName);
8641            }
8642
8643            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8644            switch (level) {
8645                case PermissionInfo.PROTECTION_NORMAL: {
8646                    // For all apps normal permissions are install time ones.
8647                    grant = GRANT_INSTALL;
8648                } break;
8649
8650                case PermissionInfo.PROTECTION_DANGEROUS: {
8651                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8652                        // For legacy apps dangerous permissions are install time ones.
8653                        grant = GRANT_INSTALL_LEGACY;
8654                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8655                        // For legacy apps that became modern, install becomes runtime.
8656                        grant = GRANT_UPGRADE;
8657                    } else if (mPromoteSystemApps
8658                            && isSystemApp(ps)
8659                            && mExistingSystemPackages.contains(ps.name)) {
8660                        // For legacy system apps, install becomes runtime.
8661                        // We cannot check hasInstallPermission() for system apps since those
8662                        // permissions were granted implicitly and not persisted pre-M.
8663                        grant = GRANT_UPGRADE;
8664                    } else {
8665                        // For modern apps keep runtime permissions unchanged.
8666                        grant = GRANT_RUNTIME;
8667                    }
8668                } break;
8669
8670                case PermissionInfo.PROTECTION_SIGNATURE: {
8671                    // For all apps signature permissions are install time ones.
8672                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8673                    if (allowedSig) {
8674                        grant = GRANT_INSTALL;
8675                    }
8676                } break;
8677            }
8678
8679            if (DEBUG_INSTALL) {
8680                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8681            }
8682
8683            if (grant != GRANT_DENIED) {
8684                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8685                    // If this is an existing, non-system package, then
8686                    // we can't add any new permissions to it.
8687                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8688                        // Except...  if this is a permission that was added
8689                        // to the platform (note: need to only do this when
8690                        // updating the platform).
8691                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8692                            grant = GRANT_DENIED;
8693                        }
8694                    }
8695                }
8696
8697                switch (grant) {
8698                    case GRANT_INSTALL: {
8699                        // Revoke this as runtime permission to handle the case of
8700                        // a runtime permission being downgraded to an install one.
8701                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8702                            if (origPermissions.getRuntimePermissionState(
8703                                    bp.name, userId) != null) {
8704                                // Revoke the runtime permission and clear the flags.
8705                                origPermissions.revokeRuntimePermission(bp, userId);
8706                                origPermissions.updatePermissionFlags(bp, userId,
8707                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8708                                // If we revoked a permission permission, we have to write.
8709                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8710                                        changedRuntimePermissionUserIds, userId);
8711                            }
8712                        }
8713                        // Grant an install permission.
8714                        if (permissionsState.grantInstallPermission(bp) !=
8715                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8716                            changedInstallPermission = true;
8717                        }
8718                    } break;
8719
8720                    case GRANT_INSTALL_LEGACY: {
8721                        // Grant an install permission.
8722                        if (permissionsState.grantInstallPermission(bp) !=
8723                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8724                            changedInstallPermission = true;
8725                        }
8726                    } break;
8727
8728                    case GRANT_RUNTIME: {
8729                        // Grant previously granted runtime permissions.
8730                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8731                            PermissionState permissionState = origPermissions
8732                                    .getRuntimePermissionState(bp.name, userId);
8733                            final int flags = permissionState != null
8734                                    ? permissionState.getFlags() : 0;
8735                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8736                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8737                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8738                                    // If we cannot put the permission as it was, we have to write.
8739                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8740                                            changedRuntimePermissionUserIds, userId);
8741                                }
8742                            }
8743                            // Propagate the permission flags.
8744                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8745                        }
8746                    } break;
8747
8748                    case GRANT_UPGRADE: {
8749                        // Grant runtime permissions for a previously held install permission.
8750                        PermissionState permissionState = origPermissions
8751                                .getInstallPermissionState(bp.name);
8752                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8753
8754                        if (origPermissions.revokeInstallPermission(bp)
8755                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8756                            // We will be transferring the permission flags, so clear them.
8757                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8758                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8759                            changedInstallPermission = true;
8760                        }
8761
8762                        // If the permission is not to be promoted to runtime we ignore it and
8763                        // also its other flags as they are not applicable to install permissions.
8764                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8765                            for (int userId : currentUserIds) {
8766                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8767                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8768                                    // Transfer the permission flags.
8769                                    permissionsState.updatePermissionFlags(bp, userId,
8770                                            flags, flags);
8771                                    // If we granted the permission, we have to write.
8772                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8773                                            changedRuntimePermissionUserIds, userId);
8774                                }
8775                            }
8776                        }
8777                    } break;
8778
8779                    default: {
8780                        if (packageOfInterest == null
8781                                || packageOfInterest.equals(pkg.packageName)) {
8782                            Slog.w(TAG, "Not granting permission " + perm
8783                                    + " to package " + pkg.packageName
8784                                    + " because it was previously installed without");
8785                        }
8786                    } break;
8787                }
8788            } else {
8789                if (permissionsState.revokeInstallPermission(bp) !=
8790                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8791                    // Also drop the permission flags.
8792                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8793                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8794                    changedInstallPermission = true;
8795                    Slog.i(TAG, "Un-granting permission " + perm
8796                            + " from package " + pkg.packageName
8797                            + " (protectionLevel=" + bp.protectionLevel
8798                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8799                            + ")");
8800                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8801                    // Don't print warning for app op permissions, since it is fine for them
8802                    // not to be granted, there is a UI for the user to decide.
8803                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8804                        Slog.w(TAG, "Not granting permission " + perm
8805                                + " to package " + pkg.packageName
8806                                + " (protectionLevel=" + bp.protectionLevel
8807                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8808                                + ")");
8809                    }
8810                }
8811            }
8812        }
8813
8814        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8815                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8816            // This is the first that we have heard about this package, so the
8817            // permissions we have now selected are fixed until explicitly
8818            // changed.
8819            ps.installPermissionsFixed = true;
8820        }
8821
8822        // Persist the runtime permissions state for users with changes. If permissions
8823        // were revoked because no app in the shared user declares them we have to
8824        // write synchronously to avoid losing runtime permissions state.
8825        for (int userId : changedRuntimePermissionUserIds) {
8826            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8827        }
8828
8829        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8830    }
8831
8832    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8833        boolean allowed = false;
8834        final int NP = PackageParser.NEW_PERMISSIONS.length;
8835        for (int ip=0; ip<NP; ip++) {
8836            final PackageParser.NewPermissionInfo npi
8837                    = PackageParser.NEW_PERMISSIONS[ip];
8838            if (npi.name.equals(perm)
8839                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8840                allowed = true;
8841                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8842                        + pkg.packageName);
8843                break;
8844            }
8845        }
8846        return allowed;
8847    }
8848
8849    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8850            BasePermission bp, PermissionsState origPermissions) {
8851        boolean allowed;
8852        allowed = (compareSignatures(
8853                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8854                        == PackageManager.SIGNATURE_MATCH)
8855                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8856                        == PackageManager.SIGNATURE_MATCH);
8857        if (!allowed && (bp.protectionLevel
8858                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8859            if (isSystemApp(pkg)) {
8860                // For updated system applications, a system permission
8861                // is granted only if it had been defined by the original application.
8862                if (pkg.isUpdatedSystemApp()) {
8863                    final PackageSetting sysPs = mSettings
8864                            .getDisabledSystemPkgLPr(pkg.packageName);
8865                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8866                        // If the original was granted this permission, we take
8867                        // that grant decision as read and propagate it to the
8868                        // update.
8869                        if (sysPs.isPrivileged()) {
8870                            allowed = true;
8871                        }
8872                    } else {
8873                        // The system apk may have been updated with an older
8874                        // version of the one on the data partition, but which
8875                        // granted a new system permission that it didn't have
8876                        // before.  In this case we do want to allow the app to
8877                        // now get the new permission if the ancestral apk is
8878                        // privileged to get it.
8879                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8880                            for (int j=0;
8881                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8882                                if (perm.equals(
8883                                        sysPs.pkg.requestedPermissions.get(j))) {
8884                                    allowed = true;
8885                                    break;
8886                                }
8887                            }
8888                        }
8889                    }
8890                } else {
8891                    allowed = isPrivilegedApp(pkg);
8892                }
8893            }
8894        }
8895        if (!allowed) {
8896            if (!allowed && (bp.protectionLevel
8897                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8898                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8899                // If this was a previously normal/dangerous permission that got moved
8900                // to a system permission as part of the runtime permission redesign, then
8901                // we still want to blindly grant it to old apps.
8902                allowed = true;
8903            }
8904            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8905                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8906                // If this permission is to be granted to the system installer and
8907                // this app is an installer, then it gets the permission.
8908                allowed = true;
8909            }
8910            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8911                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8912                // If this permission is to be granted to the system verifier and
8913                // this app is a verifier, then it gets the permission.
8914                allowed = true;
8915            }
8916            if (!allowed && (bp.protectionLevel
8917                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8918                    && isSystemApp(pkg)) {
8919                // Any pre-installed system app is allowed to get this permission.
8920                allowed = true;
8921            }
8922            if (!allowed && (bp.protectionLevel
8923                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8924                // For development permissions, a development permission
8925                // is granted only if it was already granted.
8926                allowed = origPermissions.hasInstallPermission(perm);
8927            }
8928        }
8929        return allowed;
8930    }
8931
8932    final class ActivityIntentResolver
8933            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8935                boolean defaultOnly, int userId) {
8936            if (!sUserManager.exists(userId)) return null;
8937            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8938            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8939        }
8940
8941        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8942                int userId) {
8943            if (!sUserManager.exists(userId)) return null;
8944            mFlags = flags;
8945            return super.queryIntent(intent, resolvedType,
8946                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8947        }
8948
8949        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8950                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8951            if (!sUserManager.exists(userId)) return null;
8952            if (packageActivities == null) {
8953                return null;
8954            }
8955            mFlags = flags;
8956            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8957            final int N = packageActivities.size();
8958            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8959                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8960
8961            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8962            for (int i = 0; i < N; ++i) {
8963                intentFilters = packageActivities.get(i).intents;
8964                if (intentFilters != null && intentFilters.size() > 0) {
8965                    PackageParser.ActivityIntentInfo[] array =
8966                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8967                    intentFilters.toArray(array);
8968                    listCut.add(array);
8969                }
8970            }
8971            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8972        }
8973
8974        public final void addActivity(PackageParser.Activity a, String type) {
8975            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8976            mActivities.put(a.getComponentName(), a);
8977            if (DEBUG_SHOW_INFO)
8978                Log.v(
8979                TAG, "  " + type + " " +
8980                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8981            if (DEBUG_SHOW_INFO)
8982                Log.v(TAG, "    Class=" + a.info.name);
8983            final int NI = a.intents.size();
8984            for (int j=0; j<NI; j++) {
8985                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8986                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8987                    intent.setPriority(0);
8988                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8989                            + a.className + " with priority > 0, forcing to 0");
8990                }
8991                if (DEBUG_SHOW_INFO) {
8992                    Log.v(TAG, "    IntentFilter:");
8993                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8994                }
8995                if (!intent.debugCheck()) {
8996                    Log.w(TAG, "==> For Activity " + a.info.name);
8997                }
8998                addFilter(intent);
8999            }
9000        }
9001
9002        public final void removeActivity(PackageParser.Activity a, String type) {
9003            mActivities.remove(a.getComponentName());
9004            if (DEBUG_SHOW_INFO) {
9005                Log.v(TAG, "  " + type + " "
9006                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9007                                : a.info.name) + ":");
9008                Log.v(TAG, "    Class=" + a.info.name);
9009            }
9010            final int NI = a.intents.size();
9011            for (int j=0; j<NI; j++) {
9012                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9013                if (DEBUG_SHOW_INFO) {
9014                    Log.v(TAG, "    IntentFilter:");
9015                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9016                }
9017                removeFilter(intent);
9018            }
9019        }
9020
9021        @Override
9022        protected boolean allowFilterResult(
9023                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9024            ActivityInfo filterAi = filter.activity.info;
9025            for (int i=dest.size()-1; i>=0; i--) {
9026                ActivityInfo destAi = dest.get(i).activityInfo;
9027                if (destAi.name == filterAi.name
9028                        && destAi.packageName == filterAi.packageName) {
9029                    return false;
9030                }
9031            }
9032            return true;
9033        }
9034
9035        @Override
9036        protected ActivityIntentInfo[] newArray(int size) {
9037            return new ActivityIntentInfo[size];
9038        }
9039
9040        @Override
9041        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9042            if (!sUserManager.exists(userId)) return true;
9043            PackageParser.Package p = filter.activity.owner;
9044            if (p != null) {
9045                PackageSetting ps = (PackageSetting)p.mExtras;
9046                if (ps != null) {
9047                    // System apps are never considered stopped for purposes of
9048                    // filtering, because there may be no way for the user to
9049                    // actually re-launch them.
9050                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9051                            && ps.getStopped(userId);
9052                }
9053            }
9054            return false;
9055        }
9056
9057        @Override
9058        protected boolean isPackageForFilter(String packageName,
9059                PackageParser.ActivityIntentInfo info) {
9060            return packageName.equals(info.activity.owner.packageName);
9061        }
9062
9063        @Override
9064        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9065                int match, int userId) {
9066            if (!sUserManager.exists(userId)) return null;
9067            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9068                return null;
9069            }
9070            final PackageParser.Activity activity = info.activity;
9071            if (mSafeMode && (activity.info.applicationInfo.flags
9072                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9073                return null;
9074            }
9075            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9076            if (ps == null) {
9077                return null;
9078            }
9079            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9080                    ps.readUserState(userId), userId);
9081            if (ai == null) {
9082                return null;
9083            }
9084            final ResolveInfo res = new ResolveInfo();
9085            res.activityInfo = ai;
9086            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9087                res.filter = info;
9088            }
9089            if (info != null) {
9090                res.handleAllWebDataURI = info.handleAllWebDataURI();
9091            }
9092            res.priority = info.getPriority();
9093            res.preferredOrder = activity.owner.mPreferredOrder;
9094            //System.out.println("Result: " + res.activityInfo.className +
9095            //                   " = " + res.priority);
9096            res.match = match;
9097            res.isDefault = info.hasDefault;
9098            res.labelRes = info.labelRes;
9099            res.nonLocalizedLabel = info.nonLocalizedLabel;
9100            if (userNeedsBadging(userId)) {
9101                res.noResourceId = true;
9102            } else {
9103                res.icon = info.icon;
9104            }
9105            res.iconResourceId = info.icon;
9106            res.system = res.activityInfo.applicationInfo.isSystemApp();
9107            return res;
9108        }
9109
9110        @Override
9111        protected void sortResults(List<ResolveInfo> results) {
9112            Collections.sort(results, mResolvePrioritySorter);
9113        }
9114
9115        @Override
9116        protected void dumpFilter(PrintWriter out, String prefix,
9117                PackageParser.ActivityIntentInfo filter) {
9118            out.print(prefix); out.print(
9119                    Integer.toHexString(System.identityHashCode(filter.activity)));
9120                    out.print(' ');
9121                    filter.activity.printComponentShortName(out);
9122                    out.print(" filter ");
9123                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9124        }
9125
9126        @Override
9127        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9128            return filter.activity;
9129        }
9130
9131        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9132            PackageParser.Activity activity = (PackageParser.Activity)label;
9133            out.print(prefix); out.print(
9134                    Integer.toHexString(System.identityHashCode(activity)));
9135                    out.print(' ');
9136                    activity.printComponentShortName(out);
9137            if (count > 1) {
9138                out.print(" ("); out.print(count); out.print(" filters)");
9139            }
9140            out.println();
9141        }
9142
9143//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9144//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9145//            final List<ResolveInfo> retList = Lists.newArrayList();
9146//            while (i.hasNext()) {
9147//                final ResolveInfo resolveInfo = i.next();
9148//                if (isEnabledLP(resolveInfo.activityInfo)) {
9149//                    retList.add(resolveInfo);
9150//                }
9151//            }
9152//            return retList;
9153//        }
9154
9155        // Keys are String (activity class name), values are Activity.
9156        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9157                = new ArrayMap<ComponentName, PackageParser.Activity>();
9158        private int mFlags;
9159    }
9160
9161    private final class ServiceIntentResolver
9162            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9164                boolean defaultOnly, int userId) {
9165            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9166            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9167        }
9168
9169        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9170                int userId) {
9171            if (!sUserManager.exists(userId)) return null;
9172            mFlags = flags;
9173            return super.queryIntent(intent, resolvedType,
9174                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9175        }
9176
9177        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9178                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9179            if (!sUserManager.exists(userId)) return null;
9180            if (packageServices == null) {
9181                return null;
9182            }
9183            mFlags = flags;
9184            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9185            final int N = packageServices.size();
9186            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9187                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9188
9189            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9190            for (int i = 0; i < N; ++i) {
9191                intentFilters = packageServices.get(i).intents;
9192                if (intentFilters != null && intentFilters.size() > 0) {
9193                    PackageParser.ServiceIntentInfo[] array =
9194                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9195                    intentFilters.toArray(array);
9196                    listCut.add(array);
9197                }
9198            }
9199            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9200        }
9201
9202        public final void addService(PackageParser.Service s) {
9203            mServices.put(s.getComponentName(), s);
9204            if (DEBUG_SHOW_INFO) {
9205                Log.v(TAG, "  "
9206                        + (s.info.nonLocalizedLabel != null
9207                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9208                Log.v(TAG, "    Class=" + s.info.name);
9209            }
9210            final int NI = s.intents.size();
9211            int j;
9212            for (j=0; j<NI; j++) {
9213                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9214                if (DEBUG_SHOW_INFO) {
9215                    Log.v(TAG, "    IntentFilter:");
9216                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9217                }
9218                if (!intent.debugCheck()) {
9219                    Log.w(TAG, "==> For Service " + s.info.name);
9220                }
9221                addFilter(intent);
9222            }
9223        }
9224
9225        public final void removeService(PackageParser.Service s) {
9226            mServices.remove(s.getComponentName());
9227            if (DEBUG_SHOW_INFO) {
9228                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9229                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9230                Log.v(TAG, "    Class=" + s.info.name);
9231            }
9232            final int NI = s.intents.size();
9233            int j;
9234            for (j=0; j<NI; j++) {
9235                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9236                if (DEBUG_SHOW_INFO) {
9237                    Log.v(TAG, "    IntentFilter:");
9238                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9239                }
9240                removeFilter(intent);
9241            }
9242        }
9243
9244        @Override
9245        protected boolean allowFilterResult(
9246                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9247            ServiceInfo filterSi = filter.service.info;
9248            for (int i=dest.size()-1; i>=0; i--) {
9249                ServiceInfo destAi = dest.get(i).serviceInfo;
9250                if (destAi.name == filterSi.name
9251                        && destAi.packageName == filterSi.packageName) {
9252                    return false;
9253                }
9254            }
9255            return true;
9256        }
9257
9258        @Override
9259        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9260            return new PackageParser.ServiceIntentInfo[size];
9261        }
9262
9263        @Override
9264        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9265            if (!sUserManager.exists(userId)) return true;
9266            PackageParser.Package p = filter.service.owner;
9267            if (p != null) {
9268                PackageSetting ps = (PackageSetting)p.mExtras;
9269                if (ps != null) {
9270                    // System apps are never considered stopped for purposes of
9271                    // filtering, because there may be no way for the user to
9272                    // actually re-launch them.
9273                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9274                            && ps.getStopped(userId);
9275                }
9276            }
9277            return false;
9278        }
9279
9280        @Override
9281        protected boolean isPackageForFilter(String packageName,
9282                PackageParser.ServiceIntentInfo info) {
9283            return packageName.equals(info.service.owner.packageName);
9284        }
9285
9286        @Override
9287        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9288                int match, int userId) {
9289            if (!sUserManager.exists(userId)) return null;
9290            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9291            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9292                return null;
9293            }
9294            final PackageParser.Service service = info.service;
9295            if (mSafeMode && (service.info.applicationInfo.flags
9296                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9297                return null;
9298            }
9299            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9300            if (ps == null) {
9301                return null;
9302            }
9303            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9304                    ps.readUserState(userId), userId);
9305            if (si == null) {
9306                return null;
9307            }
9308            final ResolveInfo res = new ResolveInfo();
9309            res.serviceInfo = si;
9310            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9311                res.filter = filter;
9312            }
9313            res.priority = info.getPriority();
9314            res.preferredOrder = service.owner.mPreferredOrder;
9315            res.match = match;
9316            res.isDefault = info.hasDefault;
9317            res.labelRes = info.labelRes;
9318            res.nonLocalizedLabel = info.nonLocalizedLabel;
9319            res.icon = info.icon;
9320            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9321            return res;
9322        }
9323
9324        @Override
9325        protected void sortResults(List<ResolveInfo> results) {
9326            Collections.sort(results, mResolvePrioritySorter);
9327        }
9328
9329        @Override
9330        protected void dumpFilter(PrintWriter out, String prefix,
9331                PackageParser.ServiceIntentInfo filter) {
9332            out.print(prefix); out.print(
9333                    Integer.toHexString(System.identityHashCode(filter.service)));
9334                    out.print(' ');
9335                    filter.service.printComponentShortName(out);
9336                    out.print(" filter ");
9337                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9338        }
9339
9340        @Override
9341        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9342            return filter.service;
9343        }
9344
9345        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9346            PackageParser.Service service = (PackageParser.Service)label;
9347            out.print(prefix); out.print(
9348                    Integer.toHexString(System.identityHashCode(service)));
9349                    out.print(' ');
9350                    service.printComponentShortName(out);
9351            if (count > 1) {
9352                out.print(" ("); out.print(count); out.print(" filters)");
9353            }
9354            out.println();
9355        }
9356
9357//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9358//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9359//            final List<ResolveInfo> retList = Lists.newArrayList();
9360//            while (i.hasNext()) {
9361//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9362//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9363//                    retList.add(resolveInfo);
9364//                }
9365//            }
9366//            return retList;
9367//        }
9368
9369        // Keys are String (activity class name), values are Activity.
9370        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9371                = new ArrayMap<ComponentName, PackageParser.Service>();
9372        private int mFlags;
9373    };
9374
9375    private final class ProviderIntentResolver
9376            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9377        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9378                boolean defaultOnly, int userId) {
9379            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9380            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9381        }
9382
9383        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9384                int userId) {
9385            if (!sUserManager.exists(userId))
9386                return null;
9387            mFlags = flags;
9388            return super.queryIntent(intent, resolvedType,
9389                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9390        }
9391
9392        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9393                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9394            if (!sUserManager.exists(userId))
9395                return null;
9396            if (packageProviders == null) {
9397                return null;
9398            }
9399            mFlags = flags;
9400            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9401            final int N = packageProviders.size();
9402            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9403                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9404
9405            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9406            for (int i = 0; i < N; ++i) {
9407                intentFilters = packageProviders.get(i).intents;
9408                if (intentFilters != null && intentFilters.size() > 0) {
9409                    PackageParser.ProviderIntentInfo[] array =
9410                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9411                    intentFilters.toArray(array);
9412                    listCut.add(array);
9413                }
9414            }
9415            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9416        }
9417
9418        public final void addProvider(PackageParser.Provider p) {
9419            if (mProviders.containsKey(p.getComponentName())) {
9420                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9421                return;
9422            }
9423
9424            mProviders.put(p.getComponentName(), p);
9425            if (DEBUG_SHOW_INFO) {
9426                Log.v(TAG, "  "
9427                        + (p.info.nonLocalizedLabel != null
9428                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9429                Log.v(TAG, "    Class=" + p.info.name);
9430            }
9431            final int NI = p.intents.size();
9432            int j;
9433            for (j = 0; j < NI; j++) {
9434                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9435                if (DEBUG_SHOW_INFO) {
9436                    Log.v(TAG, "    IntentFilter:");
9437                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9438                }
9439                if (!intent.debugCheck()) {
9440                    Log.w(TAG, "==> For Provider " + p.info.name);
9441                }
9442                addFilter(intent);
9443            }
9444        }
9445
9446        public final void removeProvider(PackageParser.Provider p) {
9447            mProviders.remove(p.getComponentName());
9448            if (DEBUG_SHOW_INFO) {
9449                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9450                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9451                Log.v(TAG, "    Class=" + p.info.name);
9452            }
9453            final int NI = p.intents.size();
9454            int j;
9455            for (j = 0; j < NI; j++) {
9456                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9457                if (DEBUG_SHOW_INFO) {
9458                    Log.v(TAG, "    IntentFilter:");
9459                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9460                }
9461                removeFilter(intent);
9462            }
9463        }
9464
9465        @Override
9466        protected boolean allowFilterResult(
9467                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9468            ProviderInfo filterPi = filter.provider.info;
9469            for (int i = dest.size() - 1; i >= 0; i--) {
9470                ProviderInfo destPi = dest.get(i).providerInfo;
9471                if (destPi.name == filterPi.name
9472                        && destPi.packageName == filterPi.packageName) {
9473                    return false;
9474                }
9475            }
9476            return true;
9477        }
9478
9479        @Override
9480        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9481            return new PackageParser.ProviderIntentInfo[size];
9482        }
9483
9484        @Override
9485        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9486            if (!sUserManager.exists(userId))
9487                return true;
9488            PackageParser.Package p = filter.provider.owner;
9489            if (p != null) {
9490                PackageSetting ps = (PackageSetting) p.mExtras;
9491                if (ps != null) {
9492                    // System apps are never considered stopped for purposes of
9493                    // filtering, because there may be no way for the user to
9494                    // actually re-launch them.
9495                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9496                            && ps.getStopped(userId);
9497                }
9498            }
9499            return false;
9500        }
9501
9502        @Override
9503        protected boolean isPackageForFilter(String packageName,
9504                PackageParser.ProviderIntentInfo info) {
9505            return packageName.equals(info.provider.owner.packageName);
9506        }
9507
9508        @Override
9509        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9510                int match, int userId) {
9511            if (!sUserManager.exists(userId))
9512                return null;
9513            final PackageParser.ProviderIntentInfo info = filter;
9514            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9515                return null;
9516            }
9517            final PackageParser.Provider provider = info.provider;
9518            if (mSafeMode && (provider.info.applicationInfo.flags
9519                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9520                return null;
9521            }
9522            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9523            if (ps == null) {
9524                return null;
9525            }
9526            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9527                    ps.readUserState(userId), userId);
9528            if (pi == null) {
9529                return null;
9530            }
9531            final ResolveInfo res = new ResolveInfo();
9532            res.providerInfo = pi;
9533            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9534                res.filter = filter;
9535            }
9536            res.priority = info.getPriority();
9537            res.preferredOrder = provider.owner.mPreferredOrder;
9538            res.match = match;
9539            res.isDefault = info.hasDefault;
9540            res.labelRes = info.labelRes;
9541            res.nonLocalizedLabel = info.nonLocalizedLabel;
9542            res.icon = info.icon;
9543            res.system = res.providerInfo.applicationInfo.isSystemApp();
9544            return res;
9545        }
9546
9547        @Override
9548        protected void sortResults(List<ResolveInfo> results) {
9549            Collections.sort(results, mResolvePrioritySorter);
9550        }
9551
9552        @Override
9553        protected void dumpFilter(PrintWriter out, String prefix,
9554                PackageParser.ProviderIntentInfo filter) {
9555            out.print(prefix);
9556            out.print(
9557                    Integer.toHexString(System.identityHashCode(filter.provider)));
9558            out.print(' ');
9559            filter.provider.printComponentShortName(out);
9560            out.print(" filter ");
9561            out.println(Integer.toHexString(System.identityHashCode(filter)));
9562        }
9563
9564        @Override
9565        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9566            return filter.provider;
9567        }
9568
9569        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9570            PackageParser.Provider provider = (PackageParser.Provider)label;
9571            out.print(prefix); out.print(
9572                    Integer.toHexString(System.identityHashCode(provider)));
9573                    out.print(' ');
9574                    provider.printComponentShortName(out);
9575            if (count > 1) {
9576                out.print(" ("); out.print(count); out.print(" filters)");
9577            }
9578            out.println();
9579        }
9580
9581        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9582                = new ArrayMap<ComponentName, PackageParser.Provider>();
9583        private int mFlags;
9584    }
9585
9586    private static final class EphemeralIntentResolver
9587            extends IntentResolver<IntentFilter, ResolveInfo> {
9588        @Override
9589        protected IntentFilter[] newArray(int size) {
9590            return new IntentFilter[size];
9591        }
9592
9593        @Override
9594        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9595            return true;
9596        }
9597
9598        @Override
9599        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9600            if (!sUserManager.exists(userId)) return null;
9601            final ResolveInfo res = new ResolveInfo();
9602            res.filter = info;
9603            return res;
9604        }
9605    }
9606
9607    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9608            new Comparator<ResolveInfo>() {
9609        public int compare(ResolveInfo r1, ResolveInfo r2) {
9610            int v1 = r1.priority;
9611            int v2 = r2.priority;
9612            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9613            if (v1 != v2) {
9614                return (v1 > v2) ? -1 : 1;
9615            }
9616            v1 = r1.preferredOrder;
9617            v2 = r2.preferredOrder;
9618            if (v1 != v2) {
9619                return (v1 > v2) ? -1 : 1;
9620            }
9621            if (r1.isDefault != r2.isDefault) {
9622                return r1.isDefault ? -1 : 1;
9623            }
9624            v1 = r1.match;
9625            v2 = r2.match;
9626            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9627            if (v1 != v2) {
9628                return (v1 > v2) ? -1 : 1;
9629            }
9630            if (r1.system != r2.system) {
9631                return r1.system ? -1 : 1;
9632            }
9633            return 0;
9634        }
9635    };
9636
9637    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9638            new Comparator<ProviderInfo>() {
9639        public int compare(ProviderInfo p1, ProviderInfo p2) {
9640            final int v1 = p1.initOrder;
9641            final int v2 = p2.initOrder;
9642            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9643        }
9644    };
9645
9646    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9647            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9648            final int[] userIds) {
9649        mHandler.post(new Runnable() {
9650            @Override
9651            public void run() {
9652                try {
9653                    final IActivityManager am = ActivityManagerNative.getDefault();
9654                    if (am == null) return;
9655                    final int[] resolvedUserIds;
9656                    if (userIds == null) {
9657                        resolvedUserIds = am.getRunningUserIds();
9658                    } else {
9659                        resolvedUserIds = userIds;
9660                    }
9661                    for (int id : resolvedUserIds) {
9662                        final Intent intent = new Intent(action,
9663                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9664                        if (extras != null) {
9665                            intent.putExtras(extras);
9666                        }
9667                        if (targetPkg != null) {
9668                            intent.setPackage(targetPkg);
9669                        }
9670                        // Modify the UID when posting to other users
9671                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9672                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9673                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9674                            intent.putExtra(Intent.EXTRA_UID, uid);
9675                        }
9676                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9677                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9678                        if (DEBUG_BROADCASTS) {
9679                            RuntimeException here = new RuntimeException("here");
9680                            here.fillInStackTrace();
9681                            Slog.d(TAG, "Sending to user " + id + ": "
9682                                    + intent.toShortString(false, true, false, false)
9683                                    + " " + intent.getExtras(), here);
9684                        }
9685                        am.broadcastIntent(null, intent, null, finishedReceiver,
9686                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9687                                null, finishedReceiver != null, false, id);
9688                    }
9689                } catch (RemoteException ex) {
9690                }
9691            }
9692        });
9693    }
9694
9695    /**
9696     * Check if the external storage media is available. This is true if there
9697     * is a mounted external storage medium or if the external storage is
9698     * emulated.
9699     */
9700    private boolean isExternalMediaAvailable() {
9701        return mMediaMounted || Environment.isExternalStorageEmulated();
9702    }
9703
9704    @Override
9705    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9706        // writer
9707        synchronized (mPackages) {
9708            if (!isExternalMediaAvailable()) {
9709                // If the external storage is no longer mounted at this point,
9710                // the caller may not have been able to delete all of this
9711                // packages files and can not delete any more.  Bail.
9712                return null;
9713            }
9714            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9715            if (lastPackage != null) {
9716                pkgs.remove(lastPackage);
9717            }
9718            if (pkgs.size() > 0) {
9719                return pkgs.get(0);
9720            }
9721        }
9722        return null;
9723    }
9724
9725    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9726        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9727                userId, andCode ? 1 : 0, packageName);
9728        if (mSystemReady) {
9729            msg.sendToTarget();
9730        } else {
9731            if (mPostSystemReadyMessages == null) {
9732                mPostSystemReadyMessages = new ArrayList<>();
9733            }
9734            mPostSystemReadyMessages.add(msg);
9735        }
9736    }
9737
9738    void startCleaningPackages() {
9739        // reader
9740        synchronized (mPackages) {
9741            if (!isExternalMediaAvailable()) {
9742                return;
9743            }
9744            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9745                return;
9746            }
9747        }
9748        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9749        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9750        IActivityManager am = ActivityManagerNative.getDefault();
9751        if (am != null) {
9752            try {
9753                am.startService(null, intent, null, mContext.getOpPackageName(),
9754                        UserHandle.USER_SYSTEM);
9755            } catch (RemoteException e) {
9756            }
9757        }
9758    }
9759
9760    @Override
9761    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9762            int installFlags, String installerPackageName, VerificationParams verificationParams,
9763            String packageAbiOverride) {
9764        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9765                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9766    }
9767
9768    @Override
9769    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9770            int installFlags, String installerPackageName, VerificationParams verificationParams,
9771            String packageAbiOverride, int userId) {
9772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9773
9774        final int callingUid = Binder.getCallingUid();
9775        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9776
9777        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9778            try {
9779                if (observer != null) {
9780                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9781                }
9782            } catch (RemoteException re) {
9783            }
9784            return;
9785        }
9786
9787        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9788            installFlags |= PackageManager.INSTALL_FROM_ADB;
9789
9790        } else {
9791            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9792            // about installerPackageName.
9793
9794            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9795            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9796        }
9797
9798        UserHandle user;
9799        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9800            user = UserHandle.ALL;
9801        } else {
9802            user = new UserHandle(userId);
9803        }
9804
9805        // Only system components can circumvent runtime permissions when installing.
9806        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9807                && mContext.checkCallingOrSelfPermission(Manifest.permission
9808                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9809            throw new SecurityException("You need the "
9810                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9811                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9812        }
9813
9814        verificationParams.setInstallerUid(callingUid);
9815
9816        final File originFile = new File(originPath);
9817        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9818
9819        final Message msg = mHandler.obtainMessage(INIT_COPY);
9820        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9821                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9822        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9823        msg.obj = params;
9824
9825        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9826                System.identityHashCode(msg.obj));
9827        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9828                System.identityHashCode(msg.obj));
9829
9830        mHandler.sendMessage(msg);
9831    }
9832
9833    void installStage(String packageName, File stagedDir, String stagedCid,
9834            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9835            String installerPackageName, int installerUid, UserHandle user) {
9836        final VerificationParams verifParams = new VerificationParams(
9837                null, sessionParams.originatingUri, sessionParams.referrerUri,
9838                sessionParams.originatingUid, null);
9839        verifParams.setInstallerUid(installerUid);
9840
9841        final OriginInfo origin;
9842        if (stagedDir != null) {
9843            origin = OriginInfo.fromStagedFile(stagedDir);
9844        } else {
9845            origin = OriginInfo.fromStagedContainer(stagedCid);
9846        }
9847
9848        final Message msg = mHandler.obtainMessage(INIT_COPY);
9849        final InstallParams params = new InstallParams(origin, null, observer,
9850                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9851                verifParams, user, sessionParams.abiOverride,
9852                sessionParams.grantedRuntimePermissions);
9853        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9854        msg.obj = params;
9855
9856        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9857                System.identityHashCode(msg.obj));
9858        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9859                System.identityHashCode(msg.obj));
9860
9861        mHandler.sendMessage(msg);
9862    }
9863
9864    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9865        Bundle extras = new Bundle(1);
9866        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9867
9868        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9869                packageName, extras, 0, null, null, new int[] {userId});
9870        try {
9871            IActivityManager am = ActivityManagerNative.getDefault();
9872            final boolean isSystem =
9873                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9874            if (isSystem && am.isUserRunning(userId, 0)) {
9875                // The just-installed/enabled app is bundled on the system, so presumed
9876                // to be able to run automatically without needing an explicit launch.
9877                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9878                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9879                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9880                        .setPackage(packageName);
9881                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9882                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9883            }
9884        } catch (RemoteException e) {
9885            // shouldn't happen
9886            Slog.w(TAG, "Unable to bootstrap installed package", e);
9887        }
9888    }
9889
9890    @Override
9891    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9892            int userId) {
9893        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9894        PackageSetting pkgSetting;
9895        final int uid = Binder.getCallingUid();
9896        enforceCrossUserPermission(uid, userId, true, true,
9897                "setApplicationHiddenSetting for user " + userId);
9898
9899        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9900            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9901            return false;
9902        }
9903
9904        long callingId = Binder.clearCallingIdentity();
9905        try {
9906            boolean sendAdded = false;
9907            boolean sendRemoved = false;
9908            // writer
9909            synchronized (mPackages) {
9910                pkgSetting = mSettings.mPackages.get(packageName);
9911                if (pkgSetting == null) {
9912                    return false;
9913                }
9914                if (pkgSetting.getHidden(userId) != hidden) {
9915                    pkgSetting.setHidden(hidden, userId);
9916                    mSettings.writePackageRestrictionsLPr(userId);
9917                    if (hidden) {
9918                        sendRemoved = true;
9919                    } else {
9920                        sendAdded = true;
9921                    }
9922                }
9923            }
9924            if (sendAdded) {
9925                sendPackageAddedForUser(packageName, pkgSetting, userId);
9926                return true;
9927            }
9928            if (sendRemoved) {
9929                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9930                        "hiding pkg");
9931                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9932                return true;
9933            }
9934        } finally {
9935            Binder.restoreCallingIdentity(callingId);
9936        }
9937        return false;
9938    }
9939
9940    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9941            int userId) {
9942        final PackageRemovedInfo info = new PackageRemovedInfo();
9943        info.removedPackage = packageName;
9944        info.removedUsers = new int[] {userId};
9945        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9946        info.sendBroadcast(false, false, false);
9947    }
9948
9949    /**
9950     * Returns true if application is not found or there was an error. Otherwise it returns
9951     * the hidden state of the package for the given user.
9952     */
9953    @Override
9954    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9955        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9956        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9957                false, "getApplicationHidden for user " + userId);
9958        PackageSetting pkgSetting;
9959        long callingId = Binder.clearCallingIdentity();
9960        try {
9961            // writer
9962            synchronized (mPackages) {
9963                pkgSetting = mSettings.mPackages.get(packageName);
9964                if (pkgSetting == null) {
9965                    return true;
9966                }
9967                return pkgSetting.getHidden(userId);
9968            }
9969        } finally {
9970            Binder.restoreCallingIdentity(callingId);
9971        }
9972    }
9973
9974    /**
9975     * @hide
9976     */
9977    @Override
9978    public int installExistingPackageAsUser(String packageName, int userId) {
9979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9980                null);
9981        PackageSetting pkgSetting;
9982        final int uid = Binder.getCallingUid();
9983        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9984                + userId);
9985        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9986            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9987        }
9988
9989        long callingId = Binder.clearCallingIdentity();
9990        try {
9991            boolean sendAdded = false;
9992
9993            // writer
9994            synchronized (mPackages) {
9995                pkgSetting = mSettings.mPackages.get(packageName);
9996                if (pkgSetting == null) {
9997                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9998                }
9999                if (!pkgSetting.getInstalled(userId)) {
10000                    pkgSetting.setInstalled(true, userId);
10001                    pkgSetting.setHidden(false, userId);
10002                    mSettings.writePackageRestrictionsLPr(userId);
10003                    sendAdded = true;
10004                }
10005            }
10006
10007            if (sendAdded) {
10008                sendPackageAddedForUser(packageName, pkgSetting, userId);
10009            }
10010        } finally {
10011            Binder.restoreCallingIdentity(callingId);
10012        }
10013
10014        return PackageManager.INSTALL_SUCCEEDED;
10015    }
10016
10017    boolean isUserRestricted(int userId, String restrictionKey) {
10018        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10019        if (restrictions.getBoolean(restrictionKey, false)) {
10020            Log.w(TAG, "User is restricted: " + restrictionKey);
10021            return true;
10022        }
10023        return false;
10024    }
10025
10026    @Override
10027    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10028        mContext.enforceCallingOrSelfPermission(
10029                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10030                "Only package verification agents can verify applications");
10031
10032        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10033        final PackageVerificationResponse response = new PackageVerificationResponse(
10034                verificationCode, Binder.getCallingUid());
10035        msg.arg1 = id;
10036        msg.obj = response;
10037        mHandler.sendMessage(msg);
10038    }
10039
10040    @Override
10041    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10042            long millisecondsToDelay) {
10043        mContext.enforceCallingOrSelfPermission(
10044                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10045                "Only package verification agents can extend verification timeouts");
10046
10047        final PackageVerificationState state = mPendingVerification.get(id);
10048        final PackageVerificationResponse response = new PackageVerificationResponse(
10049                verificationCodeAtTimeout, Binder.getCallingUid());
10050
10051        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10052            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10053        }
10054        if (millisecondsToDelay < 0) {
10055            millisecondsToDelay = 0;
10056        }
10057        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10058                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10059            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10060        }
10061
10062        if ((state != null) && !state.timeoutExtended()) {
10063            state.extendTimeout();
10064
10065            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10066            msg.arg1 = id;
10067            msg.obj = response;
10068            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10069        }
10070    }
10071
10072    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10073            int verificationCode, UserHandle user) {
10074        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10075        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10076        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10077        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10078        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10079
10080        mContext.sendBroadcastAsUser(intent, user,
10081                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10082    }
10083
10084    private ComponentName matchComponentForVerifier(String packageName,
10085            List<ResolveInfo> receivers) {
10086        ActivityInfo targetReceiver = null;
10087
10088        final int NR = receivers.size();
10089        for (int i = 0; i < NR; i++) {
10090            final ResolveInfo info = receivers.get(i);
10091            if (info.activityInfo == null) {
10092                continue;
10093            }
10094
10095            if (packageName.equals(info.activityInfo.packageName)) {
10096                targetReceiver = info.activityInfo;
10097                break;
10098            }
10099        }
10100
10101        if (targetReceiver == null) {
10102            return null;
10103        }
10104
10105        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10106    }
10107
10108    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10109            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10110        if (pkgInfo.verifiers.length == 0) {
10111            return null;
10112        }
10113
10114        final int N = pkgInfo.verifiers.length;
10115        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10116        for (int i = 0; i < N; i++) {
10117            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10118
10119            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10120                    receivers);
10121            if (comp == null) {
10122                continue;
10123            }
10124
10125            final int verifierUid = getUidForVerifier(verifierInfo);
10126            if (verifierUid == -1) {
10127                continue;
10128            }
10129
10130            if (DEBUG_VERIFY) {
10131                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10132                        + " with the correct signature");
10133            }
10134            sufficientVerifiers.add(comp);
10135            verificationState.addSufficientVerifier(verifierUid);
10136        }
10137
10138        return sufficientVerifiers;
10139    }
10140
10141    private int getUidForVerifier(VerifierInfo verifierInfo) {
10142        synchronized (mPackages) {
10143            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10144            if (pkg == null) {
10145                return -1;
10146            } else if (pkg.mSignatures.length != 1) {
10147                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10148                        + " has more than one signature; ignoring");
10149                return -1;
10150            }
10151
10152            /*
10153             * If the public key of the package's signature does not match
10154             * our expected public key, then this is a different package and
10155             * we should skip.
10156             */
10157
10158            final byte[] expectedPublicKey;
10159            try {
10160                final Signature verifierSig = pkg.mSignatures[0];
10161                final PublicKey publicKey = verifierSig.getPublicKey();
10162                expectedPublicKey = publicKey.getEncoded();
10163            } catch (CertificateException e) {
10164                return -1;
10165            }
10166
10167            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10168
10169            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10170                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10171                        + " does not have the expected public key; ignoring");
10172                return -1;
10173            }
10174
10175            return pkg.applicationInfo.uid;
10176        }
10177    }
10178
10179    @Override
10180    public void finishPackageInstall(int token) {
10181        enforceSystemOrRoot("Only the system is allowed to finish installs");
10182
10183        if (DEBUG_INSTALL) {
10184            Slog.v(TAG, "BM finishing package install for " + token);
10185        }
10186        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10187
10188        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10189        mHandler.sendMessage(msg);
10190    }
10191
10192    /**
10193     * Get the verification agent timeout.
10194     *
10195     * @return verification timeout in milliseconds
10196     */
10197    private long getVerificationTimeout() {
10198        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10199                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10200                DEFAULT_VERIFICATION_TIMEOUT);
10201    }
10202
10203    /**
10204     * Get the default verification agent response code.
10205     *
10206     * @return default verification response code
10207     */
10208    private int getDefaultVerificationResponse() {
10209        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10210                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10211                DEFAULT_VERIFICATION_RESPONSE);
10212    }
10213
10214    /**
10215     * Check whether or not package verification has been enabled.
10216     *
10217     * @return true if verification should be performed
10218     */
10219    private boolean isVerificationEnabled(int userId, int installFlags) {
10220        if (!DEFAULT_VERIFY_ENABLE) {
10221            return false;
10222        }
10223        // TODO: fix b/25118622; don't bypass verification
10224        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10225            return false;
10226        }
10227
10228        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10229
10230        // Check if installing from ADB
10231        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10232            // Do not run verification in a test harness environment
10233            if (ActivityManager.isRunningInTestHarness()) {
10234                return false;
10235            }
10236            if (ensureVerifyAppsEnabled) {
10237                return true;
10238            }
10239            // Check if the developer does not want package verification for ADB installs
10240            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10241                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10242                return false;
10243            }
10244        }
10245
10246        if (ensureVerifyAppsEnabled) {
10247            return true;
10248        }
10249
10250        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10251                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10252    }
10253
10254    @Override
10255    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10256            throws RemoteException {
10257        mContext.enforceCallingOrSelfPermission(
10258                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10259                "Only intentfilter verification agents can verify applications");
10260
10261        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10262        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10263                Binder.getCallingUid(), verificationCode, failedDomains);
10264        msg.arg1 = id;
10265        msg.obj = response;
10266        mHandler.sendMessage(msg);
10267    }
10268
10269    @Override
10270    public int getIntentVerificationStatus(String packageName, int userId) {
10271        synchronized (mPackages) {
10272            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10273        }
10274    }
10275
10276    @Override
10277    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10278        mContext.enforceCallingOrSelfPermission(
10279                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10280
10281        boolean result = false;
10282        synchronized (mPackages) {
10283            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10284        }
10285        if (result) {
10286            scheduleWritePackageRestrictionsLocked(userId);
10287        }
10288        return result;
10289    }
10290
10291    @Override
10292    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10293        synchronized (mPackages) {
10294            return mSettings.getIntentFilterVerificationsLPr(packageName);
10295        }
10296    }
10297
10298    @Override
10299    public List<IntentFilter> getAllIntentFilters(String packageName) {
10300        if (TextUtils.isEmpty(packageName)) {
10301            return Collections.<IntentFilter>emptyList();
10302        }
10303        synchronized (mPackages) {
10304            PackageParser.Package pkg = mPackages.get(packageName);
10305            if (pkg == null || pkg.activities == null) {
10306                return Collections.<IntentFilter>emptyList();
10307            }
10308            final int count = pkg.activities.size();
10309            ArrayList<IntentFilter> result = new ArrayList<>();
10310            for (int n=0; n<count; n++) {
10311                PackageParser.Activity activity = pkg.activities.get(n);
10312                if (activity.intents != null || activity.intents.size() > 0) {
10313                    result.addAll(activity.intents);
10314                }
10315            }
10316            return result;
10317        }
10318    }
10319
10320    @Override
10321    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10322        mContext.enforceCallingOrSelfPermission(
10323                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10324
10325        synchronized (mPackages) {
10326            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10327            if (packageName != null) {
10328                result |= updateIntentVerificationStatus(packageName,
10329                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10330                        userId);
10331                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10332                        packageName, userId);
10333            }
10334            return result;
10335        }
10336    }
10337
10338    @Override
10339    public String getDefaultBrowserPackageName(int userId) {
10340        synchronized (mPackages) {
10341            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10342        }
10343    }
10344
10345    /**
10346     * Get the "allow unknown sources" setting.
10347     *
10348     * @return the current "allow unknown sources" setting
10349     */
10350    private int getUnknownSourcesSettings() {
10351        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10352                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10353                -1);
10354    }
10355
10356    @Override
10357    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10358        final int uid = Binder.getCallingUid();
10359        // writer
10360        synchronized (mPackages) {
10361            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10362            if (targetPackageSetting == null) {
10363                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10364            }
10365
10366            PackageSetting installerPackageSetting;
10367            if (installerPackageName != null) {
10368                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10369                if (installerPackageSetting == null) {
10370                    throw new IllegalArgumentException("Unknown installer package: "
10371                            + installerPackageName);
10372                }
10373            } else {
10374                installerPackageSetting = null;
10375            }
10376
10377            Signature[] callerSignature;
10378            Object obj = mSettings.getUserIdLPr(uid);
10379            if (obj != null) {
10380                if (obj instanceof SharedUserSetting) {
10381                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10382                } else if (obj instanceof PackageSetting) {
10383                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10384                } else {
10385                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10386                }
10387            } else {
10388                throw new SecurityException("Unknown calling uid " + uid);
10389            }
10390
10391            // Verify: can't set installerPackageName to a package that is
10392            // not signed with the same cert as the caller.
10393            if (installerPackageSetting != null) {
10394                if (compareSignatures(callerSignature,
10395                        installerPackageSetting.signatures.mSignatures)
10396                        != PackageManager.SIGNATURE_MATCH) {
10397                    throw new SecurityException(
10398                            "Caller does not have same cert as new installer package "
10399                            + installerPackageName);
10400                }
10401            }
10402
10403            // Verify: if target already has an installer package, it must
10404            // be signed with the same cert as the caller.
10405            if (targetPackageSetting.installerPackageName != null) {
10406                PackageSetting setting = mSettings.mPackages.get(
10407                        targetPackageSetting.installerPackageName);
10408                // If the currently set package isn't valid, then it's always
10409                // okay to change it.
10410                if (setting != null) {
10411                    if (compareSignatures(callerSignature,
10412                            setting.signatures.mSignatures)
10413                            != PackageManager.SIGNATURE_MATCH) {
10414                        throw new SecurityException(
10415                                "Caller does not have same cert as old installer package "
10416                                + targetPackageSetting.installerPackageName);
10417                    }
10418                }
10419            }
10420
10421            // Okay!
10422            targetPackageSetting.installerPackageName = installerPackageName;
10423            scheduleWriteSettingsLocked();
10424        }
10425    }
10426
10427    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10428        // Queue up an async operation since the package installation may take a little while.
10429        mHandler.post(new Runnable() {
10430            public void run() {
10431                mHandler.removeCallbacks(this);
10432                 // Result object to be returned
10433                PackageInstalledInfo res = new PackageInstalledInfo();
10434                res.returnCode = currentStatus;
10435                res.uid = -1;
10436                res.pkg = null;
10437                res.removedInfo = new PackageRemovedInfo();
10438                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10439                    args.doPreInstall(res.returnCode);
10440                    synchronized (mInstallLock) {
10441                        installPackageTracedLI(args, res);
10442                    }
10443                    args.doPostInstall(res.returnCode, res.uid);
10444                }
10445
10446                // A restore should be performed at this point if (a) the install
10447                // succeeded, (b) the operation is not an update, and (c) the new
10448                // package has not opted out of backup participation.
10449                final boolean update = res.removedInfo.removedPackage != null;
10450                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10451                boolean doRestore = !update
10452                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10453
10454                // Set up the post-install work request bookkeeping.  This will be used
10455                // and cleaned up by the post-install event handling regardless of whether
10456                // there's a restore pass performed.  Token values are >= 1.
10457                int token;
10458                if (mNextInstallToken < 0) mNextInstallToken = 1;
10459                token = mNextInstallToken++;
10460
10461                PostInstallData data = new PostInstallData(args, res);
10462                mRunningInstalls.put(token, data);
10463                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10464
10465                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10466                    // Pass responsibility to the Backup Manager.  It will perform a
10467                    // restore if appropriate, then pass responsibility back to the
10468                    // Package Manager to run the post-install observer callbacks
10469                    // and broadcasts.
10470                    IBackupManager bm = IBackupManager.Stub.asInterface(
10471                            ServiceManager.getService(Context.BACKUP_SERVICE));
10472                    if (bm != null) {
10473                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10474                                + " to BM for possible restore");
10475                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10476                        try {
10477                            // TODO: http://b/22388012
10478                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10479                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10480                            } else {
10481                                doRestore = false;
10482                            }
10483                        } catch (RemoteException e) {
10484                            // can't happen; the backup manager is local
10485                        } catch (Exception e) {
10486                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10487                            doRestore = false;
10488                        }
10489                    } else {
10490                        Slog.e(TAG, "Backup Manager not found!");
10491                        doRestore = false;
10492                    }
10493                }
10494
10495                if (!doRestore) {
10496                    // No restore possible, or the Backup Manager was mysteriously not
10497                    // available -- just fire the post-install work request directly.
10498                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10499
10500                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10501
10502                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10503                    mHandler.sendMessage(msg);
10504                }
10505            }
10506        });
10507    }
10508
10509    private abstract class HandlerParams {
10510        private static final int MAX_RETRIES = 4;
10511
10512        /**
10513         * Number of times startCopy() has been attempted and had a non-fatal
10514         * error.
10515         */
10516        private int mRetries = 0;
10517
10518        /** User handle for the user requesting the information or installation. */
10519        private final UserHandle mUser;
10520        String traceMethod;
10521        int traceCookie;
10522
10523        HandlerParams(UserHandle user) {
10524            mUser = user;
10525        }
10526
10527        UserHandle getUser() {
10528            return mUser;
10529        }
10530
10531        HandlerParams setTraceMethod(String traceMethod) {
10532            this.traceMethod = traceMethod;
10533            return this;
10534        }
10535
10536        HandlerParams setTraceCookie(int traceCookie) {
10537            this.traceCookie = traceCookie;
10538            return this;
10539        }
10540
10541        final boolean startCopy() {
10542            boolean res;
10543            try {
10544                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10545
10546                if (++mRetries > MAX_RETRIES) {
10547                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10548                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10549                    handleServiceError();
10550                    return false;
10551                } else {
10552                    handleStartCopy();
10553                    res = true;
10554                }
10555            } catch (RemoteException e) {
10556                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10557                mHandler.sendEmptyMessage(MCS_RECONNECT);
10558                res = false;
10559            }
10560            handleReturnCode();
10561            return res;
10562        }
10563
10564        final void serviceError() {
10565            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10566            handleServiceError();
10567            handleReturnCode();
10568        }
10569
10570        abstract void handleStartCopy() throws RemoteException;
10571        abstract void handleServiceError();
10572        abstract void handleReturnCode();
10573    }
10574
10575    class MeasureParams extends HandlerParams {
10576        private final PackageStats mStats;
10577        private boolean mSuccess;
10578
10579        private final IPackageStatsObserver mObserver;
10580
10581        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10582            super(new UserHandle(stats.userHandle));
10583            mObserver = observer;
10584            mStats = stats;
10585        }
10586
10587        @Override
10588        public String toString() {
10589            return "MeasureParams{"
10590                + Integer.toHexString(System.identityHashCode(this))
10591                + " " + mStats.packageName + "}";
10592        }
10593
10594        @Override
10595        void handleStartCopy() throws RemoteException {
10596            synchronized (mInstallLock) {
10597                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10598            }
10599
10600            if (mSuccess) {
10601                final boolean mounted;
10602                if (Environment.isExternalStorageEmulated()) {
10603                    mounted = true;
10604                } else {
10605                    final String status = Environment.getExternalStorageState();
10606                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10607                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10608                }
10609
10610                if (mounted) {
10611                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10612
10613                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10614                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10615
10616                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10617                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10618
10619                    // Always subtract cache size, since it's a subdirectory
10620                    mStats.externalDataSize -= mStats.externalCacheSize;
10621
10622                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10623                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10624
10625                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10626                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10627                }
10628            }
10629        }
10630
10631        @Override
10632        void handleReturnCode() {
10633            if (mObserver != null) {
10634                try {
10635                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10636                } catch (RemoteException e) {
10637                    Slog.i(TAG, "Observer no longer exists.");
10638                }
10639            }
10640        }
10641
10642        @Override
10643        void handleServiceError() {
10644            Slog.e(TAG, "Could not measure application " + mStats.packageName
10645                            + " external storage");
10646        }
10647    }
10648
10649    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10650            throws RemoteException {
10651        long result = 0;
10652        for (File path : paths) {
10653            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10654        }
10655        return result;
10656    }
10657
10658    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10659        for (File path : paths) {
10660            try {
10661                mcs.clearDirectory(path.getAbsolutePath());
10662            } catch (RemoteException e) {
10663            }
10664        }
10665    }
10666
10667    static class OriginInfo {
10668        /**
10669         * Location where install is coming from, before it has been
10670         * copied/renamed into place. This could be a single monolithic APK
10671         * file, or a cluster directory. This location may be untrusted.
10672         */
10673        final File file;
10674        final String cid;
10675
10676        /**
10677         * Flag indicating that {@link #file} or {@link #cid} has already been
10678         * staged, meaning downstream users don't need to defensively copy the
10679         * contents.
10680         */
10681        final boolean staged;
10682
10683        /**
10684         * Flag indicating that {@link #file} or {@link #cid} is an already
10685         * installed app that is being moved.
10686         */
10687        final boolean existing;
10688
10689        final String resolvedPath;
10690        final File resolvedFile;
10691
10692        static OriginInfo fromNothing() {
10693            return new OriginInfo(null, null, false, false);
10694        }
10695
10696        static OriginInfo fromUntrustedFile(File file) {
10697            return new OriginInfo(file, null, false, false);
10698        }
10699
10700        static OriginInfo fromExistingFile(File file) {
10701            return new OriginInfo(file, null, false, true);
10702        }
10703
10704        static OriginInfo fromStagedFile(File file) {
10705            return new OriginInfo(file, null, true, false);
10706        }
10707
10708        static OriginInfo fromStagedContainer(String cid) {
10709            return new OriginInfo(null, cid, true, false);
10710        }
10711
10712        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10713            this.file = file;
10714            this.cid = cid;
10715            this.staged = staged;
10716            this.existing = existing;
10717
10718            if (cid != null) {
10719                resolvedPath = PackageHelper.getSdDir(cid);
10720                resolvedFile = new File(resolvedPath);
10721            } else if (file != null) {
10722                resolvedPath = file.getAbsolutePath();
10723                resolvedFile = file;
10724            } else {
10725                resolvedPath = null;
10726                resolvedFile = null;
10727            }
10728        }
10729    }
10730
10731    class MoveInfo {
10732        final int moveId;
10733        final String fromUuid;
10734        final String toUuid;
10735        final String packageName;
10736        final String dataAppName;
10737        final int appId;
10738        final String seinfo;
10739
10740        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10741                String dataAppName, int appId, String seinfo) {
10742            this.moveId = moveId;
10743            this.fromUuid = fromUuid;
10744            this.toUuid = toUuid;
10745            this.packageName = packageName;
10746            this.dataAppName = dataAppName;
10747            this.appId = appId;
10748            this.seinfo = seinfo;
10749        }
10750    }
10751
10752    class InstallParams extends HandlerParams {
10753        final OriginInfo origin;
10754        final MoveInfo move;
10755        final IPackageInstallObserver2 observer;
10756        int installFlags;
10757        final String installerPackageName;
10758        final String volumeUuid;
10759        final VerificationParams verificationParams;
10760        private InstallArgs mArgs;
10761        private int mRet;
10762        final String packageAbiOverride;
10763        final String[] grantedRuntimePermissions;
10764
10765        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10766                int installFlags, String installerPackageName, String volumeUuid,
10767                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10768                String[] grantedPermissions) {
10769            super(user);
10770            this.origin = origin;
10771            this.move = move;
10772            this.observer = observer;
10773            this.installFlags = installFlags;
10774            this.installerPackageName = installerPackageName;
10775            this.volumeUuid = volumeUuid;
10776            this.verificationParams = verificationParams;
10777            this.packageAbiOverride = packageAbiOverride;
10778            this.grantedRuntimePermissions = grantedPermissions;
10779        }
10780
10781        @Override
10782        public String toString() {
10783            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10784                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10785        }
10786
10787        public ManifestDigest getManifestDigest() {
10788            if (verificationParams == null) {
10789                return null;
10790            }
10791            return verificationParams.getManifestDigest();
10792        }
10793
10794        private int installLocationPolicy(PackageInfoLite pkgLite) {
10795            String packageName = pkgLite.packageName;
10796            int installLocation = pkgLite.installLocation;
10797            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10798            // reader
10799            synchronized (mPackages) {
10800                PackageParser.Package pkg = mPackages.get(packageName);
10801                if (pkg != null) {
10802                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10803                        // Check for downgrading.
10804                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10805                            try {
10806                                checkDowngrade(pkg, pkgLite);
10807                            } catch (PackageManagerException e) {
10808                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10809                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10810                            }
10811                        }
10812                        // Check for updated system application.
10813                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10814                            if (onSd) {
10815                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10816                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10817                            }
10818                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10819                        } else {
10820                            if (onSd) {
10821                                // Install flag overrides everything.
10822                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10823                            }
10824                            // If current upgrade specifies particular preference
10825                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10826                                // Application explicitly specified internal.
10827                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10828                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10829                                // App explictly prefers external. Let policy decide
10830                            } else {
10831                                // Prefer previous location
10832                                if (isExternal(pkg)) {
10833                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10834                                }
10835                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10836                            }
10837                        }
10838                    } else {
10839                        // Invalid install. Return error code
10840                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10841                    }
10842                }
10843            }
10844            // All the special cases have been taken care of.
10845            // Return result based on recommended install location.
10846            if (onSd) {
10847                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10848            }
10849            return pkgLite.recommendedInstallLocation;
10850        }
10851
10852        /*
10853         * Invoke remote method to get package information and install
10854         * location values. Override install location based on default
10855         * policy if needed and then create install arguments based
10856         * on the install location.
10857         */
10858        public void handleStartCopy() throws RemoteException {
10859            int ret = PackageManager.INSTALL_SUCCEEDED;
10860
10861            // If we're already staged, we've firmly committed to an install location
10862            if (origin.staged) {
10863                if (origin.file != null) {
10864                    installFlags |= PackageManager.INSTALL_INTERNAL;
10865                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10866                } else if (origin.cid != null) {
10867                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10868                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10869                } else {
10870                    throw new IllegalStateException("Invalid stage location");
10871                }
10872            }
10873
10874            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10875            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10876            PackageInfoLite pkgLite = null;
10877
10878            if (onInt && onSd) {
10879                // Check if both bits are set.
10880                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10881                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10882            } else {
10883                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10884                        packageAbiOverride);
10885
10886                /*
10887                 * If we have too little free space, try to free cache
10888                 * before giving up.
10889                 */
10890                if (!origin.staged && pkgLite.recommendedInstallLocation
10891                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10892                    // TODO: focus freeing disk space on the target device
10893                    final StorageManager storage = StorageManager.from(mContext);
10894                    final long lowThreshold = storage.getStorageLowBytes(
10895                            Environment.getDataDirectory());
10896
10897                    final long sizeBytes = mContainerService.calculateInstalledSize(
10898                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10899
10900                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10901                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10902                                installFlags, packageAbiOverride);
10903                    }
10904
10905                    /*
10906                     * The cache free must have deleted the file we
10907                     * downloaded to install.
10908                     *
10909                     * TODO: fix the "freeCache" call to not delete
10910                     *       the file we care about.
10911                     */
10912                    if (pkgLite.recommendedInstallLocation
10913                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10914                        pkgLite.recommendedInstallLocation
10915                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10916                    }
10917                }
10918            }
10919
10920            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10921                int loc = pkgLite.recommendedInstallLocation;
10922                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10923                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10924                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10925                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10926                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10927                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10928                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10929                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10930                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10931                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10932                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10933                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10934                } else {
10935                    // Override with defaults if needed.
10936                    loc = installLocationPolicy(pkgLite);
10937                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10938                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10939                    } else if (!onSd && !onInt) {
10940                        // Override install location with flags
10941                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10942                            // Set the flag to install on external media.
10943                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10944                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10945                        } else {
10946                            // Make sure the flag for installing on external
10947                            // media is unset
10948                            installFlags |= PackageManager.INSTALL_INTERNAL;
10949                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10950                        }
10951                    }
10952                }
10953            }
10954
10955            final InstallArgs args = createInstallArgs(this);
10956            mArgs = args;
10957
10958            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10959                // TODO: http://b/22976637
10960                // Apps installed for "all" users use the device owner to verify the app
10961                UserHandle verifierUser = getUser();
10962                if (verifierUser == UserHandle.ALL) {
10963                    verifierUser = UserHandle.SYSTEM;
10964                }
10965
10966                /*
10967                 * Determine if we have any installed package verifiers. If we
10968                 * do, then we'll defer to them to verify the packages.
10969                 */
10970                final int requiredUid = mRequiredVerifierPackage == null ? -1
10971                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10972                if (!origin.existing && requiredUid != -1
10973                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10974                    final Intent verification = new Intent(
10975                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10976                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10977                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10978                            PACKAGE_MIME_TYPE);
10979                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10980
10981                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10982                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10983                            verifierUser.getIdentifier());
10984
10985                    if (DEBUG_VERIFY) {
10986                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10987                                + verification.toString() + " with " + pkgLite.verifiers.length
10988                                + " optional verifiers");
10989                    }
10990
10991                    final int verificationId = mPendingVerificationToken++;
10992
10993                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10994
10995                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10996                            installerPackageName);
10997
10998                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10999                            installFlags);
11000
11001                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11002                            pkgLite.packageName);
11003
11004                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11005                            pkgLite.versionCode);
11006
11007                    if (verificationParams != null) {
11008                        if (verificationParams.getVerificationURI() != null) {
11009                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11010                                 verificationParams.getVerificationURI());
11011                        }
11012                        if (verificationParams.getOriginatingURI() != null) {
11013                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11014                                  verificationParams.getOriginatingURI());
11015                        }
11016                        if (verificationParams.getReferrer() != null) {
11017                            verification.putExtra(Intent.EXTRA_REFERRER,
11018                                  verificationParams.getReferrer());
11019                        }
11020                        if (verificationParams.getOriginatingUid() >= 0) {
11021                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11022                                  verificationParams.getOriginatingUid());
11023                        }
11024                        if (verificationParams.getInstallerUid() >= 0) {
11025                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11026                                  verificationParams.getInstallerUid());
11027                        }
11028                    }
11029
11030                    final PackageVerificationState verificationState = new PackageVerificationState(
11031                            requiredUid, args);
11032
11033                    mPendingVerification.append(verificationId, verificationState);
11034
11035                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11036                            receivers, verificationState);
11037
11038                    /*
11039                     * If any sufficient verifiers were listed in the package
11040                     * manifest, attempt to ask them.
11041                     */
11042                    if (sufficientVerifiers != null) {
11043                        final int N = sufficientVerifiers.size();
11044                        if (N == 0) {
11045                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11046                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11047                        } else {
11048                            for (int i = 0; i < N; i++) {
11049                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11050
11051                                final Intent sufficientIntent = new Intent(verification);
11052                                sufficientIntent.setComponent(verifierComponent);
11053                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11054                            }
11055                        }
11056                    }
11057
11058                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11059                            mRequiredVerifierPackage, receivers);
11060                    if (ret == PackageManager.INSTALL_SUCCEEDED
11061                            && mRequiredVerifierPackage != null) {
11062                        Trace.asyncTraceBegin(
11063                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11064                        /*
11065                         * Send the intent to the required verification agent,
11066                         * but only start the verification timeout after the
11067                         * target BroadcastReceivers have run.
11068                         */
11069                        verification.setComponent(requiredVerifierComponent);
11070                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11071                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11072                                new BroadcastReceiver() {
11073                                    @Override
11074                                    public void onReceive(Context context, Intent intent) {
11075                                        final Message msg = mHandler
11076                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11077                                        msg.arg1 = verificationId;
11078                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11079                                    }
11080                                }, null, 0, null, null);
11081
11082                        /*
11083                         * We don't want the copy to proceed until verification
11084                         * succeeds, so null out this field.
11085                         */
11086                        mArgs = null;
11087                    }
11088                } else {
11089                    /*
11090                     * No package verification is enabled, so immediately start
11091                     * the remote call to initiate copy using temporary file.
11092                     */
11093                    ret = args.copyApk(mContainerService, true);
11094                }
11095            }
11096
11097            mRet = ret;
11098        }
11099
11100        @Override
11101        void handleReturnCode() {
11102            // If mArgs is null, then MCS couldn't be reached. When it
11103            // reconnects, it will try again to install. At that point, this
11104            // will succeed.
11105            if (mArgs != null) {
11106                processPendingInstall(mArgs, mRet);
11107            }
11108        }
11109
11110        @Override
11111        void handleServiceError() {
11112            mArgs = createInstallArgs(this);
11113            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11114        }
11115
11116        public boolean isForwardLocked() {
11117            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11118        }
11119    }
11120
11121    /**
11122     * Used during creation of InstallArgs
11123     *
11124     * @param installFlags package installation flags
11125     * @return true if should be installed on external storage
11126     */
11127    private static boolean installOnExternalAsec(int installFlags) {
11128        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11129            return false;
11130        }
11131        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11132            return true;
11133        }
11134        return false;
11135    }
11136
11137    /**
11138     * Used during creation of InstallArgs
11139     *
11140     * @param installFlags package installation flags
11141     * @return true if should be installed as forward locked
11142     */
11143    private static boolean installForwardLocked(int installFlags) {
11144        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11145    }
11146
11147    private InstallArgs createInstallArgs(InstallParams params) {
11148        if (params.move != null) {
11149            return new MoveInstallArgs(params);
11150        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11151            return new AsecInstallArgs(params);
11152        } else {
11153            return new FileInstallArgs(params);
11154        }
11155    }
11156
11157    /**
11158     * Create args that describe an existing installed package. Typically used
11159     * when cleaning up old installs, or used as a move source.
11160     */
11161    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11162            String resourcePath, String[] instructionSets) {
11163        final boolean isInAsec;
11164        if (installOnExternalAsec(installFlags)) {
11165            /* Apps on SD card are always in ASEC containers. */
11166            isInAsec = true;
11167        } else if (installForwardLocked(installFlags)
11168                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11169            /*
11170             * Forward-locked apps are only in ASEC containers if they're the
11171             * new style
11172             */
11173            isInAsec = true;
11174        } else {
11175            isInAsec = false;
11176        }
11177
11178        if (isInAsec) {
11179            return new AsecInstallArgs(codePath, instructionSets,
11180                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11181        } else {
11182            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11183        }
11184    }
11185
11186    static abstract class InstallArgs {
11187        /** @see InstallParams#origin */
11188        final OriginInfo origin;
11189        /** @see InstallParams#move */
11190        final MoveInfo move;
11191
11192        final IPackageInstallObserver2 observer;
11193        // Always refers to PackageManager flags only
11194        final int installFlags;
11195        final String installerPackageName;
11196        final String volumeUuid;
11197        final ManifestDigest manifestDigest;
11198        final UserHandle user;
11199        final String abiOverride;
11200        final String[] installGrantPermissions;
11201        /** If non-null, drop an async trace when the install completes */
11202        final String traceMethod;
11203        final int traceCookie;
11204
11205        // The list of instruction sets supported by this app. This is currently
11206        // only used during the rmdex() phase to clean up resources. We can get rid of this
11207        // if we move dex files under the common app path.
11208        /* nullable */ String[] instructionSets;
11209
11210        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11211                int installFlags, String installerPackageName, String volumeUuid,
11212                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11213                String abiOverride, String[] installGrantPermissions,
11214                String traceMethod, int traceCookie) {
11215            this.origin = origin;
11216            this.move = move;
11217            this.installFlags = installFlags;
11218            this.observer = observer;
11219            this.installerPackageName = installerPackageName;
11220            this.volumeUuid = volumeUuid;
11221            this.manifestDigest = manifestDigest;
11222            this.user = user;
11223            this.instructionSets = instructionSets;
11224            this.abiOverride = abiOverride;
11225            this.installGrantPermissions = installGrantPermissions;
11226            this.traceMethod = traceMethod;
11227            this.traceCookie = traceCookie;
11228        }
11229
11230        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11231        abstract int doPreInstall(int status);
11232
11233        /**
11234         * Rename package into final resting place. All paths on the given
11235         * scanned package should be updated to reflect the rename.
11236         */
11237        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11238        abstract int doPostInstall(int status, int uid);
11239
11240        /** @see PackageSettingBase#codePathString */
11241        abstract String getCodePath();
11242        /** @see PackageSettingBase#resourcePathString */
11243        abstract String getResourcePath();
11244
11245        // Need installer lock especially for dex file removal.
11246        abstract void cleanUpResourcesLI();
11247        abstract boolean doPostDeleteLI(boolean delete);
11248
11249        /**
11250         * Called before the source arguments are copied. This is used mostly
11251         * for MoveParams when it needs to read the source file to put it in the
11252         * destination.
11253         */
11254        int doPreCopy() {
11255            return PackageManager.INSTALL_SUCCEEDED;
11256        }
11257
11258        /**
11259         * Called after the source arguments are copied. This is used mostly for
11260         * MoveParams when it needs to read the source file to put it in the
11261         * destination.
11262         *
11263         * @return
11264         */
11265        int doPostCopy(int uid) {
11266            return PackageManager.INSTALL_SUCCEEDED;
11267        }
11268
11269        protected boolean isFwdLocked() {
11270            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11271        }
11272
11273        protected boolean isExternalAsec() {
11274            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11275        }
11276
11277        UserHandle getUser() {
11278            return user;
11279        }
11280    }
11281
11282    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11283        if (!allCodePaths.isEmpty()) {
11284            if (instructionSets == null) {
11285                throw new IllegalStateException("instructionSet == null");
11286            }
11287            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11288            for (String codePath : allCodePaths) {
11289                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11290                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11291                    if (retCode < 0) {
11292                        Slog.w(TAG, "Couldn't remove dex file for package: "
11293                                + " at location " + codePath + ", retcode=" + retCode);
11294                        // we don't consider this to be a failure of the core package deletion
11295                    }
11296                }
11297            }
11298        }
11299    }
11300
11301    /**
11302     * Logic to handle installation of non-ASEC applications, including copying
11303     * and renaming logic.
11304     */
11305    class FileInstallArgs extends InstallArgs {
11306        private File codeFile;
11307        private File resourceFile;
11308
11309        // Example topology:
11310        // /data/app/com.example/base.apk
11311        // /data/app/com.example/split_foo.apk
11312        // /data/app/com.example/lib/arm/libfoo.so
11313        // /data/app/com.example/lib/arm64/libfoo.so
11314        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11315
11316        /** New install */
11317        FileInstallArgs(InstallParams params) {
11318            super(params.origin, params.move, params.observer, params.installFlags,
11319                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11320                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11321                    params.grantedRuntimePermissions,
11322                    params.traceMethod, params.traceCookie);
11323            if (isFwdLocked()) {
11324                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11325            }
11326        }
11327
11328        /** Existing install */
11329        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11330            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11331                    null, null, null, 0);
11332            this.codeFile = (codePath != null) ? new File(codePath) : null;
11333            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11334        }
11335
11336        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11337            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11338            try {
11339                return doCopyApk(imcs, temp);
11340            } finally {
11341                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11342            }
11343        }
11344
11345        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11346            if (origin.staged) {
11347                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11348                codeFile = origin.file;
11349                resourceFile = origin.file;
11350                return PackageManager.INSTALL_SUCCEEDED;
11351            }
11352
11353            try {
11354                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11355                codeFile = tempDir;
11356                resourceFile = tempDir;
11357            } catch (IOException e) {
11358                Slog.w(TAG, "Failed to create copy file: " + e);
11359                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11360            }
11361
11362            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11363                @Override
11364                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11365                    if (!FileUtils.isValidExtFilename(name)) {
11366                        throw new IllegalArgumentException("Invalid filename: " + name);
11367                    }
11368                    try {
11369                        final File file = new File(codeFile, name);
11370                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11371                                O_RDWR | O_CREAT, 0644);
11372                        Os.chmod(file.getAbsolutePath(), 0644);
11373                        return new ParcelFileDescriptor(fd);
11374                    } catch (ErrnoException e) {
11375                        throw new RemoteException("Failed to open: " + e.getMessage());
11376                    }
11377                }
11378            };
11379
11380            int ret = PackageManager.INSTALL_SUCCEEDED;
11381            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11382            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11383                Slog.e(TAG, "Failed to copy package");
11384                return ret;
11385            }
11386
11387            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11388            NativeLibraryHelper.Handle handle = null;
11389            try {
11390                handle = NativeLibraryHelper.Handle.create(codeFile);
11391                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11392                        abiOverride);
11393            } catch (IOException e) {
11394                Slog.e(TAG, "Copying native libraries failed", e);
11395                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11396            } finally {
11397                IoUtils.closeQuietly(handle);
11398            }
11399
11400            return ret;
11401        }
11402
11403        int doPreInstall(int status) {
11404            if (status != PackageManager.INSTALL_SUCCEEDED) {
11405                cleanUp();
11406            }
11407            return status;
11408        }
11409
11410        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11411            if (status != PackageManager.INSTALL_SUCCEEDED) {
11412                cleanUp();
11413                return false;
11414            }
11415
11416            final File targetDir = codeFile.getParentFile();
11417            final File beforeCodeFile = codeFile;
11418            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11419
11420            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11421            try {
11422                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11423            } catch (ErrnoException e) {
11424                Slog.w(TAG, "Failed to rename", e);
11425                return false;
11426            }
11427
11428            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11429                Slog.w(TAG, "Failed to restorecon");
11430                return false;
11431            }
11432
11433            // Reflect the rename internally
11434            codeFile = afterCodeFile;
11435            resourceFile = afterCodeFile;
11436
11437            // Reflect the rename in scanned details
11438            pkg.codePath = afterCodeFile.getAbsolutePath();
11439            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11440                    pkg.baseCodePath);
11441            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11442                    pkg.splitCodePaths);
11443
11444            // Reflect the rename in app info
11445            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11446            pkg.applicationInfo.setCodePath(pkg.codePath);
11447            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11448            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11449            pkg.applicationInfo.setResourcePath(pkg.codePath);
11450            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11451            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11452
11453            return true;
11454        }
11455
11456        int doPostInstall(int status, int uid) {
11457            if (status != PackageManager.INSTALL_SUCCEEDED) {
11458                cleanUp();
11459            }
11460            return status;
11461        }
11462
11463        @Override
11464        String getCodePath() {
11465            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11466        }
11467
11468        @Override
11469        String getResourcePath() {
11470            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11471        }
11472
11473        private boolean cleanUp() {
11474            if (codeFile == null || !codeFile.exists()) {
11475                return false;
11476            }
11477
11478            if (codeFile.isDirectory()) {
11479                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11480            } else {
11481                codeFile.delete();
11482            }
11483
11484            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11485                resourceFile.delete();
11486            }
11487
11488            return true;
11489        }
11490
11491        void cleanUpResourcesLI() {
11492            // Try enumerating all code paths before deleting
11493            List<String> allCodePaths = Collections.EMPTY_LIST;
11494            if (codeFile != null && codeFile.exists()) {
11495                try {
11496                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11497                    allCodePaths = pkg.getAllCodePaths();
11498                } catch (PackageParserException e) {
11499                    // Ignored; we tried our best
11500                }
11501            }
11502
11503            cleanUp();
11504            removeDexFiles(allCodePaths, instructionSets);
11505        }
11506
11507        boolean doPostDeleteLI(boolean delete) {
11508            // XXX err, shouldn't we respect the delete flag?
11509            cleanUpResourcesLI();
11510            return true;
11511        }
11512    }
11513
11514    private boolean isAsecExternal(String cid) {
11515        final String asecPath = PackageHelper.getSdFilesystem(cid);
11516        return !asecPath.startsWith(mAsecInternalPath);
11517    }
11518
11519    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11520            PackageManagerException {
11521        if (copyRet < 0) {
11522            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11523                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11524                throw new PackageManagerException(copyRet, message);
11525            }
11526        }
11527    }
11528
11529    /**
11530     * Extract the MountService "container ID" from the full code path of an
11531     * .apk.
11532     */
11533    static String cidFromCodePath(String fullCodePath) {
11534        int eidx = fullCodePath.lastIndexOf("/");
11535        String subStr1 = fullCodePath.substring(0, eidx);
11536        int sidx = subStr1.lastIndexOf("/");
11537        return subStr1.substring(sidx+1, eidx);
11538    }
11539
11540    /**
11541     * Logic to handle installation of ASEC applications, including copying and
11542     * renaming logic.
11543     */
11544    class AsecInstallArgs extends InstallArgs {
11545        static final String RES_FILE_NAME = "pkg.apk";
11546        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11547
11548        String cid;
11549        String packagePath;
11550        String resourcePath;
11551
11552        /** New install */
11553        AsecInstallArgs(InstallParams params) {
11554            super(params.origin, params.move, params.observer, params.installFlags,
11555                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11556                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11557                    params.grantedRuntimePermissions,
11558                    params.traceMethod, params.traceCookie);
11559        }
11560
11561        /** Existing install */
11562        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11563                        boolean isExternal, boolean isForwardLocked) {
11564            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11565                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11566                    instructionSets, null, null, null, 0);
11567            // Hackily pretend we're still looking at a full code path
11568            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11569                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11570            }
11571
11572            // Extract cid from fullCodePath
11573            int eidx = fullCodePath.lastIndexOf("/");
11574            String subStr1 = fullCodePath.substring(0, eidx);
11575            int sidx = subStr1.lastIndexOf("/");
11576            cid = subStr1.substring(sidx+1, eidx);
11577            setMountPath(subStr1);
11578        }
11579
11580        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11581            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11582                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11583                    instructionSets, null, null, null, 0);
11584            this.cid = cid;
11585            setMountPath(PackageHelper.getSdDir(cid));
11586        }
11587
11588        void createCopyFile() {
11589            cid = mInstallerService.allocateExternalStageCidLegacy();
11590        }
11591
11592        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11593            if (origin.staged) {
11594                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11595                cid = origin.cid;
11596                setMountPath(PackageHelper.getSdDir(cid));
11597                return PackageManager.INSTALL_SUCCEEDED;
11598            }
11599
11600            if (temp) {
11601                createCopyFile();
11602            } else {
11603                /*
11604                 * Pre-emptively destroy the container since it's destroyed if
11605                 * copying fails due to it existing anyway.
11606                 */
11607                PackageHelper.destroySdDir(cid);
11608            }
11609
11610            final String newMountPath = imcs.copyPackageToContainer(
11611                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11612                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11613
11614            if (newMountPath != null) {
11615                setMountPath(newMountPath);
11616                return PackageManager.INSTALL_SUCCEEDED;
11617            } else {
11618                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11619            }
11620        }
11621
11622        @Override
11623        String getCodePath() {
11624            return packagePath;
11625        }
11626
11627        @Override
11628        String getResourcePath() {
11629            return resourcePath;
11630        }
11631
11632        int doPreInstall(int status) {
11633            if (status != PackageManager.INSTALL_SUCCEEDED) {
11634                // Destroy container
11635                PackageHelper.destroySdDir(cid);
11636            } else {
11637                boolean mounted = PackageHelper.isContainerMounted(cid);
11638                if (!mounted) {
11639                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11640                            Process.SYSTEM_UID);
11641                    if (newMountPath != null) {
11642                        setMountPath(newMountPath);
11643                    } else {
11644                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11645                    }
11646                }
11647            }
11648            return status;
11649        }
11650
11651        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11652            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11653            String newMountPath = null;
11654            if (PackageHelper.isContainerMounted(cid)) {
11655                // Unmount the container
11656                if (!PackageHelper.unMountSdDir(cid)) {
11657                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11658                    return false;
11659                }
11660            }
11661            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11662                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11663                        " which might be stale. Will try to clean up.");
11664                // Clean up the stale container and proceed to recreate.
11665                if (!PackageHelper.destroySdDir(newCacheId)) {
11666                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11667                    return false;
11668                }
11669                // Successfully cleaned up stale container. Try to rename again.
11670                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11671                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11672                            + " inspite of cleaning it up.");
11673                    return false;
11674                }
11675            }
11676            if (!PackageHelper.isContainerMounted(newCacheId)) {
11677                Slog.w(TAG, "Mounting container " + newCacheId);
11678                newMountPath = PackageHelper.mountSdDir(newCacheId,
11679                        getEncryptKey(), Process.SYSTEM_UID);
11680            } else {
11681                newMountPath = PackageHelper.getSdDir(newCacheId);
11682            }
11683            if (newMountPath == null) {
11684                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11685                return false;
11686            }
11687            Log.i(TAG, "Succesfully renamed " + cid +
11688                    " to " + newCacheId +
11689                    " at new path: " + newMountPath);
11690            cid = newCacheId;
11691
11692            final File beforeCodeFile = new File(packagePath);
11693            setMountPath(newMountPath);
11694            final File afterCodeFile = new File(packagePath);
11695
11696            // Reflect the rename in scanned details
11697            pkg.codePath = afterCodeFile.getAbsolutePath();
11698            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11699                    pkg.baseCodePath);
11700            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11701                    pkg.splitCodePaths);
11702
11703            // Reflect the rename in app info
11704            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11705            pkg.applicationInfo.setCodePath(pkg.codePath);
11706            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11707            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11708            pkg.applicationInfo.setResourcePath(pkg.codePath);
11709            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11710            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11711
11712            return true;
11713        }
11714
11715        private void setMountPath(String mountPath) {
11716            final File mountFile = new File(mountPath);
11717
11718            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11719            if (monolithicFile.exists()) {
11720                packagePath = monolithicFile.getAbsolutePath();
11721                if (isFwdLocked()) {
11722                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11723                } else {
11724                    resourcePath = packagePath;
11725                }
11726            } else {
11727                packagePath = mountFile.getAbsolutePath();
11728                resourcePath = packagePath;
11729            }
11730        }
11731
11732        int doPostInstall(int status, int uid) {
11733            if (status != PackageManager.INSTALL_SUCCEEDED) {
11734                cleanUp();
11735            } else {
11736                final int groupOwner;
11737                final String protectedFile;
11738                if (isFwdLocked()) {
11739                    groupOwner = UserHandle.getSharedAppGid(uid);
11740                    protectedFile = RES_FILE_NAME;
11741                } else {
11742                    groupOwner = -1;
11743                    protectedFile = null;
11744                }
11745
11746                if (uid < Process.FIRST_APPLICATION_UID
11747                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11748                    Slog.e(TAG, "Failed to finalize " + cid);
11749                    PackageHelper.destroySdDir(cid);
11750                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11751                }
11752
11753                boolean mounted = PackageHelper.isContainerMounted(cid);
11754                if (!mounted) {
11755                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11756                }
11757            }
11758            return status;
11759        }
11760
11761        private void cleanUp() {
11762            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11763
11764            // Destroy secure container
11765            PackageHelper.destroySdDir(cid);
11766        }
11767
11768        private List<String> getAllCodePaths() {
11769            final File codeFile = new File(getCodePath());
11770            if (codeFile != null && codeFile.exists()) {
11771                try {
11772                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11773                    return pkg.getAllCodePaths();
11774                } catch (PackageParserException e) {
11775                    // Ignored; we tried our best
11776                }
11777            }
11778            return Collections.EMPTY_LIST;
11779        }
11780
11781        void cleanUpResourcesLI() {
11782            // Enumerate all code paths before deleting
11783            cleanUpResourcesLI(getAllCodePaths());
11784        }
11785
11786        private void cleanUpResourcesLI(List<String> allCodePaths) {
11787            cleanUp();
11788            removeDexFiles(allCodePaths, instructionSets);
11789        }
11790
11791        String getPackageName() {
11792            return getAsecPackageName(cid);
11793        }
11794
11795        boolean doPostDeleteLI(boolean delete) {
11796            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11797            final List<String> allCodePaths = getAllCodePaths();
11798            boolean mounted = PackageHelper.isContainerMounted(cid);
11799            if (mounted) {
11800                // Unmount first
11801                if (PackageHelper.unMountSdDir(cid)) {
11802                    mounted = false;
11803                }
11804            }
11805            if (!mounted && delete) {
11806                cleanUpResourcesLI(allCodePaths);
11807            }
11808            return !mounted;
11809        }
11810
11811        @Override
11812        int doPreCopy() {
11813            if (isFwdLocked()) {
11814                if (!PackageHelper.fixSdPermissions(cid,
11815                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11816                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11817                }
11818            }
11819
11820            return PackageManager.INSTALL_SUCCEEDED;
11821        }
11822
11823        @Override
11824        int doPostCopy(int uid) {
11825            if (isFwdLocked()) {
11826                if (uid < Process.FIRST_APPLICATION_UID
11827                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11828                                RES_FILE_NAME)) {
11829                    Slog.e(TAG, "Failed to finalize " + cid);
11830                    PackageHelper.destroySdDir(cid);
11831                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11832                }
11833            }
11834
11835            return PackageManager.INSTALL_SUCCEEDED;
11836        }
11837    }
11838
11839    /**
11840     * Logic to handle movement of existing installed applications.
11841     */
11842    class MoveInstallArgs extends InstallArgs {
11843        private File codeFile;
11844        private File resourceFile;
11845
11846        /** New install */
11847        MoveInstallArgs(InstallParams params) {
11848            super(params.origin, params.move, params.observer, params.installFlags,
11849                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11850                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11851                    params.grantedRuntimePermissions,
11852                    params.traceMethod, params.traceCookie);
11853        }
11854
11855        int copyApk(IMediaContainerService imcs, boolean temp) {
11856            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11857                    + move.fromUuid + " to " + move.toUuid);
11858            synchronized (mInstaller) {
11859                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11860                        move.dataAppName, move.appId, move.seinfo) != 0) {
11861                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11862                }
11863            }
11864
11865            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11866            resourceFile = codeFile;
11867            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11868
11869            return PackageManager.INSTALL_SUCCEEDED;
11870        }
11871
11872        int doPreInstall(int status) {
11873            if (status != PackageManager.INSTALL_SUCCEEDED) {
11874                cleanUp(move.toUuid);
11875            }
11876            return status;
11877        }
11878
11879        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11880            if (status != PackageManager.INSTALL_SUCCEEDED) {
11881                cleanUp(move.toUuid);
11882                return false;
11883            }
11884
11885            // Reflect the move in app info
11886            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11887            pkg.applicationInfo.setCodePath(pkg.codePath);
11888            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11889            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11890            pkg.applicationInfo.setResourcePath(pkg.codePath);
11891            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11892            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11893
11894            return true;
11895        }
11896
11897        int doPostInstall(int status, int uid) {
11898            if (status == PackageManager.INSTALL_SUCCEEDED) {
11899                cleanUp(move.fromUuid);
11900            } else {
11901                cleanUp(move.toUuid);
11902            }
11903            return status;
11904        }
11905
11906        @Override
11907        String getCodePath() {
11908            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11909        }
11910
11911        @Override
11912        String getResourcePath() {
11913            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11914        }
11915
11916        private boolean cleanUp(String volumeUuid) {
11917            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11918                    move.dataAppName);
11919            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11920            synchronized (mInstallLock) {
11921                // Clean up both app data and code
11922                removeDataDirsLI(volumeUuid, move.packageName);
11923                if (codeFile.isDirectory()) {
11924                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11925                } else {
11926                    codeFile.delete();
11927                }
11928            }
11929            return true;
11930        }
11931
11932        void cleanUpResourcesLI() {
11933            throw new UnsupportedOperationException();
11934        }
11935
11936        boolean doPostDeleteLI(boolean delete) {
11937            throw new UnsupportedOperationException();
11938        }
11939    }
11940
11941    static String getAsecPackageName(String packageCid) {
11942        int idx = packageCid.lastIndexOf("-");
11943        if (idx == -1) {
11944            return packageCid;
11945        }
11946        return packageCid.substring(0, idx);
11947    }
11948
11949    // Utility method used to create code paths based on package name and available index.
11950    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11951        String idxStr = "";
11952        int idx = 1;
11953        // Fall back to default value of idx=1 if prefix is not
11954        // part of oldCodePath
11955        if (oldCodePath != null) {
11956            String subStr = oldCodePath;
11957            // Drop the suffix right away
11958            if (suffix != null && subStr.endsWith(suffix)) {
11959                subStr = subStr.substring(0, subStr.length() - suffix.length());
11960            }
11961            // If oldCodePath already contains prefix find out the
11962            // ending index to either increment or decrement.
11963            int sidx = subStr.lastIndexOf(prefix);
11964            if (sidx != -1) {
11965                subStr = subStr.substring(sidx + prefix.length());
11966                if (subStr != null) {
11967                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11968                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11969                    }
11970                    try {
11971                        idx = Integer.parseInt(subStr);
11972                        if (idx <= 1) {
11973                            idx++;
11974                        } else {
11975                            idx--;
11976                        }
11977                    } catch(NumberFormatException e) {
11978                    }
11979                }
11980            }
11981        }
11982        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11983        return prefix + idxStr;
11984    }
11985
11986    private File getNextCodePath(File targetDir, String packageName) {
11987        int suffix = 1;
11988        File result;
11989        do {
11990            result = new File(targetDir, packageName + "-" + suffix);
11991            suffix++;
11992        } while (result.exists());
11993        return result;
11994    }
11995
11996    // Utility method that returns the relative package path with respect
11997    // to the installation directory. Like say for /data/data/com.test-1.apk
11998    // string com.test-1 is returned.
11999    static String deriveCodePathName(String codePath) {
12000        if (codePath == null) {
12001            return null;
12002        }
12003        final File codeFile = new File(codePath);
12004        final String name = codeFile.getName();
12005        if (codeFile.isDirectory()) {
12006            return name;
12007        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12008            final int lastDot = name.lastIndexOf('.');
12009            return name.substring(0, lastDot);
12010        } else {
12011            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12012            return null;
12013        }
12014    }
12015
12016    class PackageInstalledInfo {
12017        String name;
12018        int uid;
12019        // The set of users that originally had this package installed.
12020        int[] origUsers;
12021        // The set of users that now have this package installed.
12022        int[] newUsers;
12023        PackageParser.Package pkg;
12024        int returnCode;
12025        String returnMsg;
12026        PackageRemovedInfo removedInfo;
12027
12028        public void setError(int code, String msg) {
12029            returnCode = code;
12030            returnMsg = msg;
12031            Slog.w(TAG, msg);
12032        }
12033
12034        public void setError(String msg, PackageParserException e) {
12035            returnCode = e.error;
12036            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12037            Slog.w(TAG, msg, e);
12038        }
12039
12040        public void setError(String msg, PackageManagerException e) {
12041            returnCode = e.error;
12042            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12043            Slog.w(TAG, msg, e);
12044        }
12045
12046        // In some error cases we want to convey more info back to the observer
12047        String origPackage;
12048        String origPermission;
12049    }
12050
12051    /*
12052     * Install a non-existing package.
12053     */
12054    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12055            UserHandle user, String installerPackageName, String volumeUuid,
12056            PackageInstalledInfo res) {
12057        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12058
12059        // Remember this for later, in case we need to rollback this install
12060        String pkgName = pkg.packageName;
12061
12062        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12063        // TODO: b/23350563
12064        final boolean dataDirExists = Environment
12065                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12066
12067        synchronized(mPackages) {
12068            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12069                // A package with the same name is already installed, though
12070                // it has been renamed to an older name.  The package we
12071                // are trying to install should be installed as an update to
12072                // the existing one, but that has not been requested, so bail.
12073                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12074                        + " without first uninstalling package running as "
12075                        + mSettings.mRenamedPackages.get(pkgName));
12076                return;
12077            }
12078            if (mPackages.containsKey(pkgName)) {
12079                // Don't allow installation over an existing package with the same name.
12080                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12081                        + " without first uninstalling.");
12082                return;
12083            }
12084        }
12085
12086        try {
12087            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12088                    System.currentTimeMillis(), user);
12089
12090            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12091            // delete the partially installed application. the data directory will have to be
12092            // restored if it was already existing
12093            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12094                // remove package from internal structures.  Note that we want deletePackageX to
12095                // delete the package data and cache directories that it created in
12096                // scanPackageLocked, unless those directories existed before we even tried to
12097                // install.
12098                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12099                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12100                                res.removedInfo, true);
12101            }
12102
12103        } catch (PackageManagerException e) {
12104            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12105        }
12106
12107        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12108    }
12109
12110    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12111        // Can't rotate keys during boot or if sharedUser.
12112        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12113                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12114            return false;
12115        }
12116        // app is using upgradeKeySets; make sure all are valid
12117        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12118        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12119        for (int i = 0; i < upgradeKeySets.length; i++) {
12120            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12121                Slog.wtf(TAG, "Package "
12122                         + (oldPs.name != null ? oldPs.name : "<null>")
12123                         + " contains upgrade-key-set reference to unknown key-set: "
12124                         + upgradeKeySets[i]
12125                         + " reverting to signatures check.");
12126                return false;
12127            }
12128        }
12129        return true;
12130    }
12131
12132    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12133        // Upgrade keysets are being used.  Determine if new package has a superset of the
12134        // required keys.
12135        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12136        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12137        for (int i = 0; i < upgradeKeySets.length; i++) {
12138            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12139            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12140                return true;
12141            }
12142        }
12143        return false;
12144    }
12145
12146    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12147            UserHandle user, String installerPackageName, String volumeUuid,
12148            PackageInstalledInfo res) {
12149        final PackageParser.Package oldPackage;
12150        final String pkgName = pkg.packageName;
12151        final int[] allUsers;
12152        final boolean[] perUserInstalled;
12153
12154        // First find the old package info and check signatures
12155        synchronized(mPackages) {
12156            oldPackage = mPackages.get(pkgName);
12157            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12158            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12159            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12160                if(!checkUpgradeKeySetLP(ps, pkg)) {
12161                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12162                            "New package not signed by keys specified by upgrade-keysets: "
12163                            + pkgName);
12164                    return;
12165                }
12166            } else {
12167                // default to original signature matching
12168                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12169                    != PackageManager.SIGNATURE_MATCH) {
12170                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12171                            "New package has a different signature: " + pkgName);
12172                    return;
12173                }
12174            }
12175
12176            // In case of rollback, remember per-user/profile install state
12177            allUsers = sUserManager.getUserIds();
12178            perUserInstalled = new boolean[allUsers.length];
12179            for (int i = 0; i < allUsers.length; i++) {
12180                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12181            }
12182        }
12183
12184        boolean sysPkg = (isSystemApp(oldPackage));
12185        if (sysPkg) {
12186            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12187                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12188        } else {
12189            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12190                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12191        }
12192    }
12193
12194    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12195            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12196            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12197            String volumeUuid, PackageInstalledInfo res) {
12198        String pkgName = deletedPackage.packageName;
12199        boolean deletedPkg = true;
12200        boolean updatedSettings = false;
12201
12202        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12203                + deletedPackage);
12204        long origUpdateTime;
12205        if (pkg.mExtras != null) {
12206            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12207        } else {
12208            origUpdateTime = 0;
12209        }
12210
12211        // First delete the existing package while retaining the data directory
12212        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12213                res.removedInfo, true)) {
12214            // If the existing package wasn't successfully deleted
12215            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12216            deletedPkg = false;
12217        } else {
12218            // Successfully deleted the old package; proceed with replace.
12219
12220            // If deleted package lived in a container, give users a chance to
12221            // relinquish resources before killing.
12222            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12223                if (DEBUG_INSTALL) {
12224                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12225                }
12226                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12227                final ArrayList<String> pkgList = new ArrayList<String>(1);
12228                pkgList.add(deletedPackage.applicationInfo.packageName);
12229                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12230            }
12231
12232            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12233            try {
12234                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12235                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12236                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12237                        perUserInstalled, res, user);
12238                updatedSettings = true;
12239            } catch (PackageManagerException e) {
12240                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12241            }
12242        }
12243
12244        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12245            // remove package from internal structures.  Note that we want deletePackageX to
12246            // delete the package data and cache directories that it created in
12247            // scanPackageLocked, unless those directories existed before we even tried to
12248            // install.
12249            if(updatedSettings) {
12250                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12251                deletePackageLI(
12252                        pkgName, null, true, allUsers, perUserInstalled,
12253                        PackageManager.DELETE_KEEP_DATA,
12254                                res.removedInfo, true);
12255            }
12256            // Since we failed to install the new package we need to restore the old
12257            // package that we deleted.
12258            if (deletedPkg) {
12259                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12260                File restoreFile = new File(deletedPackage.codePath);
12261                // Parse old package
12262                boolean oldExternal = isExternal(deletedPackage);
12263                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12264                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12265                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12266                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12267                try {
12268                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12269                            null);
12270                } catch (PackageManagerException e) {
12271                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12272                            + e.getMessage());
12273                    return;
12274                }
12275                // Restore of old package succeeded. Update permissions.
12276                // writer
12277                synchronized (mPackages) {
12278                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12279                            UPDATE_PERMISSIONS_ALL);
12280                    // can downgrade to reader
12281                    mSettings.writeLPr();
12282                }
12283                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12284            }
12285        }
12286    }
12287
12288    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12289            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12290            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12291            String volumeUuid, PackageInstalledInfo res) {
12292        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12293                + ", old=" + deletedPackage);
12294        boolean disabledSystem = false;
12295        boolean updatedSettings = false;
12296        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12297        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12298                != 0) {
12299            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12300        }
12301        String packageName = deletedPackage.packageName;
12302        if (packageName == null) {
12303            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12304                    "Attempt to delete null packageName.");
12305            return;
12306        }
12307        PackageParser.Package oldPkg;
12308        PackageSetting oldPkgSetting;
12309        // reader
12310        synchronized (mPackages) {
12311            oldPkg = mPackages.get(packageName);
12312            oldPkgSetting = mSettings.mPackages.get(packageName);
12313            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12314                    (oldPkgSetting == null)) {
12315                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12316                        "Couldn't find package:" + packageName + " information");
12317                return;
12318            }
12319        }
12320
12321        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12322
12323        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12324        res.removedInfo.removedPackage = packageName;
12325        // Remove existing system package
12326        removePackageLI(oldPkgSetting, true);
12327        // writer
12328        synchronized (mPackages) {
12329            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12330            if (!disabledSystem && deletedPackage != null) {
12331                // We didn't need to disable the .apk as a current system package,
12332                // which means we are replacing another update that is already
12333                // installed.  We need to make sure to delete the older one's .apk.
12334                res.removedInfo.args = createInstallArgsForExisting(0,
12335                        deletedPackage.applicationInfo.getCodePath(),
12336                        deletedPackage.applicationInfo.getResourcePath(),
12337                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12338            } else {
12339                res.removedInfo.args = null;
12340            }
12341        }
12342
12343        // Successfully disabled the old package. Now proceed with re-installation
12344        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12345
12346        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12347        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12348
12349        PackageParser.Package newPackage = null;
12350        try {
12351            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12352            if (newPackage.mExtras != null) {
12353                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12354                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12355                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12356
12357                // is the update attempting to change shared user? that isn't going to work...
12358                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12359                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12360                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12361                            + " to " + newPkgSetting.sharedUser);
12362                    updatedSettings = true;
12363                }
12364            }
12365
12366            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12367                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12368                        perUserInstalled, res, user);
12369                updatedSettings = true;
12370            }
12371
12372        } catch (PackageManagerException e) {
12373            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12374        }
12375
12376        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12377            // Re installation failed. Restore old information
12378            // Remove new pkg information
12379            if (newPackage != null) {
12380                removeInstalledPackageLI(newPackage, true);
12381            }
12382            // Add back the old system package
12383            try {
12384                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12385            } catch (PackageManagerException e) {
12386                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12387            }
12388            // Restore the old system information in Settings
12389            synchronized (mPackages) {
12390                if (disabledSystem) {
12391                    mSettings.enableSystemPackageLPw(packageName);
12392                }
12393                if (updatedSettings) {
12394                    mSettings.setInstallerPackageName(packageName,
12395                            oldPkgSetting.installerPackageName);
12396                }
12397                mSettings.writeLPr();
12398            }
12399        }
12400    }
12401
12402    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12403        // Collect all used permissions in the UID
12404        ArraySet<String> usedPermissions = new ArraySet<>();
12405        final int packageCount = su.packages.size();
12406        for (int i = 0; i < packageCount; i++) {
12407            PackageSetting ps = su.packages.valueAt(i);
12408            if (ps.pkg == null) {
12409                continue;
12410            }
12411            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12412            for (int j = 0; j < requestedPermCount; j++) {
12413                String permission = ps.pkg.requestedPermissions.get(j);
12414                BasePermission bp = mSettings.mPermissions.get(permission);
12415                if (bp != null) {
12416                    usedPermissions.add(permission);
12417                }
12418            }
12419        }
12420
12421        PermissionsState permissionsState = su.getPermissionsState();
12422        // Prune install permissions
12423        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12424        final int installPermCount = installPermStates.size();
12425        for (int i = installPermCount - 1; i >= 0;  i--) {
12426            PermissionState permissionState = installPermStates.get(i);
12427            if (!usedPermissions.contains(permissionState.getName())) {
12428                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12429                if (bp != null) {
12430                    permissionsState.revokeInstallPermission(bp);
12431                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12432                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12433                }
12434            }
12435        }
12436
12437        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12438
12439        // Prune runtime permissions
12440        for (int userId : allUserIds) {
12441            List<PermissionState> runtimePermStates = permissionsState
12442                    .getRuntimePermissionStates(userId);
12443            final int runtimePermCount = runtimePermStates.size();
12444            for (int i = runtimePermCount - 1; i >= 0; i--) {
12445                PermissionState permissionState = runtimePermStates.get(i);
12446                if (!usedPermissions.contains(permissionState.getName())) {
12447                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12448                    if (bp != null) {
12449                        permissionsState.revokeRuntimePermission(bp, userId);
12450                        permissionsState.updatePermissionFlags(bp, userId,
12451                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12452                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12453                                runtimePermissionChangedUserIds, userId);
12454                    }
12455                }
12456            }
12457        }
12458
12459        return runtimePermissionChangedUserIds;
12460    }
12461
12462    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12463            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12464            UserHandle user) {
12465        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12466
12467        String pkgName = newPackage.packageName;
12468        synchronized (mPackages) {
12469            //write settings. the installStatus will be incomplete at this stage.
12470            //note that the new package setting would have already been
12471            //added to mPackages. It hasn't been persisted yet.
12472            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12474            mSettings.writeLPr();
12475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12476        }
12477
12478        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12479        synchronized (mPackages) {
12480            updatePermissionsLPw(newPackage.packageName, newPackage,
12481                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12482                            ? UPDATE_PERMISSIONS_ALL : 0));
12483            // For system-bundled packages, we assume that installing an upgraded version
12484            // of the package implies that the user actually wants to run that new code,
12485            // so we enable the package.
12486            PackageSetting ps = mSettings.mPackages.get(pkgName);
12487            if (ps != null) {
12488                if (isSystemApp(newPackage)) {
12489                    // NB: implicit assumption that system package upgrades apply to all users
12490                    if (DEBUG_INSTALL) {
12491                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12492                    }
12493                    if (res.origUsers != null) {
12494                        for (int userHandle : res.origUsers) {
12495                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12496                                    userHandle, installerPackageName);
12497                        }
12498                    }
12499                    // Also convey the prior install/uninstall state
12500                    if (allUsers != null && perUserInstalled != null) {
12501                        for (int i = 0; i < allUsers.length; i++) {
12502                            if (DEBUG_INSTALL) {
12503                                Slog.d(TAG, "    user " + allUsers[i]
12504                                        + " => " + perUserInstalled[i]);
12505                            }
12506                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12507                        }
12508                        // these install state changes will be persisted in the
12509                        // upcoming call to mSettings.writeLPr().
12510                    }
12511                }
12512                // It's implied that when a user requests installation, they want the app to be
12513                // installed and enabled.
12514                int userId = user.getIdentifier();
12515                if (userId != UserHandle.USER_ALL) {
12516                    ps.setInstalled(true, userId);
12517                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12518                }
12519            }
12520            res.name = pkgName;
12521            res.uid = newPackage.applicationInfo.uid;
12522            res.pkg = newPackage;
12523            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12524            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12525            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12526            //to update install status
12527            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12528            mSettings.writeLPr();
12529            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12530        }
12531
12532        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12533    }
12534
12535    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12536        try {
12537            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12538            installPackageLI(args, res);
12539        } finally {
12540            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12541        }
12542    }
12543
12544    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12545        final int installFlags = args.installFlags;
12546        final String installerPackageName = args.installerPackageName;
12547        final String volumeUuid = args.volumeUuid;
12548        final File tmpPackageFile = new File(args.getCodePath());
12549        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12550        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12551                || (args.volumeUuid != null));
12552        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12553        boolean replace = false;
12554        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12555        if (args.move != null) {
12556            // moving a complete application; perfom an initial scan on the new install location
12557            scanFlags |= SCAN_INITIAL;
12558        }
12559        // Result object to be returned
12560        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12561
12562        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12563
12564        // Retrieve PackageSettings and parse package
12565        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12566                | PackageParser.PARSE_ENFORCE_CODE
12567                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12568                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12569                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12570        PackageParser pp = new PackageParser();
12571        pp.setSeparateProcesses(mSeparateProcesses);
12572        pp.setDisplayMetrics(mMetrics);
12573
12574        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12575        final PackageParser.Package pkg;
12576        try {
12577            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12578        } catch (PackageParserException e) {
12579            res.setError("Failed parse during installPackageLI", e);
12580            return;
12581        } finally {
12582            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12583        }
12584
12585        // Mark that we have an install time CPU ABI override.
12586        pkg.cpuAbiOverride = args.abiOverride;
12587
12588        String pkgName = res.name = pkg.packageName;
12589        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12590            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12591                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12592                return;
12593            }
12594        }
12595
12596        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12597        try {
12598            pp.collectCertificates(pkg, parseFlags);
12599        } catch (PackageParserException e) {
12600            res.setError("Failed collect during installPackageLI", e);
12601            return;
12602        } finally {
12603            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12604        }
12605
12606        /* If the installer passed in a manifest digest, compare it now. */
12607        if (args.manifestDigest != null) {
12608            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12609            try {
12610                pp.collectManifestDigest(pkg);
12611            } catch (PackageParserException e) {
12612                res.setError("Failed collect during installPackageLI", e);
12613                return;
12614            } finally {
12615                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12616            }
12617
12618            if (DEBUG_INSTALL) {
12619                final String parsedManifest = pkg.manifestDigest == null ? "null"
12620                        : pkg.manifestDigest.toString();
12621                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12622                        + parsedManifest);
12623            }
12624
12625            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12626                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12627                return;
12628            }
12629        } else if (DEBUG_INSTALL) {
12630            final String parsedManifest = pkg.manifestDigest == null
12631                    ? "null" : pkg.manifestDigest.toString();
12632            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12633        }
12634
12635        // Get rid of all references to package scan path via parser.
12636        pp = null;
12637        String oldCodePath = null;
12638        boolean systemApp = false;
12639        synchronized (mPackages) {
12640            // Check if installing already existing package
12641            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12642                String oldName = mSettings.mRenamedPackages.get(pkgName);
12643                if (pkg.mOriginalPackages != null
12644                        && pkg.mOriginalPackages.contains(oldName)
12645                        && mPackages.containsKey(oldName)) {
12646                    // This package is derived from an original package,
12647                    // and this device has been updating from that original
12648                    // name.  We must continue using the original name, so
12649                    // rename the new package here.
12650                    pkg.setPackageName(oldName);
12651                    pkgName = pkg.packageName;
12652                    replace = true;
12653                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12654                            + oldName + " pkgName=" + pkgName);
12655                } else if (mPackages.containsKey(pkgName)) {
12656                    // This package, under its official name, already exists
12657                    // on the device; we should replace it.
12658                    replace = true;
12659                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12660                }
12661
12662                // Prevent apps opting out from runtime permissions
12663                if (replace) {
12664                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12665                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12666                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12667                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12668                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12669                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12670                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12671                                        + " doesn't support runtime permissions but the old"
12672                                        + " target SDK " + oldTargetSdk + " does.");
12673                        return;
12674                    }
12675                }
12676            }
12677
12678            PackageSetting ps = mSettings.mPackages.get(pkgName);
12679            if (ps != null) {
12680                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12681
12682                // Quick sanity check that we're signed correctly if updating;
12683                // we'll check this again later when scanning, but we want to
12684                // bail early here before tripping over redefined permissions.
12685                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12686                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12687                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12688                                + pkg.packageName + " upgrade keys do not match the "
12689                                + "previously installed version");
12690                        return;
12691                    }
12692                } else {
12693                    try {
12694                        verifySignaturesLP(ps, pkg);
12695                    } catch (PackageManagerException e) {
12696                        res.setError(e.error, e.getMessage());
12697                        return;
12698                    }
12699                }
12700
12701                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12702                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12703                    systemApp = (ps.pkg.applicationInfo.flags &
12704                            ApplicationInfo.FLAG_SYSTEM) != 0;
12705                }
12706                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12707            }
12708
12709            // Check whether the newly-scanned package wants to define an already-defined perm
12710            int N = pkg.permissions.size();
12711            for (int i = N-1; i >= 0; i--) {
12712                PackageParser.Permission perm = pkg.permissions.get(i);
12713                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12714                if (bp != null) {
12715                    // If the defining package is signed with our cert, it's okay.  This
12716                    // also includes the "updating the same package" case, of course.
12717                    // "updating same package" could also involve key-rotation.
12718                    final boolean sigsOk;
12719                    if (bp.sourcePackage.equals(pkg.packageName)
12720                            && (bp.packageSetting instanceof PackageSetting)
12721                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12722                                    scanFlags))) {
12723                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12724                    } else {
12725                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12726                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12727                    }
12728                    if (!sigsOk) {
12729                        // If the owning package is the system itself, we log but allow
12730                        // install to proceed; we fail the install on all other permission
12731                        // redefinitions.
12732                        if (!bp.sourcePackage.equals("android")) {
12733                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12734                                    + pkg.packageName + " attempting to redeclare permission "
12735                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12736                            res.origPermission = perm.info.name;
12737                            res.origPackage = bp.sourcePackage;
12738                            return;
12739                        } else {
12740                            Slog.w(TAG, "Package " + pkg.packageName
12741                                    + " attempting to redeclare system permission "
12742                                    + perm.info.name + "; ignoring new declaration");
12743                            pkg.permissions.remove(i);
12744                        }
12745                    }
12746                }
12747            }
12748
12749        }
12750
12751        if (systemApp && onExternal) {
12752            // Disable updates to system apps on sdcard
12753            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12754                    "Cannot install updates to system apps on sdcard");
12755            return;
12756        }
12757
12758        if (args.move != null) {
12759            // We did an in-place move, so dex is ready to roll
12760            scanFlags |= SCAN_NO_DEX;
12761            scanFlags |= SCAN_MOVE;
12762
12763            synchronized (mPackages) {
12764                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12765                if (ps == null) {
12766                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12767                            "Missing settings for moved package " + pkgName);
12768                }
12769
12770                // We moved the entire application as-is, so bring over the
12771                // previously derived ABI information.
12772                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12773                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12774            }
12775
12776        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12777            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12778            scanFlags |= SCAN_NO_DEX;
12779
12780            try {
12781                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12782                        true /* extract libs */);
12783            } catch (PackageManagerException pme) {
12784                Slog.e(TAG, "Error deriving application ABI", pme);
12785                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12786                return;
12787            }
12788        }
12789
12790        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12791            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12792            return;
12793        }
12794
12795        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12796
12797        if (replace) {
12798            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12799                    installerPackageName, volumeUuid, res);
12800        } else {
12801            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12802                    args.user, installerPackageName, volumeUuid, res);
12803        }
12804        synchronized (mPackages) {
12805            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12806            if (ps != null) {
12807                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12808            }
12809        }
12810    }
12811
12812    private void startIntentFilterVerifications(int userId, boolean replacing,
12813            PackageParser.Package pkg) {
12814        if (mIntentFilterVerifierComponent == null) {
12815            Slog.w(TAG, "No IntentFilter verification will not be done as "
12816                    + "there is no IntentFilterVerifier available!");
12817            return;
12818        }
12819
12820        final int verifierUid = getPackageUid(
12821                mIntentFilterVerifierComponent.getPackageName(),
12822                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12823
12824        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12825        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12826        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12827        mHandler.sendMessage(msg);
12828    }
12829
12830    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12831            PackageParser.Package pkg) {
12832        int size = pkg.activities.size();
12833        if (size == 0) {
12834            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12835                    "No activity, so no need to verify any IntentFilter!");
12836            return;
12837        }
12838
12839        final boolean hasDomainURLs = hasDomainURLs(pkg);
12840        if (!hasDomainURLs) {
12841            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12842                    "No domain URLs, so no need to verify any IntentFilter!");
12843            return;
12844        }
12845
12846        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12847                + " if any IntentFilter from the " + size
12848                + " Activities needs verification ...");
12849
12850        int count = 0;
12851        final String packageName = pkg.packageName;
12852
12853        synchronized (mPackages) {
12854            // If this is a new install and we see that we've already run verification for this
12855            // package, we have nothing to do: it means the state was restored from backup.
12856            if (!replacing) {
12857                IntentFilterVerificationInfo ivi =
12858                        mSettings.getIntentFilterVerificationLPr(packageName);
12859                if (ivi != null) {
12860                    if (DEBUG_DOMAIN_VERIFICATION) {
12861                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12862                                + ivi.getStatusString());
12863                    }
12864                    return;
12865                }
12866            }
12867
12868            // If any filters need to be verified, then all need to be.
12869            boolean needToVerify = false;
12870            for (PackageParser.Activity a : pkg.activities) {
12871                for (ActivityIntentInfo filter : a.intents) {
12872                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12873                        if (DEBUG_DOMAIN_VERIFICATION) {
12874                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12875                        }
12876                        needToVerify = true;
12877                        break;
12878                    }
12879                }
12880            }
12881
12882            if (needToVerify) {
12883                final int verificationId = mIntentFilterVerificationToken++;
12884                for (PackageParser.Activity a : pkg.activities) {
12885                    for (ActivityIntentInfo filter : a.intents) {
12886                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12887                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12888                                    "Verification needed for IntentFilter:" + filter.toString());
12889                            mIntentFilterVerifier.addOneIntentFilterVerification(
12890                                    verifierUid, userId, verificationId, filter, packageName);
12891                            count++;
12892                        }
12893                    }
12894                }
12895            }
12896        }
12897
12898        if (count > 0) {
12899            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12900                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12901                    +  " for userId:" + userId);
12902            mIntentFilterVerifier.startVerifications(userId);
12903        } else {
12904            if (DEBUG_DOMAIN_VERIFICATION) {
12905                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12906            }
12907        }
12908    }
12909
12910    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12911        final ComponentName cn  = filter.activity.getComponentName();
12912        final String packageName = cn.getPackageName();
12913
12914        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12915                packageName);
12916        if (ivi == null) {
12917            return true;
12918        }
12919        int status = ivi.getStatus();
12920        switch (status) {
12921            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12922            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12923                return true;
12924
12925            default:
12926                // Nothing to do
12927                return false;
12928        }
12929    }
12930
12931    private static boolean isMultiArch(PackageSetting ps) {
12932        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12933    }
12934
12935    private static boolean isMultiArch(ApplicationInfo info) {
12936        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12937    }
12938
12939    private static boolean isExternal(PackageParser.Package pkg) {
12940        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12941    }
12942
12943    private static boolean isExternal(PackageSetting ps) {
12944        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12945    }
12946
12947    private static boolean isExternal(ApplicationInfo info) {
12948        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12949    }
12950
12951    private static boolean isSystemApp(PackageParser.Package pkg) {
12952        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12953    }
12954
12955    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12956        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12957    }
12958
12959    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12960        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12961    }
12962
12963    private static boolean isSystemApp(PackageSetting ps) {
12964        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12965    }
12966
12967    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12968        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12969    }
12970
12971    private int packageFlagsToInstallFlags(PackageSetting ps) {
12972        int installFlags = 0;
12973        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12974            // This existing package was an external ASEC install when we have
12975            // the external flag without a UUID
12976            installFlags |= PackageManager.INSTALL_EXTERNAL;
12977        }
12978        if (ps.isForwardLocked()) {
12979            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12980        }
12981        return installFlags;
12982    }
12983
12984    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12985        if (isExternal(pkg)) {
12986            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12987                return StorageManager.UUID_PRIMARY_PHYSICAL;
12988            } else {
12989                return pkg.volumeUuid;
12990            }
12991        } else {
12992            return StorageManager.UUID_PRIVATE_INTERNAL;
12993        }
12994    }
12995
12996    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12997        if (isExternal(pkg)) {
12998            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12999                return mSettings.getExternalVersion();
13000            } else {
13001                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13002            }
13003        } else {
13004            return mSettings.getInternalVersion();
13005        }
13006    }
13007
13008    private void deleteTempPackageFiles() {
13009        final FilenameFilter filter = new FilenameFilter() {
13010            public boolean accept(File dir, String name) {
13011                return name.startsWith("vmdl") && name.endsWith(".tmp");
13012            }
13013        };
13014        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13015            file.delete();
13016        }
13017    }
13018
13019    @Override
13020    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13021            int flags) {
13022        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13023                flags);
13024    }
13025
13026    @Override
13027    public void deletePackage(final String packageName,
13028            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13029        mContext.enforceCallingOrSelfPermission(
13030                android.Manifest.permission.DELETE_PACKAGES, null);
13031        Preconditions.checkNotNull(packageName);
13032        Preconditions.checkNotNull(observer);
13033        final int uid = Binder.getCallingUid();
13034        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13035        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13036        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13037            mContext.enforceCallingOrSelfPermission(
13038                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13039                    "deletePackage for user " + userId);
13040        }
13041
13042        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13043            try {
13044                observer.onPackageDeleted(packageName,
13045                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13046            } catch (RemoteException re) {
13047            }
13048            return;
13049        }
13050
13051        for (int currentUserId : users) {
13052            if (getBlockUninstallForUser(packageName, currentUserId)) {
13053                try {
13054                    observer.onPackageDeleted(packageName,
13055                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13056                } catch (RemoteException re) {
13057                }
13058                return;
13059            }
13060        }
13061
13062        if (DEBUG_REMOVE) {
13063            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13064        }
13065        // Queue up an async operation since the package deletion may take a little while.
13066        mHandler.post(new Runnable() {
13067            public void run() {
13068                mHandler.removeCallbacks(this);
13069                final int returnCode = deletePackageX(packageName, userId, flags);
13070                try {
13071                    observer.onPackageDeleted(packageName, returnCode, null);
13072                } catch (RemoteException e) {
13073                    Log.i(TAG, "Observer no longer exists.");
13074                } //end catch
13075            } //end run
13076        });
13077    }
13078
13079    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13080        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13081                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13082        try {
13083            if (dpm != null) {
13084                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13085                        /* callingUserOnly =*/ false);
13086                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13087                        : deviceOwnerComponentName.getPackageName();
13088                // Does the package contains the device owner?
13089                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13090                // this check is probably not needed, since DO should be registered as a device
13091                // admin on some user too. (Original bug for this: b/17657954)
13092                if (packageName.equals(deviceOwnerPackageName)) {
13093                    return true;
13094                }
13095                // Does it contain a device admin for any user?
13096                int[] users;
13097                if (userId == UserHandle.USER_ALL) {
13098                    users = sUserManager.getUserIds();
13099                } else {
13100                    users = new int[]{userId};
13101                }
13102                for (int i = 0; i < users.length; ++i) {
13103                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13104                        return true;
13105                    }
13106                }
13107            }
13108        } catch (RemoteException e) {
13109        }
13110        return false;
13111    }
13112
13113    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13114        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13115    }
13116
13117    /**
13118     *  This method is an internal method that could be get invoked either
13119     *  to delete an installed package or to clean up a failed installation.
13120     *  After deleting an installed package, a broadcast is sent to notify any
13121     *  listeners that the package has been installed. For cleaning up a failed
13122     *  installation, the broadcast is not necessary since the package's
13123     *  installation wouldn't have sent the initial broadcast either
13124     *  The key steps in deleting a package are
13125     *  deleting the package information in internal structures like mPackages,
13126     *  deleting the packages base directories through installd
13127     *  updating mSettings to reflect current status
13128     *  persisting settings for later use
13129     *  sending a broadcast if necessary
13130     */
13131    private int deletePackageX(String packageName, int userId, int flags) {
13132        final PackageRemovedInfo info = new PackageRemovedInfo();
13133        final boolean res;
13134
13135        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13136                ? UserHandle.ALL : new UserHandle(userId);
13137
13138        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13139            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13140            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13141        }
13142
13143        boolean removedForAllUsers = false;
13144        boolean systemUpdate = false;
13145
13146        // for the uninstall-updates case and restricted profiles, remember the per-
13147        // userhandle installed state
13148        int[] allUsers;
13149        boolean[] perUserInstalled;
13150        synchronized (mPackages) {
13151            PackageSetting ps = mSettings.mPackages.get(packageName);
13152            allUsers = sUserManager.getUserIds();
13153            perUserInstalled = new boolean[allUsers.length];
13154            for (int i = 0; i < allUsers.length; i++) {
13155                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13156            }
13157        }
13158
13159        synchronized (mInstallLock) {
13160            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13161            res = deletePackageLI(packageName, removeForUser,
13162                    true, allUsers, perUserInstalled,
13163                    flags | REMOVE_CHATTY, info, true);
13164            systemUpdate = info.isRemovedPackageSystemUpdate;
13165            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13166                removedForAllUsers = true;
13167            }
13168            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13169                    + " removedForAllUsers=" + removedForAllUsers);
13170        }
13171
13172        if (res) {
13173            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13174
13175            // If the removed package was a system update, the old system package
13176            // was re-enabled; we need to broadcast this information
13177            if (systemUpdate) {
13178                Bundle extras = new Bundle(1);
13179                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13180                        ? info.removedAppId : info.uid);
13181                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13182
13183                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13184                        extras, 0, null, null, null);
13185                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13186                        extras, 0, null, null, null);
13187                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13188                        null, 0, packageName, null, null);
13189            }
13190        }
13191        // Force a gc here.
13192        Runtime.getRuntime().gc();
13193        // Delete the resources here after sending the broadcast to let
13194        // other processes clean up before deleting resources.
13195        if (info.args != null) {
13196            synchronized (mInstallLock) {
13197                info.args.doPostDeleteLI(true);
13198            }
13199        }
13200
13201        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13202    }
13203
13204    class PackageRemovedInfo {
13205        String removedPackage;
13206        int uid = -1;
13207        int removedAppId = -1;
13208        int[] removedUsers = null;
13209        boolean isRemovedPackageSystemUpdate = false;
13210        // Clean up resources deleted packages.
13211        InstallArgs args = null;
13212
13213        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13214            Bundle extras = new Bundle(1);
13215            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13216            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13217            if (replacing) {
13218                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13219            }
13220            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13221            if (removedPackage != null) {
13222                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13223                        extras, 0, null, null, removedUsers);
13224                if (fullRemove && !replacing) {
13225                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13226                            extras, 0, null, null, removedUsers);
13227                }
13228            }
13229            if (removedAppId >= 0) {
13230                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13231                        removedUsers);
13232            }
13233        }
13234    }
13235
13236    /*
13237     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13238     * flag is not set, the data directory is removed as well.
13239     * make sure this flag is set for partially installed apps. If not its meaningless to
13240     * delete a partially installed application.
13241     */
13242    private void removePackageDataLI(PackageSetting ps,
13243            int[] allUserHandles, boolean[] perUserInstalled,
13244            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13245        String packageName = ps.name;
13246        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13247        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13248        // Retrieve object to delete permissions for shared user later on
13249        final PackageSetting deletedPs;
13250        // reader
13251        synchronized (mPackages) {
13252            deletedPs = mSettings.mPackages.get(packageName);
13253            if (outInfo != null) {
13254                outInfo.removedPackage = packageName;
13255                outInfo.removedUsers = deletedPs != null
13256                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13257                        : null;
13258            }
13259        }
13260        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13261            removeDataDirsLI(ps.volumeUuid, packageName);
13262            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13263        }
13264        // writer
13265        synchronized (mPackages) {
13266            if (deletedPs != null) {
13267                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13268                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13269                    clearDefaultBrowserIfNeeded(packageName);
13270                    if (outInfo != null) {
13271                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13272                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13273                    }
13274                    updatePermissionsLPw(deletedPs.name, null, 0);
13275                    if (deletedPs.sharedUser != null) {
13276                        // Remove permissions associated with package. Since runtime
13277                        // permissions are per user we have to kill the removed package
13278                        // or packages running under the shared user of the removed
13279                        // package if revoking the permissions requested only by the removed
13280                        // package is successful and this causes a change in gids.
13281                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13282                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13283                                    userId);
13284                            if (userIdToKill == UserHandle.USER_ALL
13285                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13286                                // If gids changed for this user, kill all affected packages.
13287                                mHandler.post(new Runnable() {
13288                                    @Override
13289                                    public void run() {
13290                                        // This has to happen with no lock held.
13291                                        killApplication(deletedPs.name, deletedPs.appId,
13292                                                KILL_APP_REASON_GIDS_CHANGED);
13293                                    }
13294                                });
13295                                break;
13296                            }
13297                        }
13298                    }
13299                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13300                }
13301                // make sure to preserve per-user disabled state if this removal was just
13302                // a downgrade of a system app to the factory package
13303                if (allUserHandles != null && perUserInstalled != null) {
13304                    if (DEBUG_REMOVE) {
13305                        Slog.d(TAG, "Propagating install state across downgrade");
13306                    }
13307                    for (int i = 0; i < allUserHandles.length; i++) {
13308                        if (DEBUG_REMOVE) {
13309                            Slog.d(TAG, "    user " + allUserHandles[i]
13310                                    + " => " + perUserInstalled[i]);
13311                        }
13312                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13313                    }
13314                }
13315            }
13316            // can downgrade to reader
13317            if (writeSettings) {
13318                // Save settings now
13319                mSettings.writeLPr();
13320            }
13321        }
13322        if (outInfo != null) {
13323            // A user ID was deleted here. Go through all users and remove it
13324            // from KeyStore.
13325            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13326        }
13327    }
13328
13329    static boolean locationIsPrivileged(File path) {
13330        try {
13331            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13332                    .getCanonicalPath();
13333            return path.getCanonicalPath().startsWith(privilegedAppDir);
13334        } catch (IOException e) {
13335            Slog.e(TAG, "Unable to access code path " + path);
13336        }
13337        return false;
13338    }
13339
13340    /*
13341     * Tries to delete system package.
13342     */
13343    private boolean deleteSystemPackageLI(PackageSetting newPs,
13344            int[] allUserHandles, boolean[] perUserInstalled,
13345            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13346        final boolean applyUserRestrictions
13347                = (allUserHandles != null) && (perUserInstalled != null);
13348        PackageSetting disabledPs = null;
13349        // Confirm if the system package has been updated
13350        // An updated system app can be deleted. This will also have to restore
13351        // the system pkg from system partition
13352        // reader
13353        synchronized (mPackages) {
13354            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13355        }
13356        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13357                + " disabledPs=" + disabledPs);
13358        if (disabledPs == null) {
13359            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13360            return false;
13361        } else if (DEBUG_REMOVE) {
13362            Slog.d(TAG, "Deleting system pkg from data partition");
13363        }
13364        if (DEBUG_REMOVE) {
13365            if (applyUserRestrictions) {
13366                Slog.d(TAG, "Remembering install states:");
13367                for (int i = 0; i < allUserHandles.length; i++) {
13368                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13369                }
13370            }
13371        }
13372        // Delete the updated package
13373        outInfo.isRemovedPackageSystemUpdate = true;
13374        if (disabledPs.versionCode < newPs.versionCode) {
13375            // Delete data for downgrades
13376            flags &= ~PackageManager.DELETE_KEEP_DATA;
13377        } else {
13378            // Preserve data by setting flag
13379            flags |= PackageManager.DELETE_KEEP_DATA;
13380        }
13381        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13382                allUserHandles, perUserInstalled, outInfo, writeSettings);
13383        if (!ret) {
13384            return false;
13385        }
13386        // writer
13387        synchronized (mPackages) {
13388            // Reinstate the old system package
13389            mSettings.enableSystemPackageLPw(newPs.name);
13390            // Remove any native libraries from the upgraded package.
13391            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13392        }
13393        // Install the system package
13394        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13395        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13396        if (locationIsPrivileged(disabledPs.codePath)) {
13397            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13398        }
13399
13400        final PackageParser.Package newPkg;
13401        try {
13402            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13403        } catch (PackageManagerException e) {
13404            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13405            return false;
13406        }
13407
13408        // writer
13409        synchronized (mPackages) {
13410            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13411
13412            // Propagate the permissions state as we do not want to drop on the floor
13413            // runtime permissions. The update permissions method below will take
13414            // care of removing obsolete permissions and grant install permissions.
13415            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13416            updatePermissionsLPw(newPkg.packageName, newPkg,
13417                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13418
13419            if (applyUserRestrictions) {
13420                if (DEBUG_REMOVE) {
13421                    Slog.d(TAG, "Propagating install state across reinstall");
13422                }
13423                for (int i = 0; i < allUserHandles.length; i++) {
13424                    if (DEBUG_REMOVE) {
13425                        Slog.d(TAG, "    user " + allUserHandles[i]
13426                                + " => " + perUserInstalled[i]);
13427                    }
13428                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13429
13430                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13431                }
13432                // Regardless of writeSettings we need to ensure that this restriction
13433                // state propagation is persisted
13434                mSettings.writeAllUsersPackageRestrictionsLPr();
13435            }
13436            // can downgrade to reader here
13437            if (writeSettings) {
13438                mSettings.writeLPr();
13439            }
13440        }
13441        return true;
13442    }
13443
13444    private boolean deleteInstalledPackageLI(PackageSetting ps,
13445            boolean deleteCodeAndResources, int flags,
13446            int[] allUserHandles, boolean[] perUserInstalled,
13447            PackageRemovedInfo outInfo, boolean writeSettings) {
13448        if (outInfo != null) {
13449            outInfo.uid = ps.appId;
13450        }
13451
13452        // Delete package data from internal structures and also remove data if flag is set
13453        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13454
13455        // Delete application code and resources
13456        if (deleteCodeAndResources && (outInfo != null)) {
13457            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13458                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13459            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13460        }
13461        return true;
13462    }
13463
13464    @Override
13465    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13466            int userId) {
13467        mContext.enforceCallingOrSelfPermission(
13468                android.Manifest.permission.DELETE_PACKAGES, null);
13469        synchronized (mPackages) {
13470            PackageSetting ps = mSettings.mPackages.get(packageName);
13471            if (ps == null) {
13472                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13473                return false;
13474            }
13475            if (!ps.getInstalled(userId)) {
13476                // Can't block uninstall for an app that is not installed or enabled.
13477                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13478                return false;
13479            }
13480            ps.setBlockUninstall(blockUninstall, userId);
13481            mSettings.writePackageRestrictionsLPr(userId);
13482        }
13483        return true;
13484    }
13485
13486    @Override
13487    public boolean getBlockUninstallForUser(String packageName, int userId) {
13488        synchronized (mPackages) {
13489            PackageSetting ps = mSettings.mPackages.get(packageName);
13490            if (ps == null) {
13491                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13492                return false;
13493            }
13494            return ps.getBlockUninstall(userId);
13495        }
13496    }
13497
13498    /*
13499     * This method handles package deletion in general
13500     */
13501    private boolean deletePackageLI(String packageName, UserHandle user,
13502            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13503            int flags, PackageRemovedInfo outInfo,
13504            boolean writeSettings) {
13505        if (packageName == null) {
13506            Slog.w(TAG, "Attempt to delete null packageName.");
13507            return false;
13508        }
13509        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13510        PackageSetting ps;
13511        boolean dataOnly = false;
13512        int removeUser = -1;
13513        int appId = -1;
13514        synchronized (mPackages) {
13515            ps = mSettings.mPackages.get(packageName);
13516            if (ps == null) {
13517                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13518                return false;
13519            }
13520            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13521                    && user.getIdentifier() != UserHandle.USER_ALL) {
13522                // The caller is asking that the package only be deleted for a single
13523                // user.  To do this, we just mark its uninstalled state and delete
13524                // its data.  If this is a system app, we only allow this to happen if
13525                // they have set the special DELETE_SYSTEM_APP which requests different
13526                // semantics than normal for uninstalling system apps.
13527                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13528                final int userId = user.getIdentifier();
13529                ps.setUserState(userId,
13530                        COMPONENT_ENABLED_STATE_DEFAULT,
13531                        false, //installed
13532                        true,  //stopped
13533                        true,  //notLaunched
13534                        false, //hidden
13535                        null, null, null,
13536                        false, // blockUninstall
13537                        ps.readUserState(userId).domainVerificationStatus, 0);
13538                if (!isSystemApp(ps)) {
13539                    // Do not uninstall the APK if an app should be cached
13540                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13541                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13542                        // Other user still have this package installed, so all
13543                        // we need to do is clear this user's data and save that
13544                        // it is uninstalled.
13545                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13546                        removeUser = user.getIdentifier();
13547                        appId = ps.appId;
13548                        scheduleWritePackageRestrictionsLocked(removeUser);
13549                    } else {
13550                        // We need to set it back to 'installed' so the uninstall
13551                        // broadcasts will be sent correctly.
13552                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13553                        ps.setInstalled(true, user.getIdentifier());
13554                    }
13555                } else {
13556                    // This is a system app, so we assume that the
13557                    // other users still have this package installed, so all
13558                    // we need to do is clear this user's data and save that
13559                    // it is uninstalled.
13560                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13561                    removeUser = user.getIdentifier();
13562                    appId = ps.appId;
13563                    scheduleWritePackageRestrictionsLocked(removeUser);
13564                }
13565            }
13566        }
13567
13568        if (removeUser >= 0) {
13569            // From above, we determined that we are deleting this only
13570            // for a single user.  Continue the work here.
13571            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13572            if (outInfo != null) {
13573                outInfo.removedPackage = packageName;
13574                outInfo.removedAppId = appId;
13575                outInfo.removedUsers = new int[] {removeUser};
13576            }
13577            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13578            removeKeystoreDataIfNeeded(removeUser, appId);
13579            schedulePackageCleaning(packageName, removeUser, false);
13580            synchronized (mPackages) {
13581                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13582                    scheduleWritePackageRestrictionsLocked(removeUser);
13583                }
13584                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13585            }
13586            return true;
13587        }
13588
13589        if (dataOnly) {
13590            // Delete application data first
13591            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13592            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13593            return true;
13594        }
13595
13596        boolean ret = false;
13597        if (isSystemApp(ps)) {
13598            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13599            // When an updated system application is deleted we delete the existing resources as well and
13600            // fall back to existing code in system partition
13601            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13602                    flags, outInfo, writeSettings);
13603        } else {
13604            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13605            // Kill application pre-emptively especially for apps on sd.
13606            killApplication(packageName, ps.appId, "uninstall pkg");
13607            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13608                    allUserHandles, perUserInstalled,
13609                    outInfo, writeSettings);
13610        }
13611
13612        return ret;
13613    }
13614
13615    private final class ClearStorageConnection implements ServiceConnection {
13616        IMediaContainerService mContainerService;
13617
13618        @Override
13619        public void onServiceConnected(ComponentName name, IBinder service) {
13620            synchronized (this) {
13621                mContainerService = IMediaContainerService.Stub.asInterface(service);
13622                notifyAll();
13623            }
13624        }
13625
13626        @Override
13627        public void onServiceDisconnected(ComponentName name) {
13628        }
13629    }
13630
13631    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13632        final boolean mounted;
13633        if (Environment.isExternalStorageEmulated()) {
13634            mounted = true;
13635        } else {
13636            final String status = Environment.getExternalStorageState();
13637
13638            mounted = status.equals(Environment.MEDIA_MOUNTED)
13639                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13640        }
13641
13642        if (!mounted) {
13643            return;
13644        }
13645
13646        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13647        int[] users;
13648        if (userId == UserHandle.USER_ALL) {
13649            users = sUserManager.getUserIds();
13650        } else {
13651            users = new int[] { userId };
13652        }
13653        final ClearStorageConnection conn = new ClearStorageConnection();
13654        if (mContext.bindServiceAsUser(
13655                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13656            try {
13657                for (int curUser : users) {
13658                    long timeout = SystemClock.uptimeMillis() + 5000;
13659                    synchronized (conn) {
13660                        long now = SystemClock.uptimeMillis();
13661                        while (conn.mContainerService == null && now < timeout) {
13662                            try {
13663                                conn.wait(timeout - now);
13664                            } catch (InterruptedException e) {
13665                            }
13666                        }
13667                    }
13668                    if (conn.mContainerService == null) {
13669                        return;
13670                    }
13671
13672                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13673                    clearDirectory(conn.mContainerService,
13674                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13675                    if (allData) {
13676                        clearDirectory(conn.mContainerService,
13677                                userEnv.buildExternalStorageAppDataDirs(packageName));
13678                        clearDirectory(conn.mContainerService,
13679                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13680                    }
13681                }
13682            } finally {
13683                mContext.unbindService(conn);
13684            }
13685        }
13686    }
13687
13688    @Override
13689    public void clearApplicationUserData(final String packageName,
13690            final IPackageDataObserver observer, final int userId) {
13691        mContext.enforceCallingOrSelfPermission(
13692                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13693        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13694        // Queue up an async operation since the package deletion may take a little while.
13695        mHandler.post(new Runnable() {
13696            public void run() {
13697                mHandler.removeCallbacks(this);
13698                final boolean succeeded;
13699                synchronized (mInstallLock) {
13700                    succeeded = clearApplicationUserDataLI(packageName, userId);
13701                }
13702                clearExternalStorageDataSync(packageName, userId, true);
13703                if (succeeded) {
13704                    // invoke DeviceStorageMonitor's update method to clear any notifications
13705                    DeviceStorageMonitorInternal
13706                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13707                    if (dsm != null) {
13708                        dsm.checkMemory();
13709                    }
13710                }
13711                if(observer != null) {
13712                    try {
13713                        observer.onRemoveCompleted(packageName, succeeded);
13714                    } catch (RemoteException e) {
13715                        Log.i(TAG, "Observer no longer exists.");
13716                    }
13717                } //end if observer
13718            } //end run
13719        });
13720    }
13721
13722    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13723        if (packageName == null) {
13724            Slog.w(TAG, "Attempt to delete null packageName.");
13725            return false;
13726        }
13727
13728        // Try finding details about the requested package
13729        PackageParser.Package pkg;
13730        synchronized (mPackages) {
13731            pkg = mPackages.get(packageName);
13732            if (pkg == null) {
13733                final PackageSetting ps = mSettings.mPackages.get(packageName);
13734                if (ps != null) {
13735                    pkg = ps.pkg;
13736                }
13737            }
13738
13739            if (pkg == null) {
13740                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13741                return false;
13742            }
13743
13744            PackageSetting ps = (PackageSetting) pkg.mExtras;
13745            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13746        }
13747
13748        // Always delete data directories for package, even if we found no other
13749        // record of app. This helps users recover from UID mismatches without
13750        // resorting to a full data wipe.
13751        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13752        if (retCode < 0) {
13753            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13754            return false;
13755        }
13756
13757        final int appId = pkg.applicationInfo.uid;
13758        removeKeystoreDataIfNeeded(userId, appId);
13759
13760        // Create a native library symlink only if we have native libraries
13761        // and if the native libraries are 32 bit libraries. We do not provide
13762        // this symlink for 64 bit libraries.
13763        if (pkg.applicationInfo.primaryCpuAbi != null &&
13764                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13765            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13766            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13767                    nativeLibPath, userId) < 0) {
13768                Slog.w(TAG, "Failed linking native library dir");
13769                return false;
13770            }
13771        }
13772
13773        return true;
13774    }
13775
13776    /**
13777     * Reverts user permission state changes (permissions and flags) in
13778     * all packages for a given user.
13779     *
13780     * @param userId The device user for which to do a reset.
13781     */
13782    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13783        final int packageCount = mPackages.size();
13784        for (int i = 0; i < packageCount; i++) {
13785            PackageParser.Package pkg = mPackages.valueAt(i);
13786            PackageSetting ps = (PackageSetting) pkg.mExtras;
13787            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13788        }
13789    }
13790
13791    /**
13792     * Reverts user permission state changes (permissions and flags).
13793     *
13794     * @param ps The package for which to reset.
13795     * @param userId The device user for which to do a reset.
13796     */
13797    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13798            final PackageSetting ps, final int userId) {
13799        if (ps.pkg == null) {
13800            return;
13801        }
13802
13803        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13804                | FLAG_PERMISSION_USER_FIXED
13805                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13806
13807        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13808                | FLAG_PERMISSION_POLICY_FIXED;
13809
13810        boolean writeInstallPermissions = false;
13811        boolean writeRuntimePermissions = false;
13812
13813        final int permissionCount = ps.pkg.requestedPermissions.size();
13814        for (int i = 0; i < permissionCount; i++) {
13815            String permission = ps.pkg.requestedPermissions.get(i);
13816
13817            BasePermission bp = mSettings.mPermissions.get(permission);
13818            if (bp == null) {
13819                continue;
13820            }
13821
13822            // If shared user we just reset the state to which only this app contributed.
13823            if (ps.sharedUser != null) {
13824                boolean used = false;
13825                final int packageCount = ps.sharedUser.packages.size();
13826                for (int j = 0; j < packageCount; j++) {
13827                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13828                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13829                            && pkg.pkg.requestedPermissions.contains(permission)) {
13830                        used = true;
13831                        break;
13832                    }
13833                }
13834                if (used) {
13835                    continue;
13836                }
13837            }
13838
13839            PermissionsState permissionsState = ps.getPermissionsState();
13840
13841            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13842
13843            // Always clear the user settable flags.
13844            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13845                    bp.name) != null;
13846            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13847                if (hasInstallState) {
13848                    writeInstallPermissions = true;
13849                } else {
13850                    writeRuntimePermissions = true;
13851                }
13852            }
13853
13854            // Below is only runtime permission handling.
13855            if (!bp.isRuntime()) {
13856                continue;
13857            }
13858
13859            // Never clobber system or policy.
13860            if ((oldFlags & policyOrSystemFlags) != 0) {
13861                continue;
13862            }
13863
13864            // If this permission was granted by default, make sure it is.
13865            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13866                if (permissionsState.grantRuntimePermission(bp, userId)
13867                        != PERMISSION_OPERATION_FAILURE) {
13868                    writeRuntimePermissions = true;
13869                }
13870            } else {
13871                // Otherwise, reset the permission.
13872                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13873                switch (revokeResult) {
13874                    case PERMISSION_OPERATION_SUCCESS: {
13875                        writeRuntimePermissions = true;
13876                    } break;
13877
13878                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13879                        writeRuntimePermissions = true;
13880                        final int appId = ps.appId;
13881                        mHandler.post(new Runnable() {
13882                            @Override
13883                            public void run() {
13884                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13885                            }
13886                        });
13887                    } break;
13888                }
13889            }
13890        }
13891
13892        // Synchronously write as we are taking permissions away.
13893        if (writeRuntimePermissions) {
13894            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13895        }
13896
13897        // Synchronously write as we are taking permissions away.
13898        if (writeInstallPermissions) {
13899            mSettings.writeLPr();
13900        }
13901    }
13902
13903    /**
13904     * Remove entries from the keystore daemon. Will only remove it if the
13905     * {@code appId} is valid.
13906     */
13907    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13908        if (appId < 0) {
13909            return;
13910        }
13911
13912        final KeyStore keyStore = KeyStore.getInstance();
13913        if (keyStore != null) {
13914            if (userId == UserHandle.USER_ALL) {
13915                for (final int individual : sUserManager.getUserIds()) {
13916                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13917                }
13918            } else {
13919                keyStore.clearUid(UserHandle.getUid(userId, appId));
13920            }
13921        } else {
13922            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13923        }
13924    }
13925
13926    @Override
13927    public void deleteApplicationCacheFiles(final String packageName,
13928            final IPackageDataObserver observer) {
13929        mContext.enforceCallingOrSelfPermission(
13930                android.Manifest.permission.DELETE_CACHE_FILES, null);
13931        // Queue up an async operation since the package deletion may take a little while.
13932        final int userId = UserHandle.getCallingUserId();
13933        mHandler.post(new Runnable() {
13934            public void run() {
13935                mHandler.removeCallbacks(this);
13936                final boolean succeded;
13937                synchronized (mInstallLock) {
13938                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13939                }
13940                clearExternalStorageDataSync(packageName, userId, false);
13941                if (observer != null) {
13942                    try {
13943                        observer.onRemoveCompleted(packageName, succeded);
13944                    } catch (RemoteException e) {
13945                        Log.i(TAG, "Observer no longer exists.");
13946                    }
13947                } //end if observer
13948            } //end run
13949        });
13950    }
13951
13952    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13953        if (packageName == null) {
13954            Slog.w(TAG, "Attempt to delete null packageName.");
13955            return false;
13956        }
13957        PackageParser.Package p;
13958        synchronized (mPackages) {
13959            p = mPackages.get(packageName);
13960        }
13961        if (p == null) {
13962            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13963            return false;
13964        }
13965        final ApplicationInfo applicationInfo = p.applicationInfo;
13966        if (applicationInfo == null) {
13967            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13968            return false;
13969        }
13970        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13971        if (retCode < 0) {
13972            Slog.w(TAG, "Couldn't remove cache files for package: "
13973                       + packageName + " u" + userId);
13974            return false;
13975        }
13976        return true;
13977    }
13978
13979    @Override
13980    public void getPackageSizeInfo(final String packageName, int userHandle,
13981            final IPackageStatsObserver observer) {
13982        mContext.enforceCallingOrSelfPermission(
13983                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13984        if (packageName == null) {
13985            throw new IllegalArgumentException("Attempt to get size of null packageName");
13986        }
13987
13988        PackageStats stats = new PackageStats(packageName, userHandle);
13989
13990        /*
13991         * Queue up an async operation since the package measurement may take a
13992         * little while.
13993         */
13994        Message msg = mHandler.obtainMessage(INIT_COPY);
13995        msg.obj = new MeasureParams(stats, observer);
13996        mHandler.sendMessage(msg);
13997    }
13998
13999    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14000            PackageStats pStats) {
14001        if (packageName == null) {
14002            Slog.w(TAG, "Attempt to get size of null packageName.");
14003            return false;
14004        }
14005        PackageParser.Package p;
14006        boolean dataOnly = false;
14007        String libDirRoot = null;
14008        String asecPath = null;
14009        PackageSetting ps = null;
14010        synchronized (mPackages) {
14011            p = mPackages.get(packageName);
14012            ps = mSettings.mPackages.get(packageName);
14013            if(p == null) {
14014                dataOnly = true;
14015                if((ps == null) || (ps.pkg == null)) {
14016                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14017                    return false;
14018                }
14019                p = ps.pkg;
14020            }
14021            if (ps != null) {
14022                libDirRoot = ps.legacyNativeLibraryPathString;
14023            }
14024            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14025                final long token = Binder.clearCallingIdentity();
14026                try {
14027                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14028                    if (secureContainerId != null) {
14029                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14030                    }
14031                } finally {
14032                    Binder.restoreCallingIdentity(token);
14033                }
14034            }
14035        }
14036        String publicSrcDir = null;
14037        if(!dataOnly) {
14038            final ApplicationInfo applicationInfo = p.applicationInfo;
14039            if (applicationInfo == null) {
14040                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14041                return false;
14042            }
14043            if (p.isForwardLocked()) {
14044                publicSrcDir = applicationInfo.getBaseResourcePath();
14045            }
14046        }
14047        // TODO: extend to measure size of split APKs
14048        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14049        // not just the first level.
14050        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14051        // just the primary.
14052        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14053
14054        String apkPath;
14055        File packageDir = new File(p.codePath);
14056
14057        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14058            apkPath = packageDir.getAbsolutePath();
14059            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14060            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14061                libDirRoot = null;
14062            }
14063        } else {
14064            apkPath = p.baseCodePath;
14065        }
14066
14067        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14068                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14069        if (res < 0) {
14070            return false;
14071        }
14072
14073        // Fix-up for forward-locked applications in ASEC containers.
14074        if (!isExternal(p)) {
14075            pStats.codeSize += pStats.externalCodeSize;
14076            pStats.externalCodeSize = 0L;
14077        }
14078
14079        return true;
14080    }
14081
14082
14083    @Override
14084    public void addPackageToPreferred(String packageName) {
14085        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14086    }
14087
14088    @Override
14089    public void removePackageFromPreferred(String packageName) {
14090        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14091    }
14092
14093    @Override
14094    public List<PackageInfo> getPreferredPackages(int flags) {
14095        return new ArrayList<PackageInfo>();
14096    }
14097
14098    private int getUidTargetSdkVersionLockedLPr(int uid) {
14099        Object obj = mSettings.getUserIdLPr(uid);
14100        if (obj instanceof SharedUserSetting) {
14101            final SharedUserSetting sus = (SharedUserSetting) obj;
14102            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14103            final Iterator<PackageSetting> it = sus.packages.iterator();
14104            while (it.hasNext()) {
14105                final PackageSetting ps = it.next();
14106                if (ps.pkg != null) {
14107                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14108                    if (v < vers) vers = v;
14109                }
14110            }
14111            return vers;
14112        } else if (obj instanceof PackageSetting) {
14113            final PackageSetting ps = (PackageSetting) obj;
14114            if (ps.pkg != null) {
14115                return ps.pkg.applicationInfo.targetSdkVersion;
14116            }
14117        }
14118        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14119    }
14120
14121    @Override
14122    public void addPreferredActivity(IntentFilter filter, int match,
14123            ComponentName[] set, ComponentName activity, int userId) {
14124        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14125                "Adding preferred");
14126    }
14127
14128    private void addPreferredActivityInternal(IntentFilter filter, int match,
14129            ComponentName[] set, ComponentName activity, boolean always, int userId,
14130            String opname) {
14131        // writer
14132        int callingUid = Binder.getCallingUid();
14133        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14134        if (filter.countActions() == 0) {
14135            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14136            return;
14137        }
14138        synchronized (mPackages) {
14139            if (mContext.checkCallingOrSelfPermission(
14140                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14141                    != PackageManager.PERMISSION_GRANTED) {
14142                if (getUidTargetSdkVersionLockedLPr(callingUid)
14143                        < Build.VERSION_CODES.FROYO) {
14144                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14145                            + callingUid);
14146                    return;
14147                }
14148                mContext.enforceCallingOrSelfPermission(
14149                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14150            }
14151
14152            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14153            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14154                    + userId + ":");
14155            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14156            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14157            scheduleWritePackageRestrictionsLocked(userId);
14158        }
14159    }
14160
14161    @Override
14162    public void replacePreferredActivity(IntentFilter filter, int match,
14163            ComponentName[] set, ComponentName activity, int userId) {
14164        if (filter.countActions() != 1) {
14165            throw new IllegalArgumentException(
14166                    "replacePreferredActivity expects filter to have only 1 action.");
14167        }
14168        if (filter.countDataAuthorities() != 0
14169                || filter.countDataPaths() != 0
14170                || filter.countDataSchemes() > 1
14171                || filter.countDataTypes() != 0) {
14172            throw new IllegalArgumentException(
14173                    "replacePreferredActivity expects filter to have no data authorities, " +
14174                    "paths, or types; and at most one scheme.");
14175        }
14176
14177        final int callingUid = Binder.getCallingUid();
14178        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14179        synchronized (mPackages) {
14180            if (mContext.checkCallingOrSelfPermission(
14181                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14182                    != PackageManager.PERMISSION_GRANTED) {
14183                if (getUidTargetSdkVersionLockedLPr(callingUid)
14184                        < Build.VERSION_CODES.FROYO) {
14185                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14186                            + Binder.getCallingUid());
14187                    return;
14188                }
14189                mContext.enforceCallingOrSelfPermission(
14190                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14191            }
14192
14193            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14194            if (pir != null) {
14195                // Get all of the existing entries that exactly match this filter.
14196                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14197                if (existing != null && existing.size() == 1) {
14198                    PreferredActivity cur = existing.get(0);
14199                    if (DEBUG_PREFERRED) {
14200                        Slog.i(TAG, "Checking replace of preferred:");
14201                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14202                        if (!cur.mPref.mAlways) {
14203                            Slog.i(TAG, "  -- CUR; not mAlways!");
14204                        } else {
14205                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14206                            Slog.i(TAG, "  -- CUR: mSet="
14207                                    + Arrays.toString(cur.mPref.mSetComponents));
14208                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14209                            Slog.i(TAG, "  -- NEW: mMatch="
14210                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14211                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14212                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14213                        }
14214                    }
14215                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14216                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14217                            && cur.mPref.sameSet(set)) {
14218                        // Setting the preferred activity to what it happens to be already
14219                        if (DEBUG_PREFERRED) {
14220                            Slog.i(TAG, "Replacing with same preferred activity "
14221                                    + cur.mPref.mShortComponent + " for user "
14222                                    + userId + ":");
14223                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14224                        }
14225                        return;
14226                    }
14227                }
14228
14229                if (existing != null) {
14230                    if (DEBUG_PREFERRED) {
14231                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14232                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14233                    }
14234                    for (int i = 0; i < existing.size(); i++) {
14235                        PreferredActivity pa = existing.get(i);
14236                        if (DEBUG_PREFERRED) {
14237                            Slog.i(TAG, "Removing existing preferred activity "
14238                                    + pa.mPref.mComponent + ":");
14239                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14240                        }
14241                        pir.removeFilter(pa);
14242                    }
14243                }
14244            }
14245            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14246                    "Replacing preferred");
14247        }
14248    }
14249
14250    @Override
14251    public void clearPackagePreferredActivities(String packageName) {
14252        final int uid = Binder.getCallingUid();
14253        // writer
14254        synchronized (mPackages) {
14255            PackageParser.Package pkg = mPackages.get(packageName);
14256            if (pkg == null || pkg.applicationInfo.uid != uid) {
14257                if (mContext.checkCallingOrSelfPermission(
14258                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14259                        != PackageManager.PERMISSION_GRANTED) {
14260                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14261                            < Build.VERSION_CODES.FROYO) {
14262                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14263                                + Binder.getCallingUid());
14264                        return;
14265                    }
14266                    mContext.enforceCallingOrSelfPermission(
14267                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14268                }
14269            }
14270
14271            int user = UserHandle.getCallingUserId();
14272            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14273                scheduleWritePackageRestrictionsLocked(user);
14274            }
14275        }
14276    }
14277
14278    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14279    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14280        ArrayList<PreferredActivity> removed = null;
14281        boolean changed = false;
14282        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14283            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14284            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14285            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14286                continue;
14287            }
14288            Iterator<PreferredActivity> it = pir.filterIterator();
14289            while (it.hasNext()) {
14290                PreferredActivity pa = it.next();
14291                // Mark entry for removal only if it matches the package name
14292                // and the entry is of type "always".
14293                if (packageName == null ||
14294                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14295                                && pa.mPref.mAlways)) {
14296                    if (removed == null) {
14297                        removed = new ArrayList<PreferredActivity>();
14298                    }
14299                    removed.add(pa);
14300                }
14301            }
14302            if (removed != null) {
14303                for (int j=0; j<removed.size(); j++) {
14304                    PreferredActivity pa = removed.get(j);
14305                    pir.removeFilter(pa);
14306                }
14307                changed = true;
14308            }
14309        }
14310        return changed;
14311    }
14312
14313    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14314    private void clearIntentFilterVerificationsLPw(int userId) {
14315        final int packageCount = mPackages.size();
14316        for (int i = 0; i < packageCount; i++) {
14317            PackageParser.Package pkg = mPackages.valueAt(i);
14318            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14319        }
14320    }
14321
14322    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14323    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14324        if (userId == UserHandle.USER_ALL) {
14325            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14326                    sUserManager.getUserIds())) {
14327                for (int oneUserId : sUserManager.getUserIds()) {
14328                    scheduleWritePackageRestrictionsLocked(oneUserId);
14329                }
14330            }
14331        } else {
14332            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14333                scheduleWritePackageRestrictionsLocked(userId);
14334            }
14335        }
14336    }
14337
14338    void clearDefaultBrowserIfNeeded(String packageName) {
14339        for (int oneUserId : sUserManager.getUserIds()) {
14340            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14341            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14342            if (packageName.equals(defaultBrowserPackageName)) {
14343                setDefaultBrowserPackageName(null, oneUserId);
14344            }
14345        }
14346    }
14347
14348    @Override
14349    public void resetApplicationPreferences(int userId) {
14350        mContext.enforceCallingOrSelfPermission(
14351                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14352        // writer
14353        synchronized (mPackages) {
14354            final long identity = Binder.clearCallingIdentity();
14355            try {
14356                clearPackagePreferredActivitiesLPw(null, userId);
14357                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14358                // TODO: We have to reset the default SMS and Phone. This requires
14359                // significant refactoring to keep all default apps in the package
14360                // manager (cleaner but more work) or have the services provide
14361                // callbacks to the package manager to request a default app reset.
14362                applyFactoryDefaultBrowserLPw(userId);
14363                clearIntentFilterVerificationsLPw(userId);
14364                primeDomainVerificationsLPw(userId);
14365                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14366                scheduleWritePackageRestrictionsLocked(userId);
14367            } finally {
14368                Binder.restoreCallingIdentity(identity);
14369            }
14370        }
14371    }
14372
14373    @Override
14374    public int getPreferredActivities(List<IntentFilter> outFilters,
14375            List<ComponentName> outActivities, String packageName) {
14376
14377        int num = 0;
14378        final int userId = UserHandle.getCallingUserId();
14379        // reader
14380        synchronized (mPackages) {
14381            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14382            if (pir != null) {
14383                final Iterator<PreferredActivity> it = pir.filterIterator();
14384                while (it.hasNext()) {
14385                    final PreferredActivity pa = it.next();
14386                    if (packageName == null
14387                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14388                                    && pa.mPref.mAlways)) {
14389                        if (outFilters != null) {
14390                            outFilters.add(new IntentFilter(pa));
14391                        }
14392                        if (outActivities != null) {
14393                            outActivities.add(pa.mPref.mComponent);
14394                        }
14395                    }
14396                }
14397            }
14398        }
14399
14400        return num;
14401    }
14402
14403    @Override
14404    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14405            int userId) {
14406        int callingUid = Binder.getCallingUid();
14407        if (callingUid != Process.SYSTEM_UID) {
14408            throw new SecurityException(
14409                    "addPersistentPreferredActivity can only be run by the system");
14410        }
14411        if (filter.countActions() == 0) {
14412            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14413            return;
14414        }
14415        synchronized (mPackages) {
14416            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14417                    " :");
14418            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14419            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14420                    new PersistentPreferredActivity(filter, activity));
14421            scheduleWritePackageRestrictionsLocked(userId);
14422        }
14423    }
14424
14425    @Override
14426    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14427        int callingUid = Binder.getCallingUid();
14428        if (callingUid != Process.SYSTEM_UID) {
14429            throw new SecurityException(
14430                    "clearPackagePersistentPreferredActivities can only be run by the system");
14431        }
14432        ArrayList<PersistentPreferredActivity> removed = null;
14433        boolean changed = false;
14434        synchronized (mPackages) {
14435            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14436                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14437                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14438                        .valueAt(i);
14439                if (userId != thisUserId) {
14440                    continue;
14441                }
14442                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14443                while (it.hasNext()) {
14444                    PersistentPreferredActivity ppa = it.next();
14445                    // Mark entry for removal only if it matches the package name.
14446                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14447                        if (removed == null) {
14448                            removed = new ArrayList<PersistentPreferredActivity>();
14449                        }
14450                        removed.add(ppa);
14451                    }
14452                }
14453                if (removed != null) {
14454                    for (int j=0; j<removed.size(); j++) {
14455                        PersistentPreferredActivity ppa = removed.get(j);
14456                        ppir.removeFilter(ppa);
14457                    }
14458                    changed = true;
14459                }
14460            }
14461
14462            if (changed) {
14463                scheduleWritePackageRestrictionsLocked(userId);
14464            }
14465        }
14466    }
14467
14468    /**
14469     * Common machinery for picking apart a restored XML blob and passing
14470     * it to a caller-supplied functor to be applied to the running system.
14471     */
14472    private void restoreFromXml(XmlPullParser parser, int userId,
14473            String expectedStartTag, BlobXmlRestorer functor)
14474            throws IOException, XmlPullParserException {
14475        int type;
14476        while ((type = parser.next()) != XmlPullParser.START_TAG
14477                && type != XmlPullParser.END_DOCUMENT) {
14478        }
14479        if (type != XmlPullParser.START_TAG) {
14480            // oops didn't find a start tag?!
14481            if (DEBUG_BACKUP) {
14482                Slog.e(TAG, "Didn't find start tag during restore");
14483            }
14484            return;
14485        }
14486
14487        // this is supposed to be TAG_PREFERRED_BACKUP
14488        if (!expectedStartTag.equals(parser.getName())) {
14489            if (DEBUG_BACKUP) {
14490                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14491            }
14492            return;
14493        }
14494
14495        // skip interfering stuff, then we're aligned with the backing implementation
14496        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14497        functor.apply(parser, userId);
14498    }
14499
14500    private interface BlobXmlRestorer {
14501        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14502    }
14503
14504    /**
14505     * Non-Binder method, support for the backup/restore mechanism: write the
14506     * full set of preferred activities in its canonical XML format.  Returns the
14507     * XML output as a byte array, or null if there is none.
14508     */
14509    @Override
14510    public byte[] getPreferredActivityBackup(int userId) {
14511        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14512            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14513        }
14514
14515        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14516        try {
14517            final XmlSerializer serializer = new FastXmlSerializer();
14518            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14519            serializer.startDocument(null, true);
14520            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14521
14522            synchronized (mPackages) {
14523                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14524            }
14525
14526            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14527            serializer.endDocument();
14528            serializer.flush();
14529        } catch (Exception e) {
14530            if (DEBUG_BACKUP) {
14531                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14532            }
14533            return null;
14534        }
14535
14536        return dataStream.toByteArray();
14537    }
14538
14539    @Override
14540    public void restorePreferredActivities(byte[] backup, int userId) {
14541        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14542            throw new SecurityException("Only the system may call restorePreferredActivities()");
14543        }
14544
14545        try {
14546            final XmlPullParser parser = Xml.newPullParser();
14547            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14548            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14549                    new BlobXmlRestorer() {
14550                        @Override
14551                        public void apply(XmlPullParser parser, int userId)
14552                                throws XmlPullParserException, IOException {
14553                            synchronized (mPackages) {
14554                                mSettings.readPreferredActivitiesLPw(parser, userId);
14555                            }
14556                        }
14557                    } );
14558        } catch (Exception e) {
14559            if (DEBUG_BACKUP) {
14560                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14561            }
14562        }
14563    }
14564
14565    /**
14566     * Non-Binder method, support for the backup/restore mechanism: write the
14567     * default browser (etc) settings in its canonical XML format.  Returns the default
14568     * browser XML representation as a byte array, or null if there is none.
14569     */
14570    @Override
14571    public byte[] getDefaultAppsBackup(int userId) {
14572        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14573            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14574        }
14575
14576        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14577        try {
14578            final XmlSerializer serializer = new FastXmlSerializer();
14579            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14580            serializer.startDocument(null, true);
14581            serializer.startTag(null, TAG_DEFAULT_APPS);
14582
14583            synchronized (mPackages) {
14584                mSettings.writeDefaultAppsLPr(serializer, userId);
14585            }
14586
14587            serializer.endTag(null, TAG_DEFAULT_APPS);
14588            serializer.endDocument();
14589            serializer.flush();
14590        } catch (Exception e) {
14591            if (DEBUG_BACKUP) {
14592                Slog.e(TAG, "Unable to write default apps for backup", e);
14593            }
14594            return null;
14595        }
14596
14597        return dataStream.toByteArray();
14598    }
14599
14600    @Override
14601    public void restoreDefaultApps(byte[] backup, int userId) {
14602        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14603            throw new SecurityException("Only the system may call restoreDefaultApps()");
14604        }
14605
14606        try {
14607            final XmlPullParser parser = Xml.newPullParser();
14608            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14609            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14610                    new BlobXmlRestorer() {
14611                        @Override
14612                        public void apply(XmlPullParser parser, int userId)
14613                                throws XmlPullParserException, IOException {
14614                            synchronized (mPackages) {
14615                                mSettings.readDefaultAppsLPw(parser, userId);
14616                            }
14617                        }
14618                    } );
14619        } catch (Exception e) {
14620            if (DEBUG_BACKUP) {
14621                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14622            }
14623        }
14624    }
14625
14626    @Override
14627    public byte[] getIntentFilterVerificationBackup(int userId) {
14628        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14629            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14630        }
14631
14632        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14633        try {
14634            final XmlSerializer serializer = new FastXmlSerializer();
14635            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14636            serializer.startDocument(null, true);
14637            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14638
14639            synchronized (mPackages) {
14640                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14641            }
14642
14643            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14644            serializer.endDocument();
14645            serializer.flush();
14646        } catch (Exception e) {
14647            if (DEBUG_BACKUP) {
14648                Slog.e(TAG, "Unable to write default apps for backup", e);
14649            }
14650            return null;
14651        }
14652
14653        return dataStream.toByteArray();
14654    }
14655
14656    @Override
14657    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14658        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14659            throw new SecurityException("Only the system may call restorePreferredActivities()");
14660        }
14661
14662        try {
14663            final XmlPullParser parser = Xml.newPullParser();
14664            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14665            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14666                    new BlobXmlRestorer() {
14667                        @Override
14668                        public void apply(XmlPullParser parser, int userId)
14669                                throws XmlPullParserException, IOException {
14670                            synchronized (mPackages) {
14671                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14672                                mSettings.writeLPr();
14673                            }
14674                        }
14675                    } );
14676        } catch (Exception e) {
14677            if (DEBUG_BACKUP) {
14678                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14679            }
14680        }
14681    }
14682
14683    @Override
14684    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14685            int sourceUserId, int targetUserId, int flags) {
14686        mContext.enforceCallingOrSelfPermission(
14687                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14688        int callingUid = Binder.getCallingUid();
14689        enforceOwnerRights(ownerPackage, callingUid);
14690        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14691        if (intentFilter.countActions() == 0) {
14692            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14693            return;
14694        }
14695        synchronized (mPackages) {
14696            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14697                    ownerPackage, targetUserId, flags);
14698            CrossProfileIntentResolver resolver =
14699                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14700            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14701            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14702            if (existing != null) {
14703                int size = existing.size();
14704                for (int i = 0; i < size; i++) {
14705                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14706                        return;
14707                    }
14708                }
14709            }
14710            resolver.addFilter(newFilter);
14711            scheduleWritePackageRestrictionsLocked(sourceUserId);
14712        }
14713    }
14714
14715    @Override
14716    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14717        mContext.enforceCallingOrSelfPermission(
14718                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14719        int callingUid = Binder.getCallingUid();
14720        enforceOwnerRights(ownerPackage, callingUid);
14721        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14722        synchronized (mPackages) {
14723            CrossProfileIntentResolver resolver =
14724                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14725            ArraySet<CrossProfileIntentFilter> set =
14726                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14727            for (CrossProfileIntentFilter filter : set) {
14728                if (filter.getOwnerPackage().equals(ownerPackage)) {
14729                    resolver.removeFilter(filter);
14730                }
14731            }
14732            scheduleWritePackageRestrictionsLocked(sourceUserId);
14733        }
14734    }
14735
14736    // Enforcing that callingUid is owning pkg on userId
14737    private void enforceOwnerRights(String pkg, int callingUid) {
14738        // The system owns everything.
14739        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14740            return;
14741        }
14742        int callingUserId = UserHandle.getUserId(callingUid);
14743        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14744        if (pi == null) {
14745            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14746                    + callingUserId);
14747        }
14748        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14749            throw new SecurityException("Calling uid " + callingUid
14750                    + " does not own package " + pkg);
14751        }
14752    }
14753
14754    @Override
14755    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14756        Intent intent = new Intent(Intent.ACTION_MAIN);
14757        intent.addCategory(Intent.CATEGORY_HOME);
14758
14759        final int callingUserId = UserHandle.getCallingUserId();
14760        List<ResolveInfo> list = queryIntentActivities(intent, null,
14761                PackageManager.GET_META_DATA, callingUserId);
14762        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14763                true, false, false, callingUserId);
14764
14765        allHomeCandidates.clear();
14766        if (list != null) {
14767            for (ResolveInfo ri : list) {
14768                allHomeCandidates.add(ri);
14769            }
14770        }
14771        return (preferred == null || preferred.activityInfo == null)
14772                ? null
14773                : new ComponentName(preferred.activityInfo.packageName,
14774                        preferred.activityInfo.name);
14775    }
14776
14777    @Override
14778    public void setApplicationEnabledSetting(String appPackageName,
14779            int newState, int flags, int userId, String callingPackage) {
14780        if (!sUserManager.exists(userId)) return;
14781        if (callingPackage == null) {
14782            callingPackage = Integer.toString(Binder.getCallingUid());
14783        }
14784        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14785    }
14786
14787    @Override
14788    public void setComponentEnabledSetting(ComponentName componentName,
14789            int newState, int flags, int userId) {
14790        if (!sUserManager.exists(userId)) return;
14791        setEnabledSetting(componentName.getPackageName(),
14792                componentName.getClassName(), newState, flags, userId, null);
14793    }
14794
14795    private void setEnabledSetting(final String packageName, String className, int newState,
14796            final int flags, int userId, String callingPackage) {
14797        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14798              || newState == COMPONENT_ENABLED_STATE_ENABLED
14799              || newState == COMPONENT_ENABLED_STATE_DISABLED
14800              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14801              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14802            throw new IllegalArgumentException("Invalid new component state: "
14803                    + newState);
14804        }
14805        PackageSetting pkgSetting;
14806        final int uid = Binder.getCallingUid();
14807        final int permission = mContext.checkCallingOrSelfPermission(
14808                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14809        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14810        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14811        boolean sendNow = false;
14812        boolean isApp = (className == null);
14813        String componentName = isApp ? packageName : className;
14814        int packageUid = -1;
14815        ArrayList<String> components;
14816
14817        // writer
14818        synchronized (mPackages) {
14819            pkgSetting = mSettings.mPackages.get(packageName);
14820            if (pkgSetting == null) {
14821                if (className == null) {
14822                    throw new IllegalArgumentException(
14823                            "Unknown package: " + packageName);
14824                }
14825                throw new IllegalArgumentException(
14826                        "Unknown component: " + packageName
14827                        + "/" + className);
14828            }
14829            // Allow root and verify that userId is not being specified by a different user
14830            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14831                throw new SecurityException(
14832                        "Permission Denial: attempt to change component state from pid="
14833                        + Binder.getCallingPid()
14834                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14835            }
14836            if (className == null) {
14837                // We're dealing with an application/package level state change
14838                if (pkgSetting.getEnabled(userId) == newState) {
14839                    // Nothing to do
14840                    return;
14841                }
14842                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14843                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14844                    // Don't care about who enables an app.
14845                    callingPackage = null;
14846                }
14847                pkgSetting.setEnabled(newState, userId, callingPackage);
14848                // pkgSetting.pkg.mSetEnabled = newState;
14849            } else {
14850                // We're dealing with a component level state change
14851                // First, verify that this is a valid class name.
14852                PackageParser.Package pkg = pkgSetting.pkg;
14853                if (pkg == null || !pkg.hasComponentClassName(className)) {
14854                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14855                        throw new IllegalArgumentException("Component class " + className
14856                                + " does not exist in " + packageName);
14857                    } else {
14858                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14859                                + className + " does not exist in " + packageName);
14860                    }
14861                }
14862                switch (newState) {
14863                case COMPONENT_ENABLED_STATE_ENABLED:
14864                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14865                        return;
14866                    }
14867                    break;
14868                case COMPONENT_ENABLED_STATE_DISABLED:
14869                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14870                        return;
14871                    }
14872                    break;
14873                case COMPONENT_ENABLED_STATE_DEFAULT:
14874                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14875                        return;
14876                    }
14877                    break;
14878                default:
14879                    Slog.e(TAG, "Invalid new component state: " + newState);
14880                    return;
14881                }
14882            }
14883            scheduleWritePackageRestrictionsLocked(userId);
14884            components = mPendingBroadcasts.get(userId, packageName);
14885            final boolean newPackage = components == null;
14886            if (newPackage) {
14887                components = new ArrayList<String>();
14888            }
14889            if (!components.contains(componentName)) {
14890                components.add(componentName);
14891            }
14892            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14893                sendNow = true;
14894                // Purge entry from pending broadcast list if another one exists already
14895                // since we are sending one right away.
14896                mPendingBroadcasts.remove(userId, packageName);
14897            } else {
14898                if (newPackage) {
14899                    mPendingBroadcasts.put(userId, packageName, components);
14900                }
14901                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14902                    // Schedule a message
14903                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14904                }
14905            }
14906        }
14907
14908        long callingId = Binder.clearCallingIdentity();
14909        try {
14910            if (sendNow) {
14911                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14912                sendPackageChangedBroadcast(packageName,
14913                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14914            }
14915        } finally {
14916            Binder.restoreCallingIdentity(callingId);
14917        }
14918    }
14919
14920    private void sendPackageChangedBroadcast(String packageName,
14921            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14922        if (DEBUG_INSTALL)
14923            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14924                    + componentNames);
14925        Bundle extras = new Bundle(4);
14926        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14927        String nameList[] = new String[componentNames.size()];
14928        componentNames.toArray(nameList);
14929        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14930        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14931        extras.putInt(Intent.EXTRA_UID, packageUid);
14932        // If this is not reporting a change of the overall package, then only send it
14933        // to registered receivers.  We don't want to launch a swath of apps for every
14934        // little component state change.
14935        final int flags = !componentNames.contains(packageName)
14936                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
14937        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
14938                new int[] {UserHandle.getUserId(packageUid)});
14939    }
14940
14941    @Override
14942    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14943        if (!sUserManager.exists(userId)) return;
14944        final int uid = Binder.getCallingUid();
14945        final int permission = mContext.checkCallingOrSelfPermission(
14946                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14947        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14948        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14949        // writer
14950        synchronized (mPackages) {
14951            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14952                    allowedByPermission, uid, userId)) {
14953                scheduleWritePackageRestrictionsLocked(userId);
14954            }
14955        }
14956    }
14957
14958    @Override
14959    public String getInstallerPackageName(String packageName) {
14960        // reader
14961        synchronized (mPackages) {
14962            return mSettings.getInstallerPackageNameLPr(packageName);
14963        }
14964    }
14965
14966    @Override
14967    public int getApplicationEnabledSetting(String packageName, int userId) {
14968        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14969        int uid = Binder.getCallingUid();
14970        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14971        // reader
14972        synchronized (mPackages) {
14973            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14974        }
14975    }
14976
14977    @Override
14978    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14979        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14980        int uid = Binder.getCallingUid();
14981        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14982        // reader
14983        synchronized (mPackages) {
14984            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14985        }
14986    }
14987
14988    @Override
14989    public void enterSafeMode() {
14990        enforceSystemOrRoot("Only the system can request entering safe mode");
14991
14992        if (!mSystemReady) {
14993            mSafeMode = true;
14994        }
14995    }
14996
14997    @Override
14998    public void systemReady() {
14999        mSystemReady = true;
15000
15001        // Read the compatibilty setting when the system is ready.
15002        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15003                mContext.getContentResolver(),
15004                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15005        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15006        if (DEBUG_SETTINGS) {
15007            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15008        }
15009
15010        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15011
15012        synchronized (mPackages) {
15013            // Verify that all of the preferred activity components actually
15014            // exist.  It is possible for applications to be updated and at
15015            // that point remove a previously declared activity component that
15016            // had been set as a preferred activity.  We try to clean this up
15017            // the next time we encounter that preferred activity, but it is
15018            // possible for the user flow to never be able to return to that
15019            // situation so here we do a sanity check to make sure we haven't
15020            // left any junk around.
15021            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15022            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15023                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15024                removed.clear();
15025                for (PreferredActivity pa : pir.filterSet()) {
15026                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15027                        removed.add(pa);
15028                    }
15029                }
15030                if (removed.size() > 0) {
15031                    for (int r=0; r<removed.size(); r++) {
15032                        PreferredActivity pa = removed.get(r);
15033                        Slog.w(TAG, "Removing dangling preferred activity: "
15034                                + pa.mPref.mComponent);
15035                        pir.removeFilter(pa);
15036                    }
15037                    mSettings.writePackageRestrictionsLPr(
15038                            mSettings.mPreferredActivities.keyAt(i));
15039                }
15040            }
15041
15042            for (int userId : UserManagerService.getInstance().getUserIds()) {
15043                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15044                    grantPermissionsUserIds = ArrayUtils.appendInt(
15045                            grantPermissionsUserIds, userId);
15046                }
15047            }
15048        }
15049        sUserManager.systemReady();
15050
15051        // If we upgraded grant all default permissions before kicking off.
15052        for (int userId : grantPermissionsUserIds) {
15053            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15054        }
15055
15056        // Kick off any messages waiting for system ready
15057        if (mPostSystemReadyMessages != null) {
15058            for (Message msg : mPostSystemReadyMessages) {
15059                msg.sendToTarget();
15060            }
15061            mPostSystemReadyMessages = null;
15062        }
15063
15064        // Watch for external volumes that come and go over time
15065        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15066        storage.registerListener(mStorageListener);
15067
15068        mInstallerService.systemReady();
15069        mPackageDexOptimizer.systemReady();
15070
15071        MountServiceInternal mountServiceInternal = LocalServices.getService(
15072                MountServiceInternal.class);
15073        mountServiceInternal.addExternalStoragePolicy(
15074                new MountServiceInternal.ExternalStorageMountPolicy() {
15075            @Override
15076            public int getMountMode(int uid, String packageName) {
15077                if (Process.isIsolated(uid)) {
15078                    return Zygote.MOUNT_EXTERNAL_NONE;
15079                }
15080                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15081                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15082                }
15083                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15084                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15085                }
15086                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15087                    return Zygote.MOUNT_EXTERNAL_READ;
15088                }
15089                return Zygote.MOUNT_EXTERNAL_WRITE;
15090            }
15091
15092            @Override
15093            public boolean hasExternalStorage(int uid, String packageName) {
15094                return true;
15095            }
15096        });
15097    }
15098
15099    @Override
15100    public boolean isSafeMode() {
15101        return mSafeMode;
15102    }
15103
15104    @Override
15105    public boolean hasSystemUidErrors() {
15106        return mHasSystemUidErrors;
15107    }
15108
15109    static String arrayToString(int[] array) {
15110        StringBuffer buf = new StringBuffer(128);
15111        buf.append('[');
15112        if (array != null) {
15113            for (int i=0; i<array.length; i++) {
15114                if (i > 0) buf.append(", ");
15115                buf.append(array[i]);
15116            }
15117        }
15118        buf.append(']');
15119        return buf.toString();
15120    }
15121
15122    static class DumpState {
15123        public static final int DUMP_LIBS = 1 << 0;
15124        public static final int DUMP_FEATURES = 1 << 1;
15125        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15126        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15127        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15128        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15129        public static final int DUMP_PERMISSIONS = 1 << 6;
15130        public static final int DUMP_PACKAGES = 1 << 7;
15131        public static final int DUMP_SHARED_USERS = 1 << 8;
15132        public static final int DUMP_MESSAGES = 1 << 9;
15133        public static final int DUMP_PROVIDERS = 1 << 10;
15134        public static final int DUMP_VERIFIERS = 1 << 11;
15135        public static final int DUMP_PREFERRED = 1 << 12;
15136        public static final int DUMP_PREFERRED_XML = 1 << 13;
15137        public static final int DUMP_KEYSETS = 1 << 14;
15138        public static final int DUMP_VERSION = 1 << 15;
15139        public static final int DUMP_INSTALLS = 1 << 16;
15140        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15141        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15142
15143        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15144
15145        private int mTypes;
15146
15147        private int mOptions;
15148
15149        private boolean mTitlePrinted;
15150
15151        private SharedUserSetting mSharedUser;
15152
15153        public boolean isDumping(int type) {
15154            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15155                return true;
15156            }
15157
15158            return (mTypes & type) != 0;
15159        }
15160
15161        public void setDump(int type) {
15162            mTypes |= type;
15163        }
15164
15165        public boolean isOptionEnabled(int option) {
15166            return (mOptions & option) != 0;
15167        }
15168
15169        public void setOptionEnabled(int option) {
15170            mOptions |= option;
15171        }
15172
15173        public boolean onTitlePrinted() {
15174            final boolean printed = mTitlePrinted;
15175            mTitlePrinted = true;
15176            return printed;
15177        }
15178
15179        public boolean getTitlePrinted() {
15180            return mTitlePrinted;
15181        }
15182
15183        public void setTitlePrinted(boolean enabled) {
15184            mTitlePrinted = enabled;
15185        }
15186
15187        public SharedUserSetting getSharedUser() {
15188            return mSharedUser;
15189        }
15190
15191        public void setSharedUser(SharedUserSetting user) {
15192            mSharedUser = user;
15193        }
15194    }
15195
15196    @Override
15197    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15198            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15199        (new PackageManagerShellCommand(this)).exec(
15200                this, in, out, err, args, resultReceiver);
15201    }
15202
15203    @Override
15204    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15205        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15206                != PackageManager.PERMISSION_GRANTED) {
15207            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15208                    + Binder.getCallingPid()
15209                    + ", uid=" + Binder.getCallingUid()
15210                    + " without permission "
15211                    + android.Manifest.permission.DUMP);
15212            return;
15213        }
15214
15215        DumpState dumpState = new DumpState();
15216        boolean fullPreferred = false;
15217        boolean checkin = false;
15218
15219        String packageName = null;
15220        ArraySet<String> permissionNames = null;
15221
15222        int opti = 0;
15223        while (opti < args.length) {
15224            String opt = args[opti];
15225            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15226                break;
15227            }
15228            opti++;
15229
15230            if ("-a".equals(opt)) {
15231                // Right now we only know how to print all.
15232            } else if ("-h".equals(opt)) {
15233                pw.println("Package manager dump options:");
15234                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15235                pw.println("    --checkin: dump for a checkin");
15236                pw.println("    -f: print details of intent filters");
15237                pw.println("    -h: print this help");
15238                pw.println("  cmd may be one of:");
15239                pw.println("    l[ibraries]: list known shared libraries");
15240                pw.println("    f[eatures]: list device features");
15241                pw.println("    k[eysets]: print known keysets");
15242                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15243                pw.println("    perm[issions]: dump permissions");
15244                pw.println("    permission [name ...]: dump declaration and use of given permission");
15245                pw.println("    pref[erred]: print preferred package settings");
15246                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15247                pw.println("    prov[iders]: dump content providers");
15248                pw.println("    p[ackages]: dump installed packages");
15249                pw.println("    s[hared-users]: dump shared user IDs");
15250                pw.println("    m[essages]: print collected runtime messages");
15251                pw.println("    v[erifiers]: print package verifier info");
15252                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15253                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15254                pw.println("    version: print database version info");
15255                pw.println("    write: write current settings now");
15256                pw.println("    installs: details about install sessions");
15257                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15258                pw.println("    <package.name>: info about given package");
15259                return;
15260            } else if ("--checkin".equals(opt)) {
15261                checkin = true;
15262            } else if ("-f".equals(opt)) {
15263                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15264            } else {
15265                pw.println("Unknown argument: " + opt + "; use -h for help");
15266            }
15267        }
15268
15269        // Is the caller requesting to dump a particular piece of data?
15270        if (opti < args.length) {
15271            String cmd = args[opti];
15272            opti++;
15273            // Is this a package name?
15274            if ("android".equals(cmd) || cmd.contains(".")) {
15275                packageName = cmd;
15276                // When dumping a single package, we always dump all of its
15277                // filter information since the amount of data will be reasonable.
15278                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15279            } else if ("check-permission".equals(cmd)) {
15280                if (opti >= args.length) {
15281                    pw.println("Error: check-permission missing permission argument");
15282                    return;
15283                }
15284                String perm = args[opti];
15285                opti++;
15286                if (opti >= args.length) {
15287                    pw.println("Error: check-permission missing package argument");
15288                    return;
15289                }
15290                String pkg = args[opti];
15291                opti++;
15292                int user = UserHandle.getUserId(Binder.getCallingUid());
15293                if (opti < args.length) {
15294                    try {
15295                        user = Integer.parseInt(args[opti]);
15296                    } catch (NumberFormatException e) {
15297                        pw.println("Error: check-permission user argument is not a number: "
15298                                + args[opti]);
15299                        return;
15300                    }
15301                }
15302                pw.println(checkPermission(perm, pkg, user));
15303                return;
15304            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15305                dumpState.setDump(DumpState.DUMP_LIBS);
15306            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15307                dumpState.setDump(DumpState.DUMP_FEATURES);
15308            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15309                if (opti >= args.length) {
15310                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15311                            | DumpState.DUMP_SERVICE_RESOLVERS
15312                            | DumpState.DUMP_RECEIVER_RESOLVERS
15313                            | DumpState.DUMP_CONTENT_RESOLVERS);
15314                } else {
15315                    while (opti < args.length) {
15316                        String name = args[opti];
15317                        if ("a".equals(name) || "activity".equals(name)) {
15318                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15319                        } else if ("s".equals(name) || "service".equals(name)) {
15320                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15321                        } else if ("r".equals(name) || "receiver".equals(name)) {
15322                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15323                        } else if ("c".equals(name) || "content".equals(name)) {
15324                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15325                        } else {
15326                            pw.println("Error: unknown resolver table type: " + name);
15327                            return;
15328                        }
15329                        opti++;
15330                    }
15331                }
15332            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15333                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15334            } else if ("permission".equals(cmd)) {
15335                if (opti >= args.length) {
15336                    pw.println("Error: permission requires permission name");
15337                    return;
15338                }
15339                permissionNames = new ArraySet<>();
15340                while (opti < args.length) {
15341                    permissionNames.add(args[opti]);
15342                    opti++;
15343                }
15344                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15345                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15346            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15347                dumpState.setDump(DumpState.DUMP_PREFERRED);
15348            } else if ("preferred-xml".equals(cmd)) {
15349                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15350                if (opti < args.length && "--full".equals(args[opti])) {
15351                    fullPreferred = true;
15352                    opti++;
15353                }
15354            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15355                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15356            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15357                dumpState.setDump(DumpState.DUMP_PACKAGES);
15358            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15359                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15360            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15361                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15362            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15363                dumpState.setDump(DumpState.DUMP_MESSAGES);
15364            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15365                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15366            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15367                    || "intent-filter-verifiers".equals(cmd)) {
15368                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15369            } else if ("version".equals(cmd)) {
15370                dumpState.setDump(DumpState.DUMP_VERSION);
15371            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15372                dumpState.setDump(DumpState.DUMP_KEYSETS);
15373            } else if ("installs".equals(cmd)) {
15374                dumpState.setDump(DumpState.DUMP_INSTALLS);
15375            } else if ("write".equals(cmd)) {
15376                synchronized (mPackages) {
15377                    mSettings.writeLPr();
15378                    pw.println("Settings written.");
15379                    return;
15380                }
15381            }
15382        }
15383
15384        if (checkin) {
15385            pw.println("vers,1");
15386        }
15387
15388        // reader
15389        synchronized (mPackages) {
15390            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15391                if (!checkin) {
15392                    if (dumpState.onTitlePrinted())
15393                        pw.println();
15394                    pw.println("Database versions:");
15395                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15396                }
15397            }
15398
15399            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15400                if (!checkin) {
15401                    if (dumpState.onTitlePrinted())
15402                        pw.println();
15403                    pw.println("Verifiers:");
15404                    pw.print("  Required: ");
15405                    pw.print(mRequiredVerifierPackage);
15406                    pw.print(" (uid=");
15407                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15408                    pw.println(")");
15409                } else if (mRequiredVerifierPackage != null) {
15410                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15411                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15412                }
15413            }
15414
15415            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15416                    packageName == null) {
15417                if (mIntentFilterVerifierComponent != null) {
15418                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15419                    if (!checkin) {
15420                        if (dumpState.onTitlePrinted())
15421                            pw.println();
15422                        pw.println("Intent Filter Verifier:");
15423                        pw.print("  Using: ");
15424                        pw.print(verifierPackageName);
15425                        pw.print(" (uid=");
15426                        pw.print(getPackageUid(verifierPackageName, 0));
15427                        pw.println(")");
15428                    } else if (verifierPackageName != null) {
15429                        pw.print("ifv,"); pw.print(verifierPackageName);
15430                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15431                    }
15432                } else {
15433                    pw.println();
15434                    pw.println("No Intent Filter Verifier available!");
15435                }
15436            }
15437
15438            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15439                boolean printedHeader = false;
15440                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15441                while (it.hasNext()) {
15442                    String name = it.next();
15443                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15444                    if (!checkin) {
15445                        if (!printedHeader) {
15446                            if (dumpState.onTitlePrinted())
15447                                pw.println();
15448                            pw.println("Libraries:");
15449                            printedHeader = true;
15450                        }
15451                        pw.print("  ");
15452                    } else {
15453                        pw.print("lib,");
15454                    }
15455                    pw.print(name);
15456                    if (!checkin) {
15457                        pw.print(" -> ");
15458                    }
15459                    if (ent.path != null) {
15460                        if (!checkin) {
15461                            pw.print("(jar) ");
15462                            pw.print(ent.path);
15463                        } else {
15464                            pw.print(",jar,");
15465                            pw.print(ent.path);
15466                        }
15467                    } else {
15468                        if (!checkin) {
15469                            pw.print("(apk) ");
15470                            pw.print(ent.apk);
15471                        } else {
15472                            pw.print(",apk,");
15473                            pw.print(ent.apk);
15474                        }
15475                    }
15476                    pw.println();
15477                }
15478            }
15479
15480            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15481                if (dumpState.onTitlePrinted())
15482                    pw.println();
15483                if (!checkin) {
15484                    pw.println("Features:");
15485                }
15486                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15487                while (it.hasNext()) {
15488                    String name = it.next();
15489                    if (!checkin) {
15490                        pw.print("  ");
15491                    } else {
15492                        pw.print("feat,");
15493                    }
15494                    pw.println(name);
15495                }
15496            }
15497
15498            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15499                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15500                        : "Activity Resolver Table:", "  ", packageName,
15501                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15502                    dumpState.setTitlePrinted(true);
15503                }
15504            }
15505            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15506                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15507                        : "Receiver Resolver Table:", "  ", packageName,
15508                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15509                    dumpState.setTitlePrinted(true);
15510                }
15511            }
15512            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15513                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15514                        : "Service Resolver Table:", "  ", packageName,
15515                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15516                    dumpState.setTitlePrinted(true);
15517                }
15518            }
15519            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15520                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15521                        : "Provider Resolver Table:", "  ", packageName,
15522                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15523                    dumpState.setTitlePrinted(true);
15524                }
15525            }
15526
15527            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15528                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15529                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15530                    int user = mSettings.mPreferredActivities.keyAt(i);
15531                    if (pir.dump(pw,
15532                            dumpState.getTitlePrinted()
15533                                ? "\nPreferred Activities User " + user + ":"
15534                                : "Preferred Activities User " + user + ":", "  ",
15535                            packageName, true, false)) {
15536                        dumpState.setTitlePrinted(true);
15537                    }
15538                }
15539            }
15540
15541            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15542                pw.flush();
15543                FileOutputStream fout = new FileOutputStream(fd);
15544                BufferedOutputStream str = new BufferedOutputStream(fout);
15545                XmlSerializer serializer = new FastXmlSerializer();
15546                try {
15547                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15548                    serializer.startDocument(null, true);
15549                    serializer.setFeature(
15550                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15551                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15552                    serializer.endDocument();
15553                    serializer.flush();
15554                } catch (IllegalArgumentException e) {
15555                    pw.println("Failed writing: " + e);
15556                } catch (IllegalStateException e) {
15557                    pw.println("Failed writing: " + e);
15558                } catch (IOException e) {
15559                    pw.println("Failed writing: " + e);
15560                }
15561            }
15562
15563            if (!checkin
15564                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15565                    && packageName == null) {
15566                pw.println();
15567                int count = mSettings.mPackages.size();
15568                if (count == 0) {
15569                    pw.println("No applications!");
15570                    pw.println();
15571                } else {
15572                    final String prefix = "  ";
15573                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15574                    if (allPackageSettings.size() == 0) {
15575                        pw.println("No domain preferred apps!");
15576                        pw.println();
15577                    } else {
15578                        pw.println("App verification status:");
15579                        pw.println();
15580                        count = 0;
15581                        for (PackageSetting ps : allPackageSettings) {
15582                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15583                            if (ivi == null || ivi.getPackageName() == null) continue;
15584                            pw.println(prefix + "Package: " + ivi.getPackageName());
15585                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15586                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15587                            pw.println();
15588                            count++;
15589                        }
15590                        if (count == 0) {
15591                            pw.println(prefix + "No app verification established.");
15592                            pw.println();
15593                        }
15594                        for (int userId : sUserManager.getUserIds()) {
15595                            pw.println("App linkages for user " + userId + ":");
15596                            pw.println();
15597                            count = 0;
15598                            for (PackageSetting ps : allPackageSettings) {
15599                                final long status = ps.getDomainVerificationStatusForUser(userId);
15600                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15601                                    continue;
15602                                }
15603                                pw.println(prefix + "Package: " + ps.name);
15604                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15605                                String statusStr = IntentFilterVerificationInfo.
15606                                        getStatusStringFromValue(status);
15607                                pw.println(prefix + "Status:  " + statusStr);
15608                                pw.println();
15609                                count++;
15610                            }
15611                            if (count == 0) {
15612                                pw.println(prefix + "No configured app linkages.");
15613                                pw.println();
15614                            }
15615                        }
15616                    }
15617                }
15618            }
15619
15620            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15621                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15622                if (packageName == null && permissionNames == null) {
15623                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15624                        if (iperm == 0) {
15625                            if (dumpState.onTitlePrinted())
15626                                pw.println();
15627                            pw.println("AppOp Permissions:");
15628                        }
15629                        pw.print("  AppOp Permission ");
15630                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15631                        pw.println(":");
15632                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15633                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15634                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15635                        }
15636                    }
15637                }
15638            }
15639
15640            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15641                boolean printedSomething = false;
15642                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15643                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15644                        continue;
15645                    }
15646                    if (!printedSomething) {
15647                        if (dumpState.onTitlePrinted())
15648                            pw.println();
15649                        pw.println("Registered ContentProviders:");
15650                        printedSomething = true;
15651                    }
15652                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15653                    pw.print("    "); pw.println(p.toString());
15654                }
15655                printedSomething = false;
15656                for (Map.Entry<String, PackageParser.Provider> entry :
15657                        mProvidersByAuthority.entrySet()) {
15658                    PackageParser.Provider p = entry.getValue();
15659                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15660                        continue;
15661                    }
15662                    if (!printedSomething) {
15663                        if (dumpState.onTitlePrinted())
15664                            pw.println();
15665                        pw.println("ContentProvider Authorities:");
15666                        printedSomething = true;
15667                    }
15668                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15669                    pw.print("    "); pw.println(p.toString());
15670                    if (p.info != null && p.info.applicationInfo != null) {
15671                        final String appInfo = p.info.applicationInfo.toString();
15672                        pw.print("      applicationInfo="); pw.println(appInfo);
15673                    }
15674                }
15675            }
15676
15677            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15678                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15679            }
15680
15681            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15682                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15683            }
15684
15685            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15686                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15687            }
15688
15689            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15690                // XXX should handle packageName != null by dumping only install data that
15691                // the given package is involved with.
15692                if (dumpState.onTitlePrinted()) pw.println();
15693                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15694            }
15695
15696            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15697                if (dumpState.onTitlePrinted()) pw.println();
15698                mSettings.dumpReadMessagesLPr(pw, dumpState);
15699
15700                pw.println();
15701                pw.println("Package warning messages:");
15702                BufferedReader in = null;
15703                String line = null;
15704                try {
15705                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15706                    while ((line = in.readLine()) != null) {
15707                        if (line.contains("ignored: updated version")) continue;
15708                        pw.println(line);
15709                    }
15710                } catch (IOException ignored) {
15711                } finally {
15712                    IoUtils.closeQuietly(in);
15713                }
15714            }
15715
15716            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15717                BufferedReader in = null;
15718                String line = null;
15719                try {
15720                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15721                    while ((line = in.readLine()) != null) {
15722                        if (line.contains("ignored: updated version")) continue;
15723                        pw.print("msg,");
15724                        pw.println(line);
15725                    }
15726                } catch (IOException ignored) {
15727                } finally {
15728                    IoUtils.closeQuietly(in);
15729                }
15730            }
15731        }
15732    }
15733
15734    private String dumpDomainString(String packageName) {
15735        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15736        List<IntentFilter> filters = getAllIntentFilters(packageName);
15737
15738        ArraySet<String> result = new ArraySet<>();
15739        if (iviList.size() > 0) {
15740            for (IntentFilterVerificationInfo ivi : iviList) {
15741                for (String host : ivi.getDomains()) {
15742                    result.add(host);
15743                }
15744            }
15745        }
15746        if (filters != null && filters.size() > 0) {
15747            for (IntentFilter filter : filters) {
15748                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15749                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15750                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15751                    result.addAll(filter.getHostsList());
15752                }
15753            }
15754        }
15755
15756        StringBuilder sb = new StringBuilder(result.size() * 16);
15757        for (String domain : result) {
15758            if (sb.length() > 0) sb.append(" ");
15759            sb.append(domain);
15760        }
15761        return sb.toString();
15762    }
15763
15764    // ------- apps on sdcard specific code -------
15765    static final boolean DEBUG_SD_INSTALL = false;
15766
15767    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15768
15769    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15770
15771    private boolean mMediaMounted = false;
15772
15773    static String getEncryptKey() {
15774        try {
15775            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15776                    SD_ENCRYPTION_KEYSTORE_NAME);
15777            if (sdEncKey == null) {
15778                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15779                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15780                if (sdEncKey == null) {
15781                    Slog.e(TAG, "Failed to create encryption keys");
15782                    return null;
15783                }
15784            }
15785            return sdEncKey;
15786        } catch (NoSuchAlgorithmException nsae) {
15787            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15788            return null;
15789        } catch (IOException ioe) {
15790            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15791            return null;
15792        }
15793    }
15794
15795    /*
15796     * Update media status on PackageManager.
15797     */
15798    @Override
15799    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15800        int callingUid = Binder.getCallingUid();
15801        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15802            throw new SecurityException("Media status can only be updated by the system");
15803        }
15804        // reader; this apparently protects mMediaMounted, but should probably
15805        // be a different lock in that case.
15806        synchronized (mPackages) {
15807            Log.i(TAG, "Updating external media status from "
15808                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15809                    + (mediaStatus ? "mounted" : "unmounted"));
15810            if (DEBUG_SD_INSTALL)
15811                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15812                        + ", mMediaMounted=" + mMediaMounted);
15813            if (mediaStatus == mMediaMounted) {
15814                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15815                        : 0, -1);
15816                mHandler.sendMessage(msg);
15817                return;
15818            }
15819            mMediaMounted = mediaStatus;
15820        }
15821        // Queue up an async operation since the package installation may take a
15822        // little while.
15823        mHandler.post(new Runnable() {
15824            public void run() {
15825                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15826            }
15827        });
15828    }
15829
15830    /**
15831     * Called by MountService when the initial ASECs to scan are available.
15832     * Should block until all the ASEC containers are finished being scanned.
15833     */
15834    public void scanAvailableAsecs() {
15835        updateExternalMediaStatusInner(true, false, false);
15836        if (mShouldRestoreconData) {
15837            SELinuxMMAC.setRestoreconDone();
15838            mShouldRestoreconData = false;
15839        }
15840    }
15841
15842    /*
15843     * Collect information of applications on external media, map them against
15844     * existing containers and update information based on current mount status.
15845     * Please note that we always have to report status if reportStatus has been
15846     * set to true especially when unloading packages.
15847     */
15848    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15849            boolean externalStorage) {
15850        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15851        int[] uidArr = EmptyArray.INT;
15852
15853        final String[] list = PackageHelper.getSecureContainerList();
15854        if (ArrayUtils.isEmpty(list)) {
15855            Log.i(TAG, "No secure containers found");
15856        } else {
15857            // Process list of secure containers and categorize them
15858            // as active or stale based on their package internal state.
15859
15860            // reader
15861            synchronized (mPackages) {
15862                for (String cid : list) {
15863                    // Leave stages untouched for now; installer service owns them
15864                    if (PackageInstallerService.isStageName(cid)) continue;
15865
15866                    if (DEBUG_SD_INSTALL)
15867                        Log.i(TAG, "Processing container " + cid);
15868                    String pkgName = getAsecPackageName(cid);
15869                    if (pkgName == null) {
15870                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15871                        continue;
15872                    }
15873                    if (DEBUG_SD_INSTALL)
15874                        Log.i(TAG, "Looking for pkg : " + pkgName);
15875
15876                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15877                    if (ps == null) {
15878                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15879                        continue;
15880                    }
15881
15882                    /*
15883                     * Skip packages that are not external if we're unmounting
15884                     * external storage.
15885                     */
15886                    if (externalStorage && !isMounted && !isExternal(ps)) {
15887                        continue;
15888                    }
15889
15890                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15891                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15892                    // The package status is changed only if the code path
15893                    // matches between settings and the container id.
15894                    if (ps.codePathString != null
15895                            && ps.codePathString.startsWith(args.getCodePath())) {
15896                        if (DEBUG_SD_INSTALL) {
15897                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15898                                    + " at code path: " + ps.codePathString);
15899                        }
15900
15901                        // We do have a valid package installed on sdcard
15902                        processCids.put(args, ps.codePathString);
15903                        final int uid = ps.appId;
15904                        if (uid != -1) {
15905                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15906                        }
15907                    } else {
15908                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15909                                + ps.codePathString);
15910                    }
15911                }
15912            }
15913
15914            Arrays.sort(uidArr);
15915        }
15916
15917        // Process packages with valid entries.
15918        if (isMounted) {
15919            if (DEBUG_SD_INSTALL)
15920                Log.i(TAG, "Loading packages");
15921            loadMediaPackages(processCids, uidArr, externalStorage);
15922            startCleaningPackages();
15923            mInstallerService.onSecureContainersAvailable();
15924        } else {
15925            if (DEBUG_SD_INSTALL)
15926                Log.i(TAG, "Unloading packages");
15927            unloadMediaPackages(processCids, uidArr, reportStatus);
15928        }
15929    }
15930
15931    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15932            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15933        final int size = infos.size();
15934        final String[] packageNames = new String[size];
15935        final int[] packageUids = new int[size];
15936        for (int i = 0; i < size; i++) {
15937            final ApplicationInfo info = infos.get(i);
15938            packageNames[i] = info.packageName;
15939            packageUids[i] = info.uid;
15940        }
15941        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15942                finishedReceiver);
15943    }
15944
15945    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15946            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15947        sendResourcesChangedBroadcast(mediaStatus, replacing,
15948                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15949    }
15950
15951    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15952            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15953        int size = pkgList.length;
15954        if (size > 0) {
15955            // Send broadcasts here
15956            Bundle extras = new Bundle();
15957            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15958            if (uidArr != null) {
15959                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15960            }
15961            if (replacing) {
15962                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15963            }
15964            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15965                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15966            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
15967        }
15968    }
15969
15970   /*
15971     * Look at potentially valid container ids from processCids If package
15972     * information doesn't match the one on record or package scanning fails,
15973     * the cid is added to list of removeCids. We currently don't delete stale
15974     * containers.
15975     */
15976    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15977            boolean externalStorage) {
15978        ArrayList<String> pkgList = new ArrayList<String>();
15979        Set<AsecInstallArgs> keys = processCids.keySet();
15980
15981        for (AsecInstallArgs args : keys) {
15982            String codePath = processCids.get(args);
15983            if (DEBUG_SD_INSTALL)
15984                Log.i(TAG, "Loading container : " + args.cid);
15985            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15986            try {
15987                // Make sure there are no container errors first.
15988                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15989                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15990                            + " when installing from sdcard");
15991                    continue;
15992                }
15993                // Check code path here.
15994                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15995                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15996                            + " does not match one in settings " + codePath);
15997                    continue;
15998                }
15999                // Parse package
16000                int parseFlags = mDefParseFlags;
16001                if (args.isExternalAsec()) {
16002                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16003                }
16004                if (args.isFwdLocked()) {
16005                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16006                }
16007
16008                synchronized (mInstallLock) {
16009                    PackageParser.Package pkg = null;
16010                    try {
16011                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16012                    } catch (PackageManagerException e) {
16013                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16014                    }
16015                    // Scan the package
16016                    if (pkg != null) {
16017                        /*
16018                         * TODO why is the lock being held? doPostInstall is
16019                         * called in other places without the lock. This needs
16020                         * to be straightened out.
16021                         */
16022                        // writer
16023                        synchronized (mPackages) {
16024                            retCode = PackageManager.INSTALL_SUCCEEDED;
16025                            pkgList.add(pkg.packageName);
16026                            // Post process args
16027                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16028                                    pkg.applicationInfo.uid);
16029                        }
16030                    } else {
16031                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16032                    }
16033                }
16034
16035            } finally {
16036                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16037                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16038                }
16039            }
16040        }
16041        // writer
16042        synchronized (mPackages) {
16043            // If the platform SDK has changed since the last time we booted,
16044            // we need to re-grant app permission to catch any new ones that
16045            // appear. This is really a hack, and means that apps can in some
16046            // cases get permissions that the user didn't initially explicitly
16047            // allow... it would be nice to have some better way to handle
16048            // this situation.
16049            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16050                    : mSettings.getInternalVersion();
16051            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16052                    : StorageManager.UUID_PRIVATE_INTERNAL;
16053
16054            int updateFlags = UPDATE_PERMISSIONS_ALL;
16055            if (ver.sdkVersion != mSdkVersion) {
16056                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16057                        + mSdkVersion + "; regranting permissions for external");
16058                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16059            }
16060            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16061
16062            // Yay, everything is now upgraded
16063            ver.forceCurrent();
16064
16065            // can downgrade to reader
16066            // Persist settings
16067            mSettings.writeLPr();
16068        }
16069        // Send a broadcast to let everyone know we are done processing
16070        if (pkgList.size() > 0) {
16071            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16072        }
16073    }
16074
16075   /*
16076     * Utility method to unload a list of specified containers
16077     */
16078    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16079        // Just unmount all valid containers.
16080        for (AsecInstallArgs arg : cidArgs) {
16081            synchronized (mInstallLock) {
16082                arg.doPostDeleteLI(false);
16083           }
16084       }
16085   }
16086
16087    /*
16088     * Unload packages mounted on external media. This involves deleting package
16089     * data from internal structures, sending broadcasts about diabled packages,
16090     * gc'ing to free up references, unmounting all secure containers
16091     * corresponding to packages on external media, and posting a
16092     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16093     * that we always have to post this message if status has been requested no
16094     * matter what.
16095     */
16096    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16097            final boolean reportStatus) {
16098        if (DEBUG_SD_INSTALL)
16099            Log.i(TAG, "unloading media packages");
16100        ArrayList<String> pkgList = new ArrayList<String>();
16101        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16102        final Set<AsecInstallArgs> keys = processCids.keySet();
16103        for (AsecInstallArgs args : keys) {
16104            String pkgName = args.getPackageName();
16105            if (DEBUG_SD_INSTALL)
16106                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16107            // Delete package internally
16108            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16109            synchronized (mInstallLock) {
16110                boolean res = deletePackageLI(pkgName, null, false, null, null,
16111                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16112                if (res) {
16113                    pkgList.add(pkgName);
16114                } else {
16115                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16116                    failedList.add(args);
16117                }
16118            }
16119        }
16120
16121        // reader
16122        synchronized (mPackages) {
16123            // We didn't update the settings after removing each package;
16124            // write them now for all packages.
16125            mSettings.writeLPr();
16126        }
16127
16128        // We have to absolutely send UPDATED_MEDIA_STATUS only
16129        // after confirming that all the receivers processed the ordered
16130        // broadcast when packages get disabled, force a gc to clean things up.
16131        // and unload all the containers.
16132        if (pkgList.size() > 0) {
16133            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16134                    new IIntentReceiver.Stub() {
16135                public void performReceive(Intent intent, int resultCode, String data,
16136                        Bundle extras, boolean ordered, boolean sticky,
16137                        int sendingUser) throws RemoteException {
16138                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16139                            reportStatus ? 1 : 0, 1, keys);
16140                    mHandler.sendMessage(msg);
16141                }
16142            });
16143        } else {
16144            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16145                    keys);
16146            mHandler.sendMessage(msg);
16147        }
16148    }
16149
16150    private void loadPrivatePackages(final VolumeInfo vol) {
16151        mHandler.post(new Runnable() {
16152            @Override
16153            public void run() {
16154                loadPrivatePackagesInner(vol);
16155            }
16156        });
16157    }
16158
16159    private void loadPrivatePackagesInner(VolumeInfo vol) {
16160        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16161        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16162
16163        final VersionInfo ver;
16164        final List<PackageSetting> packages;
16165        synchronized (mPackages) {
16166            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16167            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16168        }
16169
16170        for (PackageSetting ps : packages) {
16171            synchronized (mInstallLock) {
16172                final PackageParser.Package pkg;
16173                try {
16174                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16175                    loaded.add(pkg.applicationInfo);
16176                } catch (PackageManagerException e) {
16177                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16178                }
16179
16180                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16181                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16182                }
16183            }
16184        }
16185
16186        synchronized (mPackages) {
16187            int updateFlags = UPDATE_PERMISSIONS_ALL;
16188            if (ver.sdkVersion != mSdkVersion) {
16189                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16190                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16191                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16192            }
16193            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16194
16195            // Yay, everything is now upgraded
16196            ver.forceCurrent();
16197
16198            mSettings.writeLPr();
16199        }
16200
16201        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16202        sendResourcesChangedBroadcast(true, false, loaded, null);
16203    }
16204
16205    private void unloadPrivatePackages(final VolumeInfo vol) {
16206        mHandler.post(new Runnable() {
16207            @Override
16208            public void run() {
16209                unloadPrivatePackagesInner(vol);
16210            }
16211        });
16212    }
16213
16214    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16215        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16216        synchronized (mInstallLock) {
16217        synchronized (mPackages) {
16218            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16219            for (PackageSetting ps : packages) {
16220                if (ps.pkg == null) continue;
16221
16222                final ApplicationInfo info = ps.pkg.applicationInfo;
16223                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16224                if (deletePackageLI(ps.name, null, false, null, null,
16225                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16226                    unloaded.add(info);
16227                } else {
16228                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16229                }
16230            }
16231
16232            mSettings.writeLPr();
16233        }
16234        }
16235
16236        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16237        sendResourcesChangedBroadcast(false, false, unloaded, null);
16238    }
16239
16240    /**
16241     * Examine all users present on given mounted volume, and destroy data
16242     * belonging to users that are no longer valid, or whose user ID has been
16243     * recycled.
16244     */
16245    private void reconcileUsers(String volumeUuid) {
16246        final File[] files = FileUtils
16247                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16248        for (File file : files) {
16249            if (!file.isDirectory()) continue;
16250
16251            final int userId;
16252            final UserInfo info;
16253            try {
16254                userId = Integer.parseInt(file.getName());
16255                info = sUserManager.getUserInfo(userId);
16256            } catch (NumberFormatException e) {
16257                Slog.w(TAG, "Invalid user directory " + file);
16258                continue;
16259            }
16260
16261            boolean destroyUser = false;
16262            if (info == null) {
16263                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16264                        + " because no matching user was found");
16265                destroyUser = true;
16266            } else {
16267                try {
16268                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16269                } catch (IOException e) {
16270                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16271                            + " because we failed to enforce serial number: " + e);
16272                    destroyUser = true;
16273                }
16274            }
16275
16276            if (destroyUser) {
16277                synchronized (mInstallLock) {
16278                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16279                }
16280            }
16281        }
16282
16283        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16284        final UserManager um = mContext.getSystemService(UserManager.class);
16285        for (UserInfo user : um.getUsers()) {
16286            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16287            if (userDir.exists()) continue;
16288
16289            try {
16290                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
16291                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16292            } catch (IOException e) {
16293                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16294            }
16295        }
16296    }
16297
16298    /**
16299     * Examine all apps present on given mounted volume, and destroy apps that
16300     * aren't expected, either due to uninstallation or reinstallation on
16301     * another volume.
16302     */
16303    private void reconcileApps(String volumeUuid) {
16304        final File[] files = FileUtils
16305                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16306        for (File file : files) {
16307            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16308                    && !PackageInstallerService.isStageName(file.getName());
16309            if (!isPackage) {
16310                // Ignore entries which are not packages
16311                continue;
16312            }
16313
16314            boolean destroyApp = false;
16315            String packageName = null;
16316            try {
16317                final PackageLite pkg = PackageParser.parsePackageLite(file,
16318                        PackageParser.PARSE_MUST_BE_APK);
16319                packageName = pkg.packageName;
16320
16321                synchronized (mPackages) {
16322                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16323                    if (ps == null) {
16324                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16325                                + volumeUuid + " because we found no install record");
16326                        destroyApp = true;
16327                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16328                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16329                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16330                        destroyApp = true;
16331                    }
16332                }
16333
16334            } catch (PackageParserException e) {
16335                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16336                destroyApp = true;
16337            }
16338
16339            if (destroyApp) {
16340                synchronized (mInstallLock) {
16341                    if (packageName != null) {
16342                        removeDataDirsLI(volumeUuid, packageName);
16343                    }
16344                    if (file.isDirectory()) {
16345                        mInstaller.rmPackageDir(file.getAbsolutePath());
16346                    } else {
16347                        file.delete();
16348                    }
16349                }
16350            }
16351        }
16352    }
16353
16354    private void unfreezePackage(String packageName) {
16355        synchronized (mPackages) {
16356            final PackageSetting ps = mSettings.mPackages.get(packageName);
16357            if (ps != null) {
16358                ps.frozen = false;
16359            }
16360        }
16361    }
16362
16363    @Override
16364    public int movePackage(final String packageName, final String volumeUuid) {
16365        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16366
16367        final int moveId = mNextMoveId.getAndIncrement();
16368        mHandler.post(new Runnable() {
16369            @Override
16370            public void run() {
16371                try {
16372                    movePackageInternal(packageName, volumeUuid, moveId);
16373                } catch (PackageManagerException e) {
16374                    Slog.w(TAG, "Failed to move " + packageName, e);
16375                    mMoveCallbacks.notifyStatusChanged(moveId,
16376                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16377                }
16378            }
16379        });
16380        return moveId;
16381    }
16382
16383    private void movePackageInternal(final String packageName, final String volumeUuid,
16384            final int moveId) throws PackageManagerException {
16385        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16386        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16387        final PackageManager pm = mContext.getPackageManager();
16388
16389        final boolean currentAsec;
16390        final String currentVolumeUuid;
16391        final File codeFile;
16392        final String installerPackageName;
16393        final String packageAbiOverride;
16394        final int appId;
16395        final String seinfo;
16396        final String label;
16397
16398        // reader
16399        synchronized (mPackages) {
16400            final PackageParser.Package pkg = mPackages.get(packageName);
16401            final PackageSetting ps = mSettings.mPackages.get(packageName);
16402            if (pkg == null || ps == null) {
16403                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16404            }
16405
16406            if (pkg.applicationInfo.isSystemApp()) {
16407                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16408                        "Cannot move system application");
16409            }
16410
16411            if (pkg.applicationInfo.isExternalAsec()) {
16412                currentAsec = true;
16413                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16414            } else if (pkg.applicationInfo.isForwardLocked()) {
16415                currentAsec = true;
16416                currentVolumeUuid = "forward_locked";
16417            } else {
16418                currentAsec = false;
16419                currentVolumeUuid = ps.volumeUuid;
16420
16421                final File probe = new File(pkg.codePath);
16422                final File probeOat = new File(probe, "oat");
16423                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16424                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16425                            "Move only supported for modern cluster style installs");
16426                }
16427            }
16428
16429            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16430                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16431                        "Package already moved to " + volumeUuid);
16432            }
16433
16434            if (ps.frozen) {
16435                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16436                        "Failed to move already frozen package");
16437            }
16438            ps.frozen = true;
16439
16440            codeFile = new File(pkg.codePath);
16441            installerPackageName = ps.installerPackageName;
16442            packageAbiOverride = ps.cpuAbiOverrideString;
16443            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16444            seinfo = pkg.applicationInfo.seinfo;
16445            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16446        }
16447
16448        // Now that we're guarded by frozen state, kill app during move
16449        final long token = Binder.clearCallingIdentity();
16450        try {
16451            killApplication(packageName, appId, "move pkg");
16452        } finally {
16453            Binder.restoreCallingIdentity(token);
16454        }
16455
16456        final Bundle extras = new Bundle();
16457        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16458        extras.putString(Intent.EXTRA_TITLE, label);
16459        mMoveCallbacks.notifyCreated(moveId, extras);
16460
16461        int installFlags;
16462        final boolean moveCompleteApp;
16463        final File measurePath;
16464
16465        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16466            installFlags = INSTALL_INTERNAL;
16467            moveCompleteApp = !currentAsec;
16468            measurePath = Environment.getDataAppDirectory(volumeUuid);
16469        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16470            installFlags = INSTALL_EXTERNAL;
16471            moveCompleteApp = false;
16472            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16473        } else {
16474            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16475            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16476                    || !volume.isMountedWritable()) {
16477                unfreezePackage(packageName);
16478                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16479                        "Move location not mounted private volume");
16480            }
16481
16482            Preconditions.checkState(!currentAsec);
16483
16484            installFlags = INSTALL_INTERNAL;
16485            moveCompleteApp = true;
16486            measurePath = Environment.getDataAppDirectory(volumeUuid);
16487        }
16488
16489        final PackageStats stats = new PackageStats(null, -1);
16490        synchronized (mInstaller) {
16491            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16492                unfreezePackage(packageName);
16493                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16494                        "Failed to measure package size");
16495            }
16496        }
16497
16498        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16499                + stats.dataSize);
16500
16501        final long startFreeBytes = measurePath.getFreeSpace();
16502        final long sizeBytes;
16503        if (moveCompleteApp) {
16504            sizeBytes = stats.codeSize + stats.dataSize;
16505        } else {
16506            sizeBytes = stats.codeSize;
16507        }
16508
16509        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16510            unfreezePackage(packageName);
16511            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16512                    "Not enough free space to move");
16513        }
16514
16515        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16516
16517        final CountDownLatch installedLatch = new CountDownLatch(1);
16518        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16519            @Override
16520            public void onUserActionRequired(Intent intent) throws RemoteException {
16521                throw new IllegalStateException();
16522            }
16523
16524            @Override
16525            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16526                    Bundle extras) throws RemoteException {
16527                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16528                        + PackageManager.installStatusToString(returnCode, msg));
16529
16530                installedLatch.countDown();
16531
16532                // Regardless of success or failure of the move operation,
16533                // always unfreeze the package
16534                unfreezePackage(packageName);
16535
16536                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16537                switch (status) {
16538                    case PackageInstaller.STATUS_SUCCESS:
16539                        mMoveCallbacks.notifyStatusChanged(moveId,
16540                                PackageManager.MOVE_SUCCEEDED);
16541                        break;
16542                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16543                        mMoveCallbacks.notifyStatusChanged(moveId,
16544                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16545                        break;
16546                    default:
16547                        mMoveCallbacks.notifyStatusChanged(moveId,
16548                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16549                        break;
16550                }
16551            }
16552        };
16553
16554        final MoveInfo move;
16555        if (moveCompleteApp) {
16556            // Kick off a thread to report progress estimates
16557            new Thread() {
16558                @Override
16559                public void run() {
16560                    while (true) {
16561                        try {
16562                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16563                                break;
16564                            }
16565                        } catch (InterruptedException ignored) {
16566                        }
16567
16568                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16569                        final int progress = 10 + (int) MathUtils.constrain(
16570                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16571                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16572                    }
16573                }
16574            }.start();
16575
16576            final String dataAppName = codeFile.getName();
16577            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16578                    dataAppName, appId, seinfo);
16579        } else {
16580            move = null;
16581        }
16582
16583        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16584
16585        final Message msg = mHandler.obtainMessage(INIT_COPY);
16586        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16587        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16588                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16589        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16590        msg.obj = params;
16591
16592        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16593                System.identityHashCode(msg.obj));
16594        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16595                System.identityHashCode(msg.obj));
16596
16597        mHandler.sendMessage(msg);
16598    }
16599
16600    @Override
16601    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16602        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16603
16604        final int realMoveId = mNextMoveId.getAndIncrement();
16605        final Bundle extras = new Bundle();
16606        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16607        mMoveCallbacks.notifyCreated(realMoveId, extras);
16608
16609        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16610            @Override
16611            public void onCreated(int moveId, Bundle extras) {
16612                // Ignored
16613            }
16614
16615            @Override
16616            public void onStatusChanged(int moveId, int status, long estMillis) {
16617                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16618            }
16619        };
16620
16621        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16622        storage.setPrimaryStorageUuid(volumeUuid, callback);
16623        return realMoveId;
16624    }
16625
16626    @Override
16627    public int getMoveStatus(int moveId) {
16628        mContext.enforceCallingOrSelfPermission(
16629                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16630        return mMoveCallbacks.mLastStatus.get(moveId);
16631    }
16632
16633    @Override
16634    public void registerMoveCallback(IPackageMoveObserver callback) {
16635        mContext.enforceCallingOrSelfPermission(
16636                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16637        mMoveCallbacks.register(callback);
16638    }
16639
16640    @Override
16641    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16642        mContext.enforceCallingOrSelfPermission(
16643                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16644        mMoveCallbacks.unregister(callback);
16645    }
16646
16647    @Override
16648    public boolean setInstallLocation(int loc) {
16649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16650                null);
16651        if (getInstallLocation() == loc) {
16652            return true;
16653        }
16654        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16655                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16656            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16657                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16658            return true;
16659        }
16660        return false;
16661   }
16662
16663    @Override
16664    public int getInstallLocation() {
16665        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16666                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16667                PackageHelper.APP_INSTALL_AUTO);
16668    }
16669
16670    /** Called by UserManagerService */
16671    void cleanUpUser(UserManagerService userManager, int userHandle) {
16672        synchronized (mPackages) {
16673            mDirtyUsers.remove(userHandle);
16674            mUserNeedsBadging.delete(userHandle);
16675            mSettings.removeUserLPw(userHandle);
16676            mPendingBroadcasts.remove(userHandle);
16677        }
16678        synchronized (mInstallLock) {
16679            if (mInstaller != null) {
16680                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16681                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16682                    final String volumeUuid = vol.getFsUuid();
16683                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16684                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16685                }
16686            }
16687            synchronized (mPackages) {
16688                removeUnusedPackagesLILPw(userManager, userHandle);
16689            }
16690        }
16691    }
16692
16693    /**
16694     * We're removing userHandle and would like to remove any downloaded packages
16695     * that are no longer in use by any other user.
16696     * @param userHandle the user being removed
16697     */
16698    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16699        final boolean DEBUG_CLEAN_APKS = false;
16700        int [] users = userManager.getUserIds();
16701        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16702        while (psit.hasNext()) {
16703            PackageSetting ps = psit.next();
16704            if (ps.pkg == null) {
16705                continue;
16706            }
16707            final String packageName = ps.pkg.packageName;
16708            // Skip over if system app
16709            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16710                continue;
16711            }
16712            if (DEBUG_CLEAN_APKS) {
16713                Slog.i(TAG, "Checking package " + packageName);
16714            }
16715            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16716            if (keep) {
16717                if (DEBUG_CLEAN_APKS) {
16718                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16719                }
16720            } else {
16721                for (int i = 0; i < users.length; i++) {
16722                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16723                        keep = true;
16724                        if (DEBUG_CLEAN_APKS) {
16725                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16726                                    + users[i]);
16727                        }
16728                        break;
16729                    }
16730                }
16731            }
16732            if (!keep) {
16733                if (DEBUG_CLEAN_APKS) {
16734                    Slog.i(TAG, "  Removing package " + packageName);
16735                }
16736                mHandler.post(new Runnable() {
16737                    public void run() {
16738                        deletePackageX(packageName, userHandle, 0);
16739                    } //end run
16740                });
16741            }
16742        }
16743    }
16744
16745    /** Called by UserManagerService */
16746    void createNewUser(int userHandle) {
16747        if (mInstaller != null) {
16748            synchronized (mInstallLock) {
16749                synchronized (mPackages) {
16750                    mInstaller.createUserConfig(userHandle);
16751                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16752                }
16753            }
16754            synchronized (mPackages) {
16755                applyFactoryDefaultBrowserLPw(userHandle);
16756                primeDomainVerificationsLPw(userHandle);
16757            }
16758        }
16759    }
16760
16761    void newUserCreated(final int userHandle) {
16762        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16763    }
16764
16765    @Override
16766    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16767        mContext.enforceCallingOrSelfPermission(
16768                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16769                "Only package verification agents can read the verifier device identity");
16770
16771        synchronized (mPackages) {
16772            return mSettings.getVerifierDeviceIdentityLPw();
16773        }
16774    }
16775
16776    @Override
16777    public void setPermissionEnforced(String permission, boolean enforced) {
16778        // TODO: Now that we no longer change GID for storage, this should to away.
16779        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16780                "setPermissionEnforced");
16781        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16782            synchronized (mPackages) {
16783                if (mSettings.mReadExternalStorageEnforced == null
16784                        || mSettings.mReadExternalStorageEnforced != enforced) {
16785                    mSettings.mReadExternalStorageEnforced = enforced;
16786                    mSettings.writeLPr();
16787                }
16788            }
16789            // kill any non-foreground processes so we restart them and
16790            // grant/revoke the GID.
16791            final IActivityManager am = ActivityManagerNative.getDefault();
16792            if (am != null) {
16793                final long token = Binder.clearCallingIdentity();
16794                try {
16795                    am.killProcessesBelowForeground("setPermissionEnforcement");
16796                } catch (RemoteException e) {
16797                } finally {
16798                    Binder.restoreCallingIdentity(token);
16799                }
16800            }
16801        } else {
16802            throw new IllegalArgumentException("No selective enforcement for " + permission);
16803        }
16804    }
16805
16806    @Override
16807    @Deprecated
16808    public boolean isPermissionEnforced(String permission) {
16809        return true;
16810    }
16811
16812    @Override
16813    public boolean isStorageLow() {
16814        final long token = Binder.clearCallingIdentity();
16815        try {
16816            final DeviceStorageMonitorInternal
16817                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16818            if (dsm != null) {
16819                return dsm.isMemoryLow();
16820            } else {
16821                return false;
16822            }
16823        } finally {
16824            Binder.restoreCallingIdentity(token);
16825        }
16826    }
16827
16828    @Override
16829    public IPackageInstaller getPackageInstaller() {
16830        return mInstallerService;
16831    }
16832
16833    private boolean userNeedsBadging(int userId) {
16834        int index = mUserNeedsBadging.indexOfKey(userId);
16835        if (index < 0) {
16836            final UserInfo userInfo;
16837            final long token = Binder.clearCallingIdentity();
16838            try {
16839                userInfo = sUserManager.getUserInfo(userId);
16840            } finally {
16841                Binder.restoreCallingIdentity(token);
16842            }
16843            final boolean b;
16844            if (userInfo != null && userInfo.isManagedProfile()) {
16845                b = true;
16846            } else {
16847                b = false;
16848            }
16849            mUserNeedsBadging.put(userId, b);
16850            return b;
16851        }
16852        return mUserNeedsBadging.valueAt(index);
16853    }
16854
16855    @Override
16856    public KeySet getKeySetByAlias(String packageName, String alias) {
16857        if (packageName == null || alias == null) {
16858            return null;
16859        }
16860        synchronized(mPackages) {
16861            final PackageParser.Package pkg = mPackages.get(packageName);
16862            if (pkg == null) {
16863                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16864                throw new IllegalArgumentException("Unknown package: " + packageName);
16865            }
16866            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16867            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16868        }
16869    }
16870
16871    @Override
16872    public KeySet getSigningKeySet(String packageName) {
16873        if (packageName == null) {
16874            return null;
16875        }
16876        synchronized(mPackages) {
16877            final PackageParser.Package pkg = mPackages.get(packageName);
16878            if (pkg == null) {
16879                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16880                throw new IllegalArgumentException("Unknown package: " + packageName);
16881            }
16882            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16883                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16884                throw new SecurityException("May not access signing KeySet of other apps.");
16885            }
16886            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16887            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16888        }
16889    }
16890
16891    @Override
16892    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16893        if (packageName == null || ks == null) {
16894            return false;
16895        }
16896        synchronized(mPackages) {
16897            final PackageParser.Package pkg = mPackages.get(packageName);
16898            if (pkg == null) {
16899                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16900                throw new IllegalArgumentException("Unknown package: " + packageName);
16901            }
16902            IBinder ksh = ks.getToken();
16903            if (ksh instanceof KeySetHandle) {
16904                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16905                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16906            }
16907            return false;
16908        }
16909    }
16910
16911    @Override
16912    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16913        if (packageName == null || ks == null) {
16914            return false;
16915        }
16916        synchronized(mPackages) {
16917            final PackageParser.Package pkg = mPackages.get(packageName);
16918            if (pkg == null) {
16919                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16920                throw new IllegalArgumentException("Unknown package: " + packageName);
16921            }
16922            IBinder ksh = ks.getToken();
16923            if (ksh instanceof KeySetHandle) {
16924                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16925                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16926            }
16927            return false;
16928        }
16929    }
16930
16931    private void deletePackageIfUnusedLPr(final String packageName) {
16932        PackageSetting ps = mSettings.mPackages.get(packageName);
16933        if (ps == null) {
16934            return;
16935        }
16936        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
16937            // TODO Implement atomic delete if package is unused
16938            // It is currently possible that the package will be deleted even if it is installed
16939            // after this method returns.
16940            mHandler.post(new Runnable() {
16941                public void run() {
16942                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
16943                }
16944            });
16945        }
16946    }
16947
16948    /**
16949     * Check and throw if the given before/after packages would be considered a
16950     * downgrade.
16951     */
16952    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16953            throws PackageManagerException {
16954        if (after.versionCode < before.mVersionCode) {
16955            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16956                    "Update version code " + after.versionCode + " is older than current "
16957                    + before.mVersionCode);
16958        } else if (after.versionCode == before.mVersionCode) {
16959            if (after.baseRevisionCode < before.baseRevisionCode) {
16960                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16961                        "Update base revision code " + after.baseRevisionCode
16962                        + " is older than current " + before.baseRevisionCode);
16963            }
16964
16965            if (!ArrayUtils.isEmpty(after.splitNames)) {
16966                for (int i = 0; i < after.splitNames.length; i++) {
16967                    final String splitName = after.splitNames[i];
16968                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16969                    if (j != -1) {
16970                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16971                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16972                                    "Update split " + splitName + " revision code "
16973                                    + after.splitRevisionCodes[i] + " is older than current "
16974                                    + before.splitRevisionCodes[j]);
16975                        }
16976                    }
16977                }
16978            }
16979        }
16980    }
16981
16982    private static class MoveCallbacks extends Handler {
16983        private static final int MSG_CREATED = 1;
16984        private static final int MSG_STATUS_CHANGED = 2;
16985
16986        private final RemoteCallbackList<IPackageMoveObserver>
16987                mCallbacks = new RemoteCallbackList<>();
16988
16989        private final SparseIntArray mLastStatus = new SparseIntArray();
16990
16991        public MoveCallbacks(Looper looper) {
16992            super(looper);
16993        }
16994
16995        public void register(IPackageMoveObserver callback) {
16996            mCallbacks.register(callback);
16997        }
16998
16999        public void unregister(IPackageMoveObserver callback) {
17000            mCallbacks.unregister(callback);
17001        }
17002
17003        @Override
17004        public void handleMessage(Message msg) {
17005            final SomeArgs args = (SomeArgs) msg.obj;
17006            final int n = mCallbacks.beginBroadcast();
17007            for (int i = 0; i < n; i++) {
17008                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17009                try {
17010                    invokeCallback(callback, msg.what, args);
17011                } catch (RemoteException ignored) {
17012                }
17013            }
17014            mCallbacks.finishBroadcast();
17015            args.recycle();
17016        }
17017
17018        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17019                throws RemoteException {
17020            switch (what) {
17021                case MSG_CREATED: {
17022                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17023                    break;
17024                }
17025                case MSG_STATUS_CHANGED: {
17026                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17027                    break;
17028                }
17029            }
17030        }
17031
17032        private void notifyCreated(int moveId, Bundle extras) {
17033            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17034
17035            final SomeArgs args = SomeArgs.obtain();
17036            args.argi1 = moveId;
17037            args.arg2 = extras;
17038            obtainMessage(MSG_CREATED, args).sendToTarget();
17039        }
17040
17041        private void notifyStatusChanged(int moveId, int status) {
17042            notifyStatusChanged(moveId, status, -1);
17043        }
17044
17045        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17046            Slog.v(TAG, "Move " + moveId + " status " + status);
17047
17048            final SomeArgs args = SomeArgs.obtain();
17049            args.argi1 = moveId;
17050            args.argi2 = status;
17051            args.arg3 = estMillis;
17052            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17053
17054            synchronized (mLastStatus) {
17055                mLastStatus.put(moveId, status);
17056            }
17057        }
17058    }
17059
17060    private final class OnPermissionChangeListeners extends Handler {
17061        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17062
17063        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17064                new RemoteCallbackList<>();
17065
17066        public OnPermissionChangeListeners(Looper looper) {
17067            super(looper);
17068        }
17069
17070        @Override
17071        public void handleMessage(Message msg) {
17072            switch (msg.what) {
17073                case MSG_ON_PERMISSIONS_CHANGED: {
17074                    final int uid = msg.arg1;
17075                    handleOnPermissionsChanged(uid);
17076                } break;
17077            }
17078        }
17079
17080        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17081            mPermissionListeners.register(listener);
17082
17083        }
17084
17085        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17086            mPermissionListeners.unregister(listener);
17087        }
17088
17089        public void onPermissionsChanged(int uid) {
17090            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17091                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17092            }
17093        }
17094
17095        private void handleOnPermissionsChanged(int uid) {
17096            final int count = mPermissionListeners.beginBroadcast();
17097            try {
17098                for (int i = 0; i < count; i++) {
17099                    IOnPermissionsChangeListener callback = mPermissionListeners
17100                            .getBroadcastItem(i);
17101                    try {
17102                        callback.onPermissionsChanged(uid);
17103                    } catch (RemoteException e) {
17104                        Log.e(TAG, "Permission listener is dead", e);
17105                    }
17106                }
17107            } finally {
17108                mPermissionListeners.finishBroadcast();
17109            }
17110        }
17111    }
17112
17113    private class PackageManagerInternalImpl extends PackageManagerInternal {
17114        @Override
17115        public void setLocationPackagesProvider(PackagesProvider provider) {
17116            synchronized (mPackages) {
17117                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17118            }
17119        }
17120
17121        @Override
17122        public void setImePackagesProvider(PackagesProvider provider) {
17123            synchronized (mPackages) {
17124                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17125            }
17126        }
17127
17128        @Override
17129        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17130            synchronized (mPackages) {
17131                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17132            }
17133        }
17134
17135        @Override
17136        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17137            synchronized (mPackages) {
17138                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17139            }
17140        }
17141
17142        @Override
17143        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17144            synchronized (mPackages) {
17145                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17146            }
17147        }
17148
17149        @Override
17150        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17151            synchronized (mPackages) {
17152                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17153            }
17154        }
17155
17156        @Override
17157        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17158            synchronized (mPackages) {
17159                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17160            }
17161        }
17162
17163        @Override
17164        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17165            synchronized (mPackages) {
17166                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17167                        packageName, userId);
17168            }
17169        }
17170
17171        @Override
17172        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17173            synchronized (mPackages) {
17174                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17175                        packageName, userId);
17176            }
17177        }
17178        @Override
17179        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17180            synchronized (mPackages) {
17181                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17182                        packageName, userId);
17183            }
17184        }
17185
17186        @Override
17187        public void setKeepUninstalledPackages(final List<String> packageList) {
17188            Preconditions.checkNotNull(packageList);
17189            List<String> removedFromList = null;
17190            synchronized (mPackages) {
17191                if (mKeepUninstalledPackages != null) {
17192                    final int packagesCount = mKeepUninstalledPackages.size();
17193                    for (int i = 0; i < packagesCount; i++) {
17194                        String oldPackage = mKeepUninstalledPackages.get(i);
17195                        if (packageList != null && packageList.contains(oldPackage)) {
17196                            continue;
17197                        }
17198                        if (removedFromList == null) {
17199                            removedFromList = new ArrayList<>();
17200                        }
17201                        removedFromList.add(oldPackage);
17202                    }
17203                }
17204                mKeepUninstalledPackages = new ArrayList<>(packageList);
17205                if (removedFromList != null) {
17206                    final int removedCount = removedFromList.size();
17207                    for (int i = 0; i < removedCount; i++) {
17208                        deletePackageIfUnusedLPr(removedFromList.get(i));
17209                    }
17210                }
17211            }
17212        }
17213    }
17214
17215    @Override
17216    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17217        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17218        synchronized (mPackages) {
17219            final long identity = Binder.clearCallingIdentity();
17220            try {
17221                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17222                        packageNames, userId);
17223            } finally {
17224                Binder.restoreCallingIdentity(identity);
17225            }
17226        }
17227    }
17228
17229    private static void enforceSystemOrPhoneCaller(String tag) {
17230        int callingUid = Binder.getCallingUid();
17231        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17232            throw new SecurityException(
17233                    "Cannot call " + tag + " from UID " + callingUid);
17234        }
17235    }
17236}
17237