PackageManagerService.java revision 807e01cb47c2d5442f76e27b70a7206f77ed76d8
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 boolean isPackageFrozen(String packageName) {
2804        synchronized (mPackages) {
2805            final PackageSetting ps = mSettings.mPackages.get(packageName);
2806            if (ps != null) {
2807                return ps.frozen;
2808            }
2809        }
2810        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2811        return true;
2812    }
2813
2814    @Override
2815    public boolean isPackageAvailable(String packageName, int userId) {
2816        if (!sUserManager.exists(userId)) return false;
2817        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2818        synchronized (mPackages) {
2819            PackageParser.Package p = mPackages.get(packageName);
2820            if (p != null) {
2821                final PackageSetting ps = (PackageSetting) p.mExtras;
2822                if (ps != null) {
2823                    final PackageUserState state = ps.readUserState(userId);
2824                    if (state != null) {
2825                        return PackageParser.isAvailable(state);
2826                    }
2827                }
2828            }
2829        }
2830        return false;
2831    }
2832
2833    @Override
2834    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2835        if (!sUserManager.exists(userId)) return null;
2836        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2837        // reader
2838        synchronized (mPackages) {
2839            PackageParser.Package p = mPackages.get(packageName);
2840            if (DEBUG_PACKAGE_INFO)
2841                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2842            if (p != null) {
2843                return generatePackageInfo(p, flags, userId);
2844            }
2845            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2846                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public String[] currentToCanonicalPackageNames(String[] names) {
2854        String[] out = new String[names.length];
2855        // reader
2856        synchronized (mPackages) {
2857            for (int i=names.length-1; i>=0; i--) {
2858                PackageSetting ps = mSettings.mPackages.get(names[i]);
2859                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2860            }
2861        }
2862        return out;
2863    }
2864
2865    @Override
2866    public String[] canonicalToCurrentPackageNames(String[] names) {
2867        String[] out = new String[names.length];
2868        // reader
2869        synchronized (mPackages) {
2870            for (int i=names.length-1; i>=0; i--) {
2871                String cur = mSettings.mRenamedPackages.get(names[i]);
2872                out[i] = cur != null ? cur : names[i];
2873            }
2874        }
2875        return out;
2876    }
2877
2878    @Override
2879    public int getPackageUid(String packageName, int userId) {
2880        return getPackageUidEtc(packageName, 0, userId);
2881    }
2882
2883    @Override
2884    public int getPackageUidEtc(String packageName, int flags, int userId) {
2885        if (!sUserManager.exists(userId)) return -1;
2886        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2887
2888        // reader
2889        synchronized (mPackages) {
2890            final PackageParser.Package p = mPackages.get(packageName);
2891            if (p != null) {
2892                return UserHandle.getUid(userId, p.applicationInfo.uid);
2893            }
2894            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2895                final PackageSetting ps = mSettings.mPackages.get(packageName);
2896                if (ps != null) {
2897                    return UserHandle.getUid(userId, ps.appId);
2898                }
2899            }
2900        }
2901
2902        return -1;
2903    }
2904
2905    @Override
2906    public int[] getPackageGids(String packageName, int userId) {
2907        return getPackageGidsEtc(packageName, 0, userId);
2908    }
2909
2910    @Override
2911    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2912        if (!sUserManager.exists(userId)) {
2913            return null;
2914        }
2915
2916        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2917                "getPackageGids");
2918
2919        // reader
2920        synchronized (mPackages) {
2921            final PackageParser.Package p = mPackages.get(packageName);
2922            if (p != null) {
2923                PackageSetting ps = (PackageSetting) p.mExtras;
2924                return ps.getPermissionsState().computeGids(userId);
2925            }
2926            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2927                final PackageSetting ps = mSettings.mPackages.get(packageName);
2928                if (ps != null) {
2929                    return ps.getPermissionsState().computeGids(userId);
2930                }
2931            }
2932        }
2933
2934        return null;
2935    }
2936
2937    static PermissionInfo generatePermissionInfo(
2938            BasePermission bp, int flags) {
2939        if (bp.perm != null) {
2940            return PackageParser.generatePermissionInfo(bp.perm, flags);
2941        }
2942        PermissionInfo pi = new PermissionInfo();
2943        pi.name = bp.name;
2944        pi.packageName = bp.sourcePackage;
2945        pi.nonLocalizedLabel = bp.name;
2946        pi.protectionLevel = bp.protectionLevel;
2947        return pi;
2948    }
2949
2950    @Override
2951    public PermissionInfo getPermissionInfo(String name, int flags) {
2952        // reader
2953        synchronized (mPackages) {
2954            final BasePermission p = mSettings.mPermissions.get(name);
2955            if (p != null) {
2956                return generatePermissionInfo(p, flags);
2957            }
2958            return null;
2959        }
2960    }
2961
2962    @Override
2963    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2964        // reader
2965        synchronized (mPackages) {
2966            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2967            for (BasePermission p : mSettings.mPermissions.values()) {
2968                if (group == null) {
2969                    if (p.perm == null || p.perm.info.group == null) {
2970                        out.add(generatePermissionInfo(p, flags));
2971                    }
2972                } else {
2973                    if (p.perm != null && group.equals(p.perm.info.group)) {
2974                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2975                    }
2976                }
2977            }
2978
2979            if (out.size() > 0) {
2980                return out;
2981            }
2982            return mPermissionGroups.containsKey(group) ? out : null;
2983        }
2984    }
2985
2986    @Override
2987    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2988        // reader
2989        synchronized (mPackages) {
2990            return PackageParser.generatePermissionGroupInfo(
2991                    mPermissionGroups.get(name), flags);
2992        }
2993    }
2994
2995    @Override
2996    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2997        // reader
2998        synchronized (mPackages) {
2999            final int N = mPermissionGroups.size();
3000            ArrayList<PermissionGroupInfo> out
3001                    = new ArrayList<PermissionGroupInfo>(N);
3002            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3003                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3004            }
3005            return out;
3006        }
3007    }
3008
3009    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3010            int userId) {
3011        if (!sUserManager.exists(userId)) return null;
3012        PackageSetting ps = mSettings.mPackages.get(packageName);
3013        if (ps != null) {
3014            if (ps.pkg == null) {
3015                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3016                        flags, userId);
3017                if (pInfo != null) {
3018                    return pInfo.applicationInfo;
3019                }
3020                return null;
3021            }
3022            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3023                    ps.readUserState(userId), userId);
3024        }
3025        return null;
3026    }
3027
3028    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3029            int userId) {
3030        if (!sUserManager.exists(userId)) return null;
3031        PackageSetting ps = mSettings.mPackages.get(packageName);
3032        if (ps != null) {
3033            PackageParser.Package pkg = ps.pkg;
3034            if (pkg == null) {
3035                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3036                    return null;
3037                }
3038                // Only data remains, so we aren't worried about code paths
3039                pkg = new PackageParser.Package(packageName);
3040                pkg.applicationInfo.packageName = packageName;
3041                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3042                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3043                pkg.applicationInfo.uid = ps.appId;
3044                pkg.applicationInfo.initForUser(userId);
3045                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3046                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3047            }
3048            return generatePackageInfo(pkg, flags, userId);
3049        }
3050        return null;
3051    }
3052
3053    @Override
3054    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3057        // writer
3058        synchronized (mPackages) {
3059            PackageParser.Package p = mPackages.get(packageName);
3060            if (DEBUG_PACKAGE_INFO) Log.v(
3061                    TAG, "getApplicationInfo " + packageName
3062                    + ": " + p);
3063            if (p != null) {
3064                PackageSetting ps = mSettings.mPackages.get(packageName);
3065                if (ps == null) return null;
3066                // Note: isEnabledLP() does not apply here - always return info
3067                return PackageParser.generateApplicationInfo(
3068                        p, flags, ps.readUserState(userId), userId);
3069            }
3070            if ("android".equals(packageName)||"system".equals(packageName)) {
3071                return mAndroidApplication;
3072            }
3073            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3074                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3075            }
3076        }
3077        return null;
3078    }
3079
3080    @Override
3081    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3082            final IPackageDataObserver observer) {
3083        mContext.enforceCallingOrSelfPermission(
3084                android.Manifest.permission.CLEAR_APP_CACHE, null);
3085        // Queue up an async operation since clearing cache may take a little while.
3086        mHandler.post(new Runnable() {
3087            public void run() {
3088                mHandler.removeCallbacks(this);
3089                int retCode = -1;
3090                synchronized (mInstallLock) {
3091                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3092                    if (retCode < 0) {
3093                        Slog.w(TAG, "Couldn't clear application caches");
3094                    }
3095                }
3096                if (observer != null) {
3097                    try {
3098                        observer.onRemoveCompleted(null, (retCode >= 0));
3099                    } catch (RemoteException e) {
3100                        Slog.w(TAG, "RemoveException when invoking call back");
3101                    }
3102                }
3103            }
3104        });
3105    }
3106
3107    @Override
3108    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3109            final IntentSender pi) {
3110        mContext.enforceCallingOrSelfPermission(
3111                android.Manifest.permission.CLEAR_APP_CACHE, null);
3112        // Queue up an async operation since clearing cache may take a little while.
3113        mHandler.post(new Runnable() {
3114            public void run() {
3115                mHandler.removeCallbacks(this);
3116                int retCode = -1;
3117                synchronized (mInstallLock) {
3118                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3119                    if (retCode < 0) {
3120                        Slog.w(TAG, "Couldn't clear application caches");
3121                    }
3122                }
3123                if(pi != null) {
3124                    try {
3125                        // Callback via pending intent
3126                        int code = (retCode >= 0) ? 1 : 0;
3127                        pi.sendIntent(null, code, null,
3128                                null, null);
3129                    } catch (SendIntentException e1) {
3130                        Slog.i(TAG, "Failed to send pending intent");
3131                    }
3132                }
3133            }
3134        });
3135    }
3136
3137    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3138        synchronized (mInstallLock) {
3139            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3140                throw new IOException("Failed to free enough space");
3141            }
3142        }
3143    }
3144
3145    /**
3146     * Augment the given flags depending on current user running state. This is
3147     * purposefully done before acquiring {@link #mPackages} lock.
3148     */
3149    private int augmentFlagsForUser(int flags, int userId) {
3150        if (StorageManager.isFileBasedEncryptionEnabled()) {
3151            final IMountService mount = IMountService.Stub
3152                    .asInterface(ServiceManager.getService("mount"));
3153            if (mount == null) {
3154                // We must be early in boot, so the best we can do is assume the
3155                // user is fully running.
3156                Slog.w(TAG, "Early during boot, assuming not encrypted");
3157                return flags;
3158            }
3159            final long token = Binder.clearCallingIdentity();
3160            try {
3161                if (!mount.isUserKeyUnlocked(userId)) {
3162                    flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3163                }
3164            } catch (RemoteException e) {
3165                throw e.rethrowAsRuntimeException();
3166            } finally {
3167                Binder.restoreCallingIdentity(token);
3168            }
3169        }
3170        return flags;
3171    }
3172
3173    @Override
3174    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3175        if (!sUserManager.exists(userId)) return null;
3176        flags = augmentFlagsForUser(flags, userId);
3177        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3178        synchronized (mPackages) {
3179            PackageParser.Activity a = mActivities.mActivities.get(component);
3180
3181            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3182            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3183                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3184                if (ps == null) return null;
3185                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3186                        userId);
3187            }
3188            if (mResolveComponentName.equals(component)) {
3189                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3190                        new PackageUserState(), userId);
3191            }
3192        }
3193        return null;
3194    }
3195
3196    @Override
3197    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3198            String resolvedType) {
3199        synchronized (mPackages) {
3200            if (component.equals(mResolveComponentName)) {
3201                // The resolver supports EVERYTHING!
3202                return true;
3203            }
3204            PackageParser.Activity a = mActivities.mActivities.get(component);
3205            if (a == null) {
3206                return false;
3207            }
3208            for (int i=0; i<a.intents.size(); i++) {
3209                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3210                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3211                    return true;
3212                }
3213            }
3214            return false;
3215        }
3216    }
3217
3218    @Override
3219    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3220        if (!sUserManager.exists(userId)) return null;
3221        flags = augmentFlagsForUser(flags, userId);
3222        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3223        synchronized (mPackages) {
3224            PackageParser.Activity a = mReceivers.mActivities.get(component);
3225            if (DEBUG_PACKAGE_INFO) Log.v(
3226                TAG, "getReceiverInfo " + component + ": " + a);
3227            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3228                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3229                if (ps == null) return null;
3230                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3231                        userId);
3232            }
3233        }
3234        return null;
3235    }
3236
3237    @Override
3238    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3239        if (!sUserManager.exists(userId)) return null;
3240        flags = augmentFlagsForUser(flags, userId);
3241        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3242        synchronized (mPackages) {
3243            PackageParser.Service s = mServices.mServices.get(component);
3244            if (DEBUG_PACKAGE_INFO) Log.v(
3245                TAG, "getServiceInfo " + component + ": " + s);
3246            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3247                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3248                if (ps == null) return null;
3249                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3250                        userId);
3251            }
3252        }
3253        return null;
3254    }
3255
3256    @Override
3257    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3258        if (!sUserManager.exists(userId)) return null;
3259        flags = augmentFlagsForUser(flags, userId);
3260        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3261        synchronized (mPackages) {
3262            PackageParser.Provider p = mProviders.mProviders.get(component);
3263            if (DEBUG_PACKAGE_INFO) Log.v(
3264                TAG, "getProviderInfo " + component + ": " + p);
3265            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3266                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3267                if (ps == null) return null;
3268                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3269                        userId);
3270            }
3271        }
3272        return null;
3273    }
3274
3275    @Override
3276    public String[] getSystemSharedLibraryNames() {
3277        Set<String> libSet;
3278        synchronized (mPackages) {
3279            libSet = mSharedLibraries.keySet();
3280            int size = libSet.size();
3281            if (size > 0) {
3282                String[] libs = new String[size];
3283                libSet.toArray(libs);
3284                return libs;
3285            }
3286        }
3287        return null;
3288    }
3289
3290    /**
3291     * @hide
3292     */
3293    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3294        synchronized (mPackages) {
3295            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3296            if (lib != null && lib.apk != null) {
3297                return mPackages.get(lib.apk);
3298            }
3299        }
3300        return null;
3301    }
3302
3303    @Override
3304    public FeatureInfo[] getSystemAvailableFeatures() {
3305        Collection<FeatureInfo> featSet;
3306        synchronized (mPackages) {
3307            featSet = mAvailableFeatures.values();
3308            int size = featSet.size();
3309            if (size > 0) {
3310                FeatureInfo[] features = new FeatureInfo[size+1];
3311                featSet.toArray(features);
3312                FeatureInfo fi = new FeatureInfo();
3313                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3314                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3315                features[size] = fi;
3316                return features;
3317            }
3318        }
3319        return null;
3320    }
3321
3322    @Override
3323    public boolean hasSystemFeature(String name) {
3324        synchronized (mPackages) {
3325            return mAvailableFeatures.containsKey(name);
3326        }
3327    }
3328
3329    private void checkValidCaller(int uid, int userId) {
3330        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3331            return;
3332
3333        throw new SecurityException("Caller uid=" + uid
3334                + " is not privileged to communicate with user=" + userId);
3335    }
3336
3337    @Override
3338    public int checkPermission(String permName, String pkgName, int userId) {
3339        if (!sUserManager.exists(userId)) {
3340            return PackageManager.PERMISSION_DENIED;
3341        }
3342
3343        synchronized (mPackages) {
3344            final PackageParser.Package p = mPackages.get(pkgName);
3345            if (p != null && p.mExtras != null) {
3346                final PackageSetting ps = (PackageSetting) p.mExtras;
3347                final PermissionsState permissionsState = ps.getPermissionsState();
3348                if (permissionsState.hasPermission(permName, userId)) {
3349                    return PackageManager.PERMISSION_GRANTED;
3350                }
3351                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3352                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3353                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3354                    return PackageManager.PERMISSION_GRANTED;
3355                }
3356            }
3357        }
3358
3359        return PackageManager.PERMISSION_DENIED;
3360    }
3361
3362    @Override
3363    public int checkUidPermission(String permName, int uid) {
3364        final int userId = UserHandle.getUserId(uid);
3365
3366        if (!sUserManager.exists(userId)) {
3367            return PackageManager.PERMISSION_DENIED;
3368        }
3369
3370        synchronized (mPackages) {
3371            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3372            if (obj != null) {
3373                final SettingBase ps = (SettingBase) obj;
3374                final PermissionsState permissionsState = ps.getPermissionsState();
3375                if (permissionsState.hasPermission(permName, userId)) {
3376                    return PackageManager.PERMISSION_GRANTED;
3377                }
3378                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3379                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3380                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3381                    return PackageManager.PERMISSION_GRANTED;
3382                }
3383            } else {
3384                ArraySet<String> perms = mSystemPermissions.get(uid);
3385                if (perms != null) {
3386                    if (perms.contains(permName)) {
3387                        return PackageManager.PERMISSION_GRANTED;
3388                    }
3389                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3390                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3391                        return PackageManager.PERMISSION_GRANTED;
3392                    }
3393                }
3394            }
3395        }
3396
3397        return PackageManager.PERMISSION_DENIED;
3398    }
3399
3400    @Override
3401    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3402        if (UserHandle.getCallingUserId() != userId) {
3403            mContext.enforceCallingPermission(
3404                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3405                    "isPermissionRevokedByPolicy for user " + userId);
3406        }
3407
3408        if (checkPermission(permission, packageName, userId)
3409                == PackageManager.PERMISSION_GRANTED) {
3410            return false;
3411        }
3412
3413        final long identity = Binder.clearCallingIdentity();
3414        try {
3415            final int flags = getPermissionFlags(permission, packageName, userId);
3416            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3417        } finally {
3418            Binder.restoreCallingIdentity(identity);
3419        }
3420    }
3421
3422    @Override
3423    public String getPermissionControllerPackageName() {
3424        synchronized (mPackages) {
3425            return mRequiredInstallerPackage;
3426        }
3427    }
3428
3429    /**
3430     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3431     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3432     * @param checkShell TODO(yamasani):
3433     * @param message the message to log on security exception
3434     */
3435    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3436            boolean checkShell, String message) {
3437        if (userId < 0) {
3438            throw new IllegalArgumentException("Invalid userId " + userId);
3439        }
3440        if (checkShell) {
3441            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3442        }
3443        if (userId == UserHandle.getUserId(callingUid)) return;
3444        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3445            if (requireFullPermission) {
3446                mContext.enforceCallingOrSelfPermission(
3447                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3448            } else {
3449                try {
3450                    mContext.enforceCallingOrSelfPermission(
3451                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3452                } catch (SecurityException se) {
3453                    mContext.enforceCallingOrSelfPermission(
3454                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3455                }
3456            }
3457        }
3458    }
3459
3460    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3461        if (callingUid == Process.SHELL_UID) {
3462            if (userHandle >= 0
3463                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3464                throw new SecurityException("Shell does not have permission to access user "
3465                        + userHandle);
3466            } else if (userHandle < 0) {
3467                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3468                        + Debug.getCallers(3));
3469            }
3470        }
3471    }
3472
3473    private BasePermission findPermissionTreeLP(String permName) {
3474        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3475            if (permName.startsWith(bp.name) &&
3476                    permName.length() > bp.name.length() &&
3477                    permName.charAt(bp.name.length()) == '.') {
3478                return bp;
3479            }
3480        }
3481        return null;
3482    }
3483
3484    private BasePermission checkPermissionTreeLP(String permName) {
3485        if (permName != null) {
3486            BasePermission bp = findPermissionTreeLP(permName);
3487            if (bp != null) {
3488                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3489                    return bp;
3490                }
3491                throw new SecurityException("Calling uid "
3492                        + Binder.getCallingUid()
3493                        + " is not allowed to add to permission tree "
3494                        + bp.name + " owned by uid " + bp.uid);
3495            }
3496        }
3497        throw new SecurityException("No permission tree found for " + permName);
3498    }
3499
3500    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3501        if (s1 == null) {
3502            return s2 == null;
3503        }
3504        if (s2 == null) {
3505            return false;
3506        }
3507        if (s1.getClass() != s2.getClass()) {
3508            return false;
3509        }
3510        return s1.equals(s2);
3511    }
3512
3513    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3514        if (pi1.icon != pi2.icon) return false;
3515        if (pi1.logo != pi2.logo) return false;
3516        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3517        if (!compareStrings(pi1.name, pi2.name)) return false;
3518        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3519        // We'll take care of setting this one.
3520        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3521        // These are not currently stored in settings.
3522        //if (!compareStrings(pi1.group, pi2.group)) return false;
3523        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3524        //if (pi1.labelRes != pi2.labelRes) return false;
3525        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3526        return true;
3527    }
3528
3529    int permissionInfoFootprint(PermissionInfo info) {
3530        int size = info.name.length();
3531        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3532        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3533        return size;
3534    }
3535
3536    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3537        int size = 0;
3538        for (BasePermission perm : mSettings.mPermissions.values()) {
3539            if (perm.uid == tree.uid) {
3540                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3541            }
3542        }
3543        return size;
3544    }
3545
3546    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3547        // We calculate the max size of permissions defined by this uid and throw
3548        // if that plus the size of 'info' would exceed our stated maximum.
3549        if (tree.uid != Process.SYSTEM_UID) {
3550            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3551            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3552                throw new SecurityException("Permission tree size cap exceeded");
3553            }
3554        }
3555    }
3556
3557    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3558        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3559            throw new SecurityException("Label must be specified in permission");
3560        }
3561        BasePermission tree = checkPermissionTreeLP(info.name);
3562        BasePermission bp = mSettings.mPermissions.get(info.name);
3563        boolean added = bp == null;
3564        boolean changed = true;
3565        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3566        if (added) {
3567            enforcePermissionCapLocked(info, tree);
3568            bp = new BasePermission(info.name, tree.sourcePackage,
3569                    BasePermission.TYPE_DYNAMIC);
3570        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3571            throw new SecurityException(
3572                    "Not allowed to modify non-dynamic permission "
3573                    + info.name);
3574        } else {
3575            if (bp.protectionLevel == fixedLevel
3576                    && bp.perm.owner.equals(tree.perm.owner)
3577                    && bp.uid == tree.uid
3578                    && comparePermissionInfos(bp.perm.info, info)) {
3579                changed = false;
3580            }
3581        }
3582        bp.protectionLevel = fixedLevel;
3583        info = new PermissionInfo(info);
3584        info.protectionLevel = fixedLevel;
3585        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3586        bp.perm.info.packageName = tree.perm.info.packageName;
3587        bp.uid = tree.uid;
3588        if (added) {
3589            mSettings.mPermissions.put(info.name, bp);
3590        }
3591        if (changed) {
3592            if (!async) {
3593                mSettings.writeLPr();
3594            } else {
3595                scheduleWriteSettingsLocked();
3596            }
3597        }
3598        return added;
3599    }
3600
3601    @Override
3602    public boolean addPermission(PermissionInfo info) {
3603        synchronized (mPackages) {
3604            return addPermissionLocked(info, false);
3605        }
3606    }
3607
3608    @Override
3609    public boolean addPermissionAsync(PermissionInfo info) {
3610        synchronized (mPackages) {
3611            return addPermissionLocked(info, true);
3612        }
3613    }
3614
3615    @Override
3616    public void removePermission(String name) {
3617        synchronized (mPackages) {
3618            checkPermissionTreeLP(name);
3619            BasePermission bp = mSettings.mPermissions.get(name);
3620            if (bp != null) {
3621                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3622                    throw new SecurityException(
3623                            "Not allowed to modify non-dynamic permission "
3624                            + name);
3625                }
3626                mSettings.mPermissions.remove(name);
3627                mSettings.writeLPr();
3628            }
3629        }
3630    }
3631
3632    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3633            BasePermission bp) {
3634        int index = pkg.requestedPermissions.indexOf(bp.name);
3635        if (index == -1) {
3636            throw new SecurityException("Package " + pkg.packageName
3637                    + " has not requested permission " + bp.name);
3638        }
3639        if (!bp.isRuntime() && !bp.isDevelopment()) {
3640            throw new SecurityException("Permission " + bp.name
3641                    + " is not a changeable permission type");
3642        }
3643    }
3644
3645    @Override
3646    public void grantRuntimePermission(String packageName, String name, final int userId) {
3647        if (!sUserManager.exists(userId)) {
3648            Log.e(TAG, "No such user:" + userId);
3649            return;
3650        }
3651
3652        mContext.enforceCallingOrSelfPermission(
3653                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3654                "grantRuntimePermission");
3655
3656        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3657                "grantRuntimePermission");
3658
3659        final int uid;
3660        final SettingBase sb;
3661
3662        synchronized (mPackages) {
3663            final PackageParser.Package pkg = mPackages.get(packageName);
3664            if (pkg == null) {
3665                throw new IllegalArgumentException("Unknown package: " + packageName);
3666            }
3667
3668            final BasePermission bp = mSettings.mPermissions.get(name);
3669            if (bp == null) {
3670                throw new IllegalArgumentException("Unknown permission: " + name);
3671            }
3672
3673            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3674
3675            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3676            sb = (SettingBase) pkg.mExtras;
3677            if (sb == null) {
3678                throw new IllegalArgumentException("Unknown package: " + packageName);
3679            }
3680
3681            final PermissionsState permissionsState = sb.getPermissionsState();
3682
3683            final int flags = permissionsState.getPermissionFlags(name, userId);
3684            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3685                throw new SecurityException("Cannot grant system fixed permission: "
3686                        + name + " for package: " + packageName);
3687            }
3688
3689            if (bp.isDevelopment()) {
3690                // Development permissions must be handled specially, since they are not
3691                // normal runtime permissions.  For now they apply to all users.
3692                if (permissionsState.grantInstallPermission(bp) !=
3693                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3694                    scheduleWriteSettingsLocked();
3695                }
3696                return;
3697            }
3698
3699            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3700                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3701                return;
3702            }
3703
3704            final int result = permissionsState.grantRuntimePermission(bp, userId);
3705            switch (result) {
3706                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3707                    return;
3708                }
3709
3710                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3711                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3712                    mHandler.post(new Runnable() {
3713                        @Override
3714                        public void run() {
3715                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3716                        }
3717                    });
3718                }
3719                break;
3720            }
3721
3722            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3723
3724            // Not critical if that is lost - app has to request again.
3725            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3726        }
3727
3728        // Only need to do this if user is initialized. Otherwise it's a new user
3729        // and there are no processes running as the user yet and there's no need
3730        // to make an expensive call to remount processes for the changed permissions.
3731        if (READ_EXTERNAL_STORAGE.equals(name)
3732                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3733            final long token = Binder.clearCallingIdentity();
3734            try {
3735                if (sUserManager.isInitialized(userId)) {
3736                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3737                            MountServiceInternal.class);
3738                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3739                }
3740            } finally {
3741                Binder.restoreCallingIdentity(token);
3742            }
3743        }
3744    }
3745
3746    @Override
3747    public void revokeRuntimePermission(String packageName, String name, int userId) {
3748        if (!sUserManager.exists(userId)) {
3749            Log.e(TAG, "No such user:" + userId);
3750            return;
3751        }
3752
3753        mContext.enforceCallingOrSelfPermission(
3754                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3755                "revokeRuntimePermission");
3756
3757        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3758                "revokeRuntimePermission");
3759
3760        final int appId;
3761
3762        synchronized (mPackages) {
3763            final PackageParser.Package pkg = mPackages.get(packageName);
3764            if (pkg == null) {
3765                throw new IllegalArgumentException("Unknown package: " + packageName);
3766            }
3767
3768            final BasePermission bp = mSettings.mPermissions.get(name);
3769            if (bp == null) {
3770                throw new IllegalArgumentException("Unknown permission: " + name);
3771            }
3772
3773            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3774
3775            SettingBase sb = (SettingBase) pkg.mExtras;
3776            if (sb == null) {
3777                throw new IllegalArgumentException("Unknown package: " + packageName);
3778            }
3779
3780            final PermissionsState permissionsState = sb.getPermissionsState();
3781
3782            final int flags = permissionsState.getPermissionFlags(name, userId);
3783            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3784                throw new SecurityException("Cannot revoke system fixed permission: "
3785                        + name + " for package: " + packageName);
3786            }
3787
3788            if (bp.isDevelopment()) {
3789                // Development permissions must be handled specially, since they are not
3790                // normal runtime permissions.  For now they apply to all users.
3791                if (permissionsState.revokeInstallPermission(bp) !=
3792                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3793                    scheduleWriteSettingsLocked();
3794                }
3795                return;
3796            }
3797
3798            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3799                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3800                return;
3801            }
3802
3803            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3804
3805            // Critical, after this call app should never have the permission.
3806            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3807
3808            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3809        }
3810
3811        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3812    }
3813
3814    @Override
3815    public void resetRuntimePermissions() {
3816        mContext.enforceCallingOrSelfPermission(
3817                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3818                "revokeRuntimePermission");
3819
3820        int callingUid = Binder.getCallingUid();
3821        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3822            mContext.enforceCallingOrSelfPermission(
3823                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3824                    "resetRuntimePermissions");
3825        }
3826
3827        synchronized (mPackages) {
3828            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3829            for (int userId : UserManagerService.getInstance().getUserIds()) {
3830                final int packageCount = mPackages.size();
3831                for (int i = 0; i < packageCount; i++) {
3832                    PackageParser.Package pkg = mPackages.valueAt(i);
3833                    if (!(pkg.mExtras instanceof PackageSetting)) {
3834                        continue;
3835                    }
3836                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3837                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3838                }
3839            }
3840        }
3841    }
3842
3843    @Override
3844    public int getPermissionFlags(String name, String packageName, int userId) {
3845        if (!sUserManager.exists(userId)) {
3846            return 0;
3847        }
3848
3849        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3850
3851        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3852                "getPermissionFlags");
3853
3854        synchronized (mPackages) {
3855            final PackageParser.Package pkg = mPackages.get(packageName);
3856            if (pkg == null) {
3857                throw new IllegalArgumentException("Unknown package: " + packageName);
3858            }
3859
3860            final BasePermission bp = mSettings.mPermissions.get(name);
3861            if (bp == null) {
3862                throw new IllegalArgumentException("Unknown permission: " + name);
3863            }
3864
3865            SettingBase sb = (SettingBase) pkg.mExtras;
3866            if (sb == null) {
3867                throw new IllegalArgumentException("Unknown package: " + packageName);
3868            }
3869
3870            PermissionsState permissionsState = sb.getPermissionsState();
3871            return permissionsState.getPermissionFlags(name, userId);
3872        }
3873    }
3874
3875    @Override
3876    public void updatePermissionFlags(String name, String packageName, int flagMask,
3877            int flagValues, int userId) {
3878        if (!sUserManager.exists(userId)) {
3879            return;
3880        }
3881
3882        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3883
3884        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3885                "updatePermissionFlags");
3886
3887        // Only the system can change these flags and nothing else.
3888        if (getCallingUid() != Process.SYSTEM_UID) {
3889            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3890            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3891            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3892            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3893        }
3894
3895        synchronized (mPackages) {
3896            final PackageParser.Package pkg = mPackages.get(packageName);
3897            if (pkg == null) {
3898                throw new IllegalArgumentException("Unknown package: " + packageName);
3899            }
3900
3901            final BasePermission bp = mSettings.mPermissions.get(name);
3902            if (bp == null) {
3903                throw new IllegalArgumentException("Unknown permission: " + name);
3904            }
3905
3906            SettingBase sb = (SettingBase) pkg.mExtras;
3907            if (sb == null) {
3908                throw new IllegalArgumentException("Unknown package: " + packageName);
3909            }
3910
3911            PermissionsState permissionsState = sb.getPermissionsState();
3912
3913            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3914
3915            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3916                // Install and runtime permissions are stored in different places,
3917                // so figure out what permission changed and persist the change.
3918                if (permissionsState.getInstallPermissionState(name) != null) {
3919                    scheduleWriteSettingsLocked();
3920                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3921                        || hadState) {
3922                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3923                }
3924            }
3925        }
3926    }
3927
3928    /**
3929     * Update the permission flags for all packages and runtime permissions of a user in order
3930     * to allow device or profile owner to remove POLICY_FIXED.
3931     */
3932    @Override
3933    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3934        if (!sUserManager.exists(userId)) {
3935            return;
3936        }
3937
3938        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3939
3940        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3941                "updatePermissionFlagsForAllApps");
3942
3943        // Only the system can change system fixed flags.
3944        if (getCallingUid() != Process.SYSTEM_UID) {
3945            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3946            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3947        }
3948
3949        synchronized (mPackages) {
3950            boolean changed = false;
3951            final int packageCount = mPackages.size();
3952            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3953                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3954                SettingBase sb = (SettingBase) pkg.mExtras;
3955                if (sb == null) {
3956                    continue;
3957                }
3958                PermissionsState permissionsState = sb.getPermissionsState();
3959                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3960                        userId, flagMask, flagValues);
3961            }
3962            if (changed) {
3963                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3964            }
3965        }
3966    }
3967
3968    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3969        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3970                != PackageManager.PERMISSION_GRANTED
3971            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3972                != PackageManager.PERMISSION_GRANTED) {
3973            throw new SecurityException(message + " requires "
3974                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3975                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3976        }
3977    }
3978
3979    @Override
3980    public boolean shouldShowRequestPermissionRationale(String permissionName,
3981            String packageName, int userId) {
3982        if (UserHandle.getCallingUserId() != userId) {
3983            mContext.enforceCallingPermission(
3984                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3985                    "canShowRequestPermissionRationale for user " + userId);
3986        }
3987
3988        final int uid = getPackageUid(packageName, userId);
3989        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3990            return false;
3991        }
3992
3993        if (checkPermission(permissionName, packageName, userId)
3994                == PackageManager.PERMISSION_GRANTED) {
3995            return false;
3996        }
3997
3998        final int flags;
3999
4000        final long identity = Binder.clearCallingIdentity();
4001        try {
4002            flags = getPermissionFlags(permissionName,
4003                    packageName, userId);
4004        } finally {
4005            Binder.restoreCallingIdentity(identity);
4006        }
4007
4008        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4009                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4010                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4011
4012        if ((flags & fixedFlags) != 0) {
4013            return false;
4014        }
4015
4016        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4017    }
4018
4019    @Override
4020    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4021        mContext.enforceCallingOrSelfPermission(
4022                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4023                "addOnPermissionsChangeListener");
4024
4025        synchronized (mPackages) {
4026            mOnPermissionChangeListeners.addListenerLocked(listener);
4027        }
4028    }
4029
4030    @Override
4031    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4032        synchronized (mPackages) {
4033            mOnPermissionChangeListeners.removeListenerLocked(listener);
4034        }
4035    }
4036
4037    @Override
4038    public boolean isProtectedBroadcast(String actionName) {
4039        synchronized (mPackages) {
4040            return mProtectedBroadcasts.contains(actionName);
4041        }
4042    }
4043
4044    @Override
4045    public int checkSignatures(String pkg1, String pkg2) {
4046        synchronized (mPackages) {
4047            final PackageParser.Package p1 = mPackages.get(pkg1);
4048            final PackageParser.Package p2 = mPackages.get(pkg2);
4049            if (p1 == null || p1.mExtras == null
4050                    || p2 == null || p2.mExtras == null) {
4051                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4052            }
4053            return compareSignatures(p1.mSignatures, p2.mSignatures);
4054        }
4055    }
4056
4057    @Override
4058    public int checkUidSignatures(int uid1, int uid2) {
4059        // Map to base uids.
4060        uid1 = UserHandle.getAppId(uid1);
4061        uid2 = UserHandle.getAppId(uid2);
4062        // reader
4063        synchronized (mPackages) {
4064            Signature[] s1;
4065            Signature[] s2;
4066            Object obj = mSettings.getUserIdLPr(uid1);
4067            if (obj != null) {
4068                if (obj instanceof SharedUserSetting) {
4069                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4070                } else if (obj instanceof PackageSetting) {
4071                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4072                } else {
4073                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4074                }
4075            } else {
4076                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4077            }
4078            obj = mSettings.getUserIdLPr(uid2);
4079            if (obj != null) {
4080                if (obj instanceof SharedUserSetting) {
4081                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4082                } else if (obj instanceof PackageSetting) {
4083                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4084                } else {
4085                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4086                }
4087            } else {
4088                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4089            }
4090            return compareSignatures(s1, s2);
4091        }
4092    }
4093
4094    private void killUid(int appId, int userId, String reason) {
4095        final long identity = Binder.clearCallingIdentity();
4096        try {
4097            IActivityManager am = ActivityManagerNative.getDefault();
4098            if (am != null) {
4099                try {
4100                    am.killUid(appId, userId, reason);
4101                } catch (RemoteException e) {
4102                    /* ignore - same process */
4103                }
4104            }
4105        } finally {
4106            Binder.restoreCallingIdentity(identity);
4107        }
4108    }
4109
4110    /**
4111     * Compares two sets of signatures. Returns:
4112     * <br />
4113     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4114     * <br />
4115     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4116     * <br />
4117     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4118     * <br />
4119     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4120     * <br />
4121     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4122     */
4123    static int compareSignatures(Signature[] s1, Signature[] s2) {
4124        if (s1 == null) {
4125            return s2 == null
4126                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4127                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4128        }
4129
4130        if (s2 == null) {
4131            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4132        }
4133
4134        if (s1.length != s2.length) {
4135            return PackageManager.SIGNATURE_NO_MATCH;
4136        }
4137
4138        // Since both signature sets are of size 1, we can compare without HashSets.
4139        if (s1.length == 1) {
4140            return s1[0].equals(s2[0]) ?
4141                    PackageManager.SIGNATURE_MATCH :
4142                    PackageManager.SIGNATURE_NO_MATCH;
4143        }
4144
4145        ArraySet<Signature> set1 = new ArraySet<Signature>();
4146        for (Signature sig : s1) {
4147            set1.add(sig);
4148        }
4149        ArraySet<Signature> set2 = new ArraySet<Signature>();
4150        for (Signature sig : s2) {
4151            set2.add(sig);
4152        }
4153        // Make sure s2 contains all signatures in s1.
4154        if (set1.equals(set2)) {
4155            return PackageManager.SIGNATURE_MATCH;
4156        }
4157        return PackageManager.SIGNATURE_NO_MATCH;
4158    }
4159
4160    /**
4161     * If the database version for this type of package (internal storage or
4162     * external storage) is less than the version where package signatures
4163     * were updated, return true.
4164     */
4165    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4166        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4167        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4168    }
4169
4170    /**
4171     * Used for backward compatibility to make sure any packages with
4172     * certificate chains get upgraded to the new style. {@code existingSigs}
4173     * will be in the old format (since they were stored on disk from before the
4174     * system upgrade) and {@code scannedSigs} will be in the newer format.
4175     */
4176    private int compareSignaturesCompat(PackageSignatures existingSigs,
4177            PackageParser.Package scannedPkg) {
4178        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4179            return PackageManager.SIGNATURE_NO_MATCH;
4180        }
4181
4182        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4183        for (Signature sig : existingSigs.mSignatures) {
4184            existingSet.add(sig);
4185        }
4186        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4187        for (Signature sig : scannedPkg.mSignatures) {
4188            try {
4189                Signature[] chainSignatures = sig.getChainSignatures();
4190                for (Signature chainSig : chainSignatures) {
4191                    scannedCompatSet.add(chainSig);
4192                }
4193            } catch (CertificateEncodingException e) {
4194                scannedCompatSet.add(sig);
4195            }
4196        }
4197        /*
4198         * Make sure the expanded scanned set contains all signatures in the
4199         * existing one.
4200         */
4201        if (scannedCompatSet.equals(existingSet)) {
4202            // Migrate the old signatures to the new scheme.
4203            existingSigs.assignSignatures(scannedPkg.mSignatures);
4204            // The new KeySets will be re-added later in the scanning process.
4205            synchronized (mPackages) {
4206                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4207            }
4208            return PackageManager.SIGNATURE_MATCH;
4209        }
4210        return PackageManager.SIGNATURE_NO_MATCH;
4211    }
4212
4213    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4214        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4215        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4216    }
4217
4218    private int compareSignaturesRecover(PackageSignatures existingSigs,
4219            PackageParser.Package scannedPkg) {
4220        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4221            return PackageManager.SIGNATURE_NO_MATCH;
4222        }
4223
4224        String msg = null;
4225        try {
4226            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4227                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4228                        + scannedPkg.packageName);
4229                return PackageManager.SIGNATURE_MATCH;
4230            }
4231        } catch (CertificateException e) {
4232            msg = e.getMessage();
4233        }
4234
4235        logCriticalInfo(Log.INFO,
4236                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4237        return PackageManager.SIGNATURE_NO_MATCH;
4238    }
4239
4240    @Override
4241    public String[] getPackagesForUid(int uid) {
4242        uid = UserHandle.getAppId(uid);
4243        // reader
4244        synchronized (mPackages) {
4245            Object obj = mSettings.getUserIdLPr(uid);
4246            if (obj instanceof SharedUserSetting) {
4247                final SharedUserSetting sus = (SharedUserSetting) obj;
4248                final int N = sus.packages.size();
4249                final String[] res = new String[N];
4250                final Iterator<PackageSetting> it = sus.packages.iterator();
4251                int i = 0;
4252                while (it.hasNext()) {
4253                    res[i++] = it.next().name;
4254                }
4255                return res;
4256            } else if (obj instanceof PackageSetting) {
4257                final PackageSetting ps = (PackageSetting) obj;
4258                return new String[] { ps.name };
4259            }
4260        }
4261        return null;
4262    }
4263
4264    @Override
4265    public String getNameForUid(int uid) {
4266        // reader
4267        synchronized (mPackages) {
4268            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4269            if (obj instanceof SharedUserSetting) {
4270                final SharedUserSetting sus = (SharedUserSetting) obj;
4271                return sus.name + ":" + sus.userId;
4272            } else if (obj instanceof PackageSetting) {
4273                final PackageSetting ps = (PackageSetting) obj;
4274                return ps.name;
4275            }
4276        }
4277        return null;
4278    }
4279
4280    @Override
4281    public int getUidForSharedUser(String sharedUserName) {
4282        if(sharedUserName == null) {
4283            return -1;
4284        }
4285        // reader
4286        synchronized (mPackages) {
4287            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4288            if (suid == null) {
4289                return -1;
4290            }
4291            return suid.userId;
4292        }
4293    }
4294
4295    @Override
4296    public int getFlagsForUid(int uid) {
4297        synchronized (mPackages) {
4298            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4299            if (obj instanceof SharedUserSetting) {
4300                final SharedUserSetting sus = (SharedUserSetting) obj;
4301                return sus.pkgFlags;
4302            } else if (obj instanceof PackageSetting) {
4303                final PackageSetting ps = (PackageSetting) obj;
4304                return ps.pkgFlags;
4305            }
4306        }
4307        return 0;
4308    }
4309
4310    @Override
4311    public int getPrivateFlagsForUid(int uid) {
4312        synchronized (mPackages) {
4313            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4314            if (obj instanceof SharedUserSetting) {
4315                final SharedUserSetting sus = (SharedUserSetting) obj;
4316                return sus.pkgPrivateFlags;
4317            } else if (obj instanceof PackageSetting) {
4318                final PackageSetting ps = (PackageSetting) obj;
4319                return ps.pkgPrivateFlags;
4320            }
4321        }
4322        return 0;
4323    }
4324
4325    @Override
4326    public boolean isUidPrivileged(int uid) {
4327        uid = UserHandle.getAppId(uid);
4328        // reader
4329        synchronized (mPackages) {
4330            Object obj = mSettings.getUserIdLPr(uid);
4331            if (obj instanceof SharedUserSetting) {
4332                final SharedUserSetting sus = (SharedUserSetting) obj;
4333                final Iterator<PackageSetting> it = sus.packages.iterator();
4334                while (it.hasNext()) {
4335                    if (it.next().isPrivileged()) {
4336                        return true;
4337                    }
4338                }
4339            } else if (obj instanceof PackageSetting) {
4340                final PackageSetting ps = (PackageSetting) obj;
4341                return ps.isPrivileged();
4342            }
4343        }
4344        return false;
4345    }
4346
4347    @Override
4348    public String[] getAppOpPermissionPackages(String permissionName) {
4349        synchronized (mPackages) {
4350            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4351            if (pkgs == null) {
4352                return null;
4353            }
4354            return pkgs.toArray(new String[pkgs.size()]);
4355        }
4356    }
4357
4358    @Override
4359    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4360            int flags, int userId) {
4361        if (!sUserManager.exists(userId)) return null;
4362        flags = augmentFlagsForUser(flags, userId);
4363        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4364        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4365        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4366    }
4367
4368    @Override
4369    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4370            IntentFilter filter, int match, ComponentName activity) {
4371        final int userId = UserHandle.getCallingUserId();
4372        if (DEBUG_PREFERRED) {
4373            Log.v(TAG, "setLastChosenActivity intent=" + intent
4374                + " resolvedType=" + resolvedType
4375                + " flags=" + flags
4376                + " filter=" + filter
4377                + " match=" + match
4378                + " activity=" + activity);
4379            filter.dump(new PrintStreamPrinter(System.out), "    ");
4380        }
4381        intent.setComponent(null);
4382        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4383        // Find any earlier preferred or last chosen entries and nuke them
4384        findPreferredActivity(intent, resolvedType,
4385                flags, query, 0, false, true, false, userId);
4386        // Add the new activity as the last chosen for this filter
4387        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4388                "Setting last chosen");
4389    }
4390
4391    @Override
4392    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4393        final int userId = UserHandle.getCallingUserId();
4394        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4395        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4396        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4397                false, false, false, userId);
4398    }
4399
4400    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4401        MessageDigest digest = null;
4402        try {
4403            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4404        } catch (NoSuchAlgorithmException e) {
4405            // If we can't create a digest, ignore ephemeral apps.
4406            return false;
4407        }
4408
4409        final byte[] hostBytes = intent.getData().getHost().getBytes();
4410        final byte[] digestBytes = digest.digest(hostBytes);
4411        int shaPrefix =
4412                digestBytes[0] << 24
4413                | digestBytes[1] << 16
4414                | digestBytes[2] << 8
4415                | digestBytes[3] << 0;
4416        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4417                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4418        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4419            // No hash prefix match; there are no ephemeral apps for this domain.
4420            return false;
4421        }
4422        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4423            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4424            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4425                continue;
4426            }
4427            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4428            // No filters; this should never happen.
4429            if (filters.isEmpty()) {
4430                continue;
4431            }
4432            // We have a domain match; resolve the filters to see if anything matches.
4433            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4434            for (int j = filters.size() - 1; j >= 0; --j) {
4435                ephemeralResolver.addFilter(filters.get(j));
4436            }
4437            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4438                    intent, resolvedType, false /*defaultOnly*/, userId);
4439            return !ephemeralResolveList.isEmpty();
4440        }
4441        // Hash or filter mis-match; no ephemeral apps for this domain.
4442        return false;
4443    }
4444
4445    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4446            int flags, List<ResolveInfo> query, int userId) {
4447        final boolean isWebUri = hasWebURI(intent);
4448        // Check whether or not an ephemeral app exists to handle the URI.
4449        if (isWebUri && mEphemeralResolverConnection != null) {
4450            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4451            boolean hasAlwaysHandler = false;
4452            synchronized (mPackages) {
4453                final int count = query.size();
4454                for (int n=0; n<count; n++) {
4455                    ResolveInfo info = query.get(n);
4456                    String packageName = info.activityInfo.packageName;
4457                    PackageSetting ps = mSettings.mPackages.get(packageName);
4458                    if (ps != null) {
4459                        // Try to get the status from User settings first
4460                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4461                        int status = (int) (packedStatus >> 32);
4462                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4463                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4464                            hasAlwaysHandler = true;
4465                            break;
4466                        }
4467                    }
4468                }
4469            }
4470
4471            // Only consider installing an ephemeral app if there isn't already a verified handler.
4472            // We've determined that there's an ephemeral app available for the URI, ignore any
4473            // ResolveInfo's and just return the ephemeral installer
4474            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4475                if (DEBUG_EPHEMERAL) {
4476                    Slog.v(TAG, "Resolving to the ephemeral installer");
4477                }
4478                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4479                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4480                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4481                // make a deep copy of the applicationInfo
4482                ri.activityInfo.applicationInfo = new ApplicationInfo(
4483                        ri.activityInfo.applicationInfo);
4484                if (userId != 0) {
4485                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4486                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4487                }
4488                return ri;
4489            }
4490        }
4491        if (query != null) {
4492            final int N = query.size();
4493            if (N == 1) {
4494                return query.get(0);
4495            } else if (N > 1) {
4496                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4497                // If there is more than one activity with the same priority,
4498                // then let the user decide between them.
4499                ResolveInfo r0 = query.get(0);
4500                ResolveInfo r1 = query.get(1);
4501                if (DEBUG_INTENT_MATCHING || debug) {
4502                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4503                            + r1.activityInfo.name + "=" + r1.priority);
4504                }
4505                // If the first activity has a higher priority, or a different
4506                // default, then it is always desireable to pick it.
4507                if (r0.priority != r1.priority
4508                        || r0.preferredOrder != r1.preferredOrder
4509                        || r0.isDefault != r1.isDefault) {
4510                    return query.get(0);
4511                }
4512                // If we have saved a preference for a preferred activity for
4513                // this Intent, use that.
4514                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4515                        flags, query, r0.priority, true, false, debug, userId);
4516                if (ri != null) {
4517                    return ri;
4518                }
4519                ri = new ResolveInfo(mResolveInfo);
4520                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4521                ri.activityInfo.applicationInfo = new ApplicationInfo(
4522                        ri.activityInfo.applicationInfo);
4523                if (userId != 0) {
4524                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4525                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4526                }
4527                // Make sure that the resolver is displayable in car mode
4528                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4529                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4530                return ri;
4531            }
4532        }
4533        return null;
4534    }
4535
4536    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4537            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4538        final int N = query.size();
4539        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4540                .get(userId);
4541        // Get the list of persistent preferred activities that handle the intent
4542        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4543        List<PersistentPreferredActivity> pprefs = ppir != null
4544                ? ppir.queryIntent(intent, resolvedType,
4545                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4546                : null;
4547        if (pprefs != null && pprefs.size() > 0) {
4548            final int M = pprefs.size();
4549            for (int i=0; i<M; i++) {
4550                final PersistentPreferredActivity ppa = pprefs.get(i);
4551                if (DEBUG_PREFERRED || debug) {
4552                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4553                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4554                            + "\n  component=" + ppa.mComponent);
4555                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4556                }
4557                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4558                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4559                if (DEBUG_PREFERRED || debug) {
4560                    Slog.v(TAG, "Found persistent preferred activity:");
4561                    if (ai != null) {
4562                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4563                    } else {
4564                        Slog.v(TAG, "  null");
4565                    }
4566                }
4567                if (ai == null) {
4568                    // This previously registered persistent preferred activity
4569                    // component is no longer known. Ignore it and do NOT remove it.
4570                    continue;
4571                }
4572                for (int j=0; j<N; j++) {
4573                    final ResolveInfo ri = query.get(j);
4574                    if (!ri.activityInfo.applicationInfo.packageName
4575                            .equals(ai.applicationInfo.packageName)) {
4576                        continue;
4577                    }
4578                    if (!ri.activityInfo.name.equals(ai.name)) {
4579                        continue;
4580                    }
4581                    //  Found a persistent preference that can handle the intent.
4582                    if (DEBUG_PREFERRED || debug) {
4583                        Slog.v(TAG, "Returning persistent preferred activity: " +
4584                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4585                    }
4586                    return ri;
4587                }
4588            }
4589        }
4590        return null;
4591    }
4592
4593    // TODO: handle preferred activities missing while user has amnesia
4594    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4595            List<ResolveInfo> query, int priority, boolean always,
4596            boolean removeMatches, boolean debug, int userId) {
4597        if (!sUserManager.exists(userId)) return null;
4598        flags = augmentFlagsForUser(flags, userId);
4599        // writer
4600        synchronized (mPackages) {
4601            if (intent.getSelector() != null) {
4602                intent = intent.getSelector();
4603            }
4604            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4605
4606            // Try to find a matching persistent preferred activity.
4607            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4608                    debug, userId);
4609
4610            // If a persistent preferred activity matched, use it.
4611            if (pri != null) {
4612                return pri;
4613            }
4614
4615            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4616            // Get the list of preferred activities that handle the intent
4617            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4618            List<PreferredActivity> prefs = pir != null
4619                    ? pir.queryIntent(intent, resolvedType,
4620                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4621                    : null;
4622            if (prefs != null && prefs.size() > 0) {
4623                boolean changed = false;
4624                try {
4625                    // First figure out how good the original match set is.
4626                    // We will only allow preferred activities that came
4627                    // from the same match quality.
4628                    int match = 0;
4629
4630                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4631
4632                    final int N = query.size();
4633                    for (int j=0; j<N; j++) {
4634                        final ResolveInfo ri = query.get(j);
4635                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4636                                + ": 0x" + Integer.toHexString(match));
4637                        if (ri.match > match) {
4638                            match = ri.match;
4639                        }
4640                    }
4641
4642                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4643                            + Integer.toHexString(match));
4644
4645                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4646                    final int M = prefs.size();
4647                    for (int i=0; i<M; i++) {
4648                        final PreferredActivity pa = prefs.get(i);
4649                        if (DEBUG_PREFERRED || debug) {
4650                            Slog.v(TAG, "Checking PreferredActivity ds="
4651                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4652                                    + "\n  component=" + pa.mPref.mComponent);
4653                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4654                        }
4655                        if (pa.mPref.mMatch != match) {
4656                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4657                                    + Integer.toHexString(pa.mPref.mMatch));
4658                            continue;
4659                        }
4660                        // If it's not an "always" type preferred activity and that's what we're
4661                        // looking for, skip it.
4662                        if (always && !pa.mPref.mAlways) {
4663                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4664                            continue;
4665                        }
4666                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4667                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4668                        if (DEBUG_PREFERRED || debug) {
4669                            Slog.v(TAG, "Found preferred activity:");
4670                            if (ai != null) {
4671                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4672                            } else {
4673                                Slog.v(TAG, "  null");
4674                            }
4675                        }
4676                        if (ai == null) {
4677                            // This previously registered preferred activity
4678                            // component is no longer known.  Most likely an update
4679                            // to the app was installed and in the new version this
4680                            // component no longer exists.  Clean it up by removing
4681                            // it from the preferred activities list, and skip it.
4682                            Slog.w(TAG, "Removing dangling preferred activity: "
4683                                    + pa.mPref.mComponent);
4684                            pir.removeFilter(pa);
4685                            changed = true;
4686                            continue;
4687                        }
4688                        for (int j=0; j<N; j++) {
4689                            final ResolveInfo ri = query.get(j);
4690                            if (!ri.activityInfo.applicationInfo.packageName
4691                                    .equals(ai.applicationInfo.packageName)) {
4692                                continue;
4693                            }
4694                            if (!ri.activityInfo.name.equals(ai.name)) {
4695                                continue;
4696                            }
4697
4698                            if (removeMatches) {
4699                                pir.removeFilter(pa);
4700                                changed = true;
4701                                if (DEBUG_PREFERRED) {
4702                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4703                                }
4704                                break;
4705                            }
4706
4707                            // Okay we found a previously set preferred or last chosen app.
4708                            // If the result set is different from when this
4709                            // was created, we need to clear it and re-ask the
4710                            // user their preference, if we're looking for an "always" type entry.
4711                            if (always && !pa.mPref.sameSet(query)) {
4712                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4713                                        + intent + " type " + resolvedType);
4714                                if (DEBUG_PREFERRED) {
4715                                    Slog.v(TAG, "Removing preferred activity since set changed "
4716                                            + pa.mPref.mComponent);
4717                                }
4718                                pir.removeFilter(pa);
4719                                // Re-add the filter as a "last chosen" entry (!always)
4720                                PreferredActivity lastChosen = new PreferredActivity(
4721                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4722                                pir.addFilter(lastChosen);
4723                                changed = true;
4724                                return null;
4725                            }
4726
4727                            // Yay! Either the set matched or we're looking for the last chosen
4728                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4729                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4730                            return ri;
4731                        }
4732                    }
4733                } finally {
4734                    if (changed) {
4735                        if (DEBUG_PREFERRED) {
4736                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4737                        }
4738                        scheduleWritePackageRestrictionsLocked(userId);
4739                    }
4740                }
4741            }
4742        }
4743        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4744        return null;
4745    }
4746
4747    /*
4748     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4749     */
4750    @Override
4751    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4752            int targetUserId) {
4753        mContext.enforceCallingOrSelfPermission(
4754                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4755        List<CrossProfileIntentFilter> matches =
4756                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4757        if (matches != null) {
4758            int size = matches.size();
4759            for (int i = 0; i < size; i++) {
4760                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4761            }
4762        }
4763        if (hasWebURI(intent)) {
4764            // cross-profile app linking works only towards the parent.
4765            final UserInfo parent = getProfileParent(sourceUserId);
4766            synchronized(mPackages) {
4767                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4768                        intent, resolvedType, 0, sourceUserId, parent.id);
4769                return xpDomainInfo != null;
4770            }
4771        }
4772        return false;
4773    }
4774
4775    private UserInfo getProfileParent(int userId) {
4776        final long identity = Binder.clearCallingIdentity();
4777        try {
4778            return sUserManager.getProfileParent(userId);
4779        } finally {
4780            Binder.restoreCallingIdentity(identity);
4781        }
4782    }
4783
4784    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4785            String resolvedType, int userId) {
4786        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4787        if (resolver != null) {
4788            return resolver.queryIntent(intent, resolvedType, false, userId);
4789        }
4790        return null;
4791    }
4792
4793    @Override
4794    public List<ResolveInfo> queryIntentActivities(Intent intent,
4795            String resolvedType, int flags, int userId) {
4796        if (!sUserManager.exists(userId)) return Collections.emptyList();
4797        flags = augmentFlagsForUser(flags, userId);
4798        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4799        ComponentName comp = intent.getComponent();
4800        if (comp == null) {
4801            if (intent.getSelector() != null) {
4802                intent = intent.getSelector();
4803                comp = intent.getComponent();
4804            }
4805        }
4806
4807        if (comp != null) {
4808            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4809            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4810            if (ai != null) {
4811                final ResolveInfo ri = new ResolveInfo();
4812                ri.activityInfo = ai;
4813                list.add(ri);
4814            }
4815            return list;
4816        }
4817
4818        // reader
4819        synchronized (mPackages) {
4820            final String pkgName = intent.getPackage();
4821            if (pkgName == null) {
4822                List<CrossProfileIntentFilter> matchingFilters =
4823                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4824                // Check for results that need to skip the current profile.
4825                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4826                        resolvedType, flags, userId);
4827                if (xpResolveInfo != null) {
4828                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4829                    result.add(xpResolveInfo);
4830                    return filterIfNotSystemUser(result, userId);
4831                }
4832
4833                // Check for results in the current profile.
4834                List<ResolveInfo> result = mActivities.queryIntent(
4835                        intent, resolvedType, flags, userId);
4836                result = filterIfNotSystemUser(result, userId);
4837
4838                // Check for cross profile results.
4839                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4840                xpResolveInfo = queryCrossProfileIntents(
4841                        matchingFilters, intent, resolvedType, flags, userId,
4842                        hasNonNegativePriorityResult);
4843                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4844                    boolean isVisibleToUser = filterIfNotSystemUser(
4845                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4846                    if (isVisibleToUser) {
4847                        result.add(xpResolveInfo);
4848                        Collections.sort(result, mResolvePrioritySorter);
4849                    }
4850                }
4851                if (hasWebURI(intent)) {
4852                    CrossProfileDomainInfo xpDomainInfo = null;
4853                    final UserInfo parent = getProfileParent(userId);
4854                    if (parent != null) {
4855                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4856                                flags, userId, parent.id);
4857                    }
4858                    if (xpDomainInfo != null) {
4859                        if (xpResolveInfo != null) {
4860                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4861                            // in the result.
4862                            result.remove(xpResolveInfo);
4863                        }
4864                        if (result.size() == 0) {
4865                            result.add(xpDomainInfo.resolveInfo);
4866                            return result;
4867                        }
4868                    } else if (result.size() <= 1) {
4869                        return result;
4870                    }
4871                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4872                            xpDomainInfo, userId);
4873                    Collections.sort(result, mResolvePrioritySorter);
4874                }
4875                return result;
4876            }
4877            final PackageParser.Package pkg = mPackages.get(pkgName);
4878            if (pkg != null) {
4879                return filterIfNotSystemUser(
4880                        mActivities.queryIntentForPackage(
4881                                intent, resolvedType, flags, pkg.activities, userId),
4882                        userId);
4883            }
4884            return new ArrayList<ResolveInfo>();
4885        }
4886    }
4887
4888    private static class CrossProfileDomainInfo {
4889        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4890        ResolveInfo resolveInfo;
4891        /* Best domain verification status of the activities found in the other profile */
4892        int bestDomainVerificationStatus;
4893    }
4894
4895    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4896            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4897        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4898                sourceUserId)) {
4899            return null;
4900        }
4901        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4902                resolvedType, flags, parentUserId);
4903
4904        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4905            return null;
4906        }
4907        CrossProfileDomainInfo result = null;
4908        int size = resultTargetUser.size();
4909        for (int i = 0; i < size; i++) {
4910            ResolveInfo riTargetUser = resultTargetUser.get(i);
4911            // Intent filter verification is only for filters that specify a host. So don't return
4912            // those that handle all web uris.
4913            if (riTargetUser.handleAllWebDataURI) {
4914                continue;
4915            }
4916            String packageName = riTargetUser.activityInfo.packageName;
4917            PackageSetting ps = mSettings.mPackages.get(packageName);
4918            if (ps == null) {
4919                continue;
4920            }
4921            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4922            int status = (int)(verificationState >> 32);
4923            if (result == null) {
4924                result = new CrossProfileDomainInfo();
4925                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4926                        sourceUserId, parentUserId);
4927                result.bestDomainVerificationStatus = status;
4928            } else {
4929                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4930                        result.bestDomainVerificationStatus);
4931            }
4932        }
4933        // Don't consider matches with status NEVER across profiles.
4934        if (result != null && result.bestDomainVerificationStatus
4935                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4936            return null;
4937        }
4938        return result;
4939    }
4940
4941    /**
4942     * Verification statuses are ordered from the worse to the best, except for
4943     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4944     */
4945    private int bestDomainVerificationStatus(int status1, int status2) {
4946        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4947            return status2;
4948        }
4949        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4950            return status1;
4951        }
4952        return (int) MathUtils.max(status1, status2);
4953    }
4954
4955    private boolean isUserEnabled(int userId) {
4956        long callingId = Binder.clearCallingIdentity();
4957        try {
4958            UserInfo userInfo = sUserManager.getUserInfo(userId);
4959            return userInfo != null && userInfo.isEnabled();
4960        } finally {
4961            Binder.restoreCallingIdentity(callingId);
4962        }
4963    }
4964
4965    /**
4966     * Filter out activities with systemUserOnly flag set, when current user is not System.
4967     *
4968     * @return filtered list
4969     */
4970    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4971        if (userId == UserHandle.USER_SYSTEM) {
4972            return resolveInfos;
4973        }
4974        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4975            ResolveInfo info = resolveInfos.get(i);
4976            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4977                resolveInfos.remove(i);
4978            }
4979        }
4980        return resolveInfos;
4981    }
4982
4983    /**
4984     * @param resolveInfos list of resolve infos in descending priority order
4985     * @return if the list contains a resolve info with non-negative priority
4986     */
4987    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
4988        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
4989    }
4990
4991    private static boolean hasWebURI(Intent intent) {
4992        if (intent.getData() == null) {
4993            return false;
4994        }
4995        final String scheme = intent.getScheme();
4996        if (TextUtils.isEmpty(scheme)) {
4997            return false;
4998        }
4999        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5000    }
5001
5002    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5003            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5004            int userId) {
5005        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5006
5007        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5008            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5009                    candidates.size());
5010        }
5011
5012        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5013        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5014        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5015        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5016        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5017        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5018
5019        synchronized (mPackages) {
5020            final int count = candidates.size();
5021            // First, try to use linked apps. Partition the candidates into four lists:
5022            // one for the final results, one for the "do not use ever", one for "undefined status"
5023            // and finally one for "browser app type".
5024            for (int n=0; n<count; n++) {
5025                ResolveInfo info = candidates.get(n);
5026                String packageName = info.activityInfo.packageName;
5027                PackageSetting ps = mSettings.mPackages.get(packageName);
5028                if (ps != null) {
5029                    // Add to the special match all list (Browser use case)
5030                    if (info.handleAllWebDataURI) {
5031                        matchAllList.add(info);
5032                        continue;
5033                    }
5034                    // Try to get the status from User settings first
5035                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5036                    int status = (int)(packedStatus >> 32);
5037                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5038                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5039                        if (DEBUG_DOMAIN_VERIFICATION) {
5040                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5041                                    + " : linkgen=" + linkGeneration);
5042                        }
5043                        // Use link-enabled generation as preferredOrder, i.e.
5044                        // prefer newly-enabled over earlier-enabled.
5045                        info.preferredOrder = linkGeneration;
5046                        alwaysList.add(info);
5047                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5048                        if (DEBUG_DOMAIN_VERIFICATION) {
5049                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5050                        }
5051                        neverList.add(info);
5052                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5053                        if (DEBUG_DOMAIN_VERIFICATION) {
5054                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5055                        }
5056                        alwaysAskList.add(info);
5057                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5058                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5059                        if (DEBUG_DOMAIN_VERIFICATION) {
5060                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5061                        }
5062                        undefinedList.add(info);
5063                    }
5064                }
5065            }
5066
5067            // We'll want to include browser possibilities in a few cases
5068            boolean includeBrowser = false;
5069
5070            // First try to add the "always" resolution(s) for the current user, if any
5071            if (alwaysList.size() > 0) {
5072                result.addAll(alwaysList);
5073            } else {
5074                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5075                result.addAll(undefinedList);
5076                // Maybe add one for the other profile.
5077                if (xpDomainInfo != null && (
5078                        xpDomainInfo.bestDomainVerificationStatus
5079                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5080                    result.add(xpDomainInfo.resolveInfo);
5081                }
5082                includeBrowser = true;
5083            }
5084
5085            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5086            // If there were 'always' entries their preferred order has been set, so we also
5087            // back that off to make the alternatives equivalent
5088            if (alwaysAskList.size() > 0) {
5089                for (ResolveInfo i : result) {
5090                    i.preferredOrder = 0;
5091                }
5092                result.addAll(alwaysAskList);
5093                includeBrowser = true;
5094            }
5095
5096            if (includeBrowser) {
5097                // Also add browsers (all of them or only the default one)
5098                if (DEBUG_DOMAIN_VERIFICATION) {
5099                    Slog.v(TAG, "   ...including browsers in candidate set");
5100                }
5101                if ((matchFlags & MATCH_ALL) != 0) {
5102                    result.addAll(matchAllList);
5103                } else {
5104                    // Browser/generic handling case.  If there's a default browser, go straight
5105                    // to that (but only if there is no other higher-priority match).
5106                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5107                    int maxMatchPrio = 0;
5108                    ResolveInfo defaultBrowserMatch = null;
5109                    final int numCandidates = matchAllList.size();
5110                    for (int n = 0; n < numCandidates; n++) {
5111                        ResolveInfo info = matchAllList.get(n);
5112                        // track the highest overall match priority...
5113                        if (info.priority > maxMatchPrio) {
5114                            maxMatchPrio = info.priority;
5115                        }
5116                        // ...and the highest-priority default browser match
5117                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5118                            if (defaultBrowserMatch == null
5119                                    || (defaultBrowserMatch.priority < info.priority)) {
5120                                if (debug) {
5121                                    Slog.v(TAG, "Considering default browser match " + info);
5122                                }
5123                                defaultBrowserMatch = info;
5124                            }
5125                        }
5126                    }
5127                    if (defaultBrowserMatch != null
5128                            && defaultBrowserMatch.priority >= maxMatchPrio
5129                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5130                    {
5131                        if (debug) {
5132                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5133                        }
5134                        result.add(defaultBrowserMatch);
5135                    } else {
5136                        result.addAll(matchAllList);
5137                    }
5138                }
5139
5140                // If there is nothing selected, add all candidates and remove the ones that the user
5141                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5142                if (result.size() == 0) {
5143                    result.addAll(candidates);
5144                    result.removeAll(neverList);
5145                }
5146            }
5147        }
5148        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5149            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5150                    result.size());
5151            for (ResolveInfo info : result) {
5152                Slog.v(TAG, "  + " + info.activityInfo);
5153            }
5154        }
5155        return result;
5156    }
5157
5158    // Returns a packed value as a long:
5159    //
5160    // high 'int'-sized word: link status: undefined/ask/never/always.
5161    // low 'int'-sized word: relative priority among 'always' results.
5162    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5163        long result = ps.getDomainVerificationStatusForUser(userId);
5164        // if none available, get the master status
5165        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5166            if (ps.getIntentFilterVerificationInfo() != null) {
5167                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5168            }
5169        }
5170        return result;
5171    }
5172
5173    private ResolveInfo querySkipCurrentProfileIntents(
5174            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5175            int flags, int sourceUserId) {
5176        if (matchingFilters != null) {
5177            int size = matchingFilters.size();
5178            for (int i = 0; i < size; i ++) {
5179                CrossProfileIntentFilter filter = matchingFilters.get(i);
5180                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5181                    // Checking if there are activities in the target user that can handle the
5182                    // intent.
5183                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5184                            resolvedType, flags, sourceUserId);
5185                    if (resolveInfo != null) {
5186                        return resolveInfo;
5187                    }
5188                }
5189            }
5190        }
5191        return null;
5192    }
5193
5194    // Return matching ResolveInfo in target user if any.
5195    private ResolveInfo queryCrossProfileIntents(
5196            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5197            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5198        if (matchingFilters != null) {
5199            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5200            // match the same intent. For performance reasons, it is better not to
5201            // run queryIntent twice for the same userId
5202            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5203            int size = matchingFilters.size();
5204            for (int i = 0; i < size; i++) {
5205                CrossProfileIntentFilter filter = matchingFilters.get(i);
5206                int targetUserId = filter.getTargetUserId();
5207                boolean skipCurrentProfile =
5208                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5209                boolean skipCurrentProfileIfNoMatchFound =
5210                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5211                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5212                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5213                    // Checking if there are activities in the target user that can handle the
5214                    // intent.
5215                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5216                            resolvedType, flags, sourceUserId);
5217                    if (resolveInfo != null) return resolveInfo;
5218                    alreadyTriedUserIds.put(targetUserId, true);
5219                }
5220            }
5221        }
5222        return null;
5223    }
5224
5225    /**
5226     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5227     * will forward the intent to the filter's target user.
5228     * Otherwise, returns null.
5229     */
5230    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5231            String resolvedType, int flags, int sourceUserId) {
5232        int targetUserId = filter.getTargetUserId();
5233        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5234                resolvedType, flags, targetUserId);
5235        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5236                && isUserEnabled(targetUserId)) {
5237            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5238        }
5239        return null;
5240    }
5241
5242    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5243            int sourceUserId, int targetUserId) {
5244        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5245        long ident = Binder.clearCallingIdentity();
5246        boolean targetIsProfile;
5247        try {
5248            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5249        } finally {
5250            Binder.restoreCallingIdentity(ident);
5251        }
5252        String className;
5253        if (targetIsProfile) {
5254            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5255        } else {
5256            className = FORWARD_INTENT_TO_PARENT;
5257        }
5258        ComponentName forwardingActivityComponentName = new ComponentName(
5259                mAndroidApplication.packageName, className);
5260        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5261                sourceUserId);
5262        if (!targetIsProfile) {
5263            forwardingActivityInfo.showUserIcon = targetUserId;
5264            forwardingResolveInfo.noResourceId = true;
5265        }
5266        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5267        forwardingResolveInfo.priority = 0;
5268        forwardingResolveInfo.preferredOrder = 0;
5269        forwardingResolveInfo.match = 0;
5270        forwardingResolveInfo.isDefault = true;
5271        forwardingResolveInfo.filter = filter;
5272        forwardingResolveInfo.targetUserId = targetUserId;
5273        return forwardingResolveInfo;
5274    }
5275
5276    @Override
5277    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5278            Intent[] specifics, String[] specificTypes, Intent intent,
5279            String resolvedType, int flags, int userId) {
5280        if (!sUserManager.exists(userId)) return Collections.emptyList();
5281        flags = augmentFlagsForUser(flags, userId);
5282        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5283                false, "query intent activity options");
5284        final String resultsAction = intent.getAction();
5285
5286        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5287                | PackageManager.GET_RESOLVED_FILTER, userId);
5288
5289        if (DEBUG_INTENT_MATCHING) {
5290            Log.v(TAG, "Query " + intent + ": " + results);
5291        }
5292
5293        int specificsPos = 0;
5294        int N;
5295
5296        // todo: note that the algorithm used here is O(N^2).  This
5297        // isn't a problem in our current environment, but if we start running
5298        // into situations where we have more than 5 or 10 matches then this
5299        // should probably be changed to something smarter...
5300
5301        // First we go through and resolve each of the specific items
5302        // that were supplied, taking care of removing any corresponding
5303        // duplicate items in the generic resolve list.
5304        if (specifics != null) {
5305            for (int i=0; i<specifics.length; i++) {
5306                final Intent sintent = specifics[i];
5307                if (sintent == null) {
5308                    continue;
5309                }
5310
5311                if (DEBUG_INTENT_MATCHING) {
5312                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5313                }
5314
5315                String action = sintent.getAction();
5316                if (resultsAction != null && resultsAction.equals(action)) {
5317                    // If this action was explicitly requested, then don't
5318                    // remove things that have it.
5319                    action = null;
5320                }
5321
5322                ResolveInfo ri = null;
5323                ActivityInfo ai = null;
5324
5325                ComponentName comp = sintent.getComponent();
5326                if (comp == null) {
5327                    ri = resolveIntent(
5328                        sintent,
5329                        specificTypes != null ? specificTypes[i] : null,
5330                            flags, userId);
5331                    if (ri == null) {
5332                        continue;
5333                    }
5334                    if (ri == mResolveInfo) {
5335                        // ACK!  Must do something better with this.
5336                    }
5337                    ai = ri.activityInfo;
5338                    comp = new ComponentName(ai.applicationInfo.packageName,
5339                            ai.name);
5340                } else {
5341                    ai = getActivityInfo(comp, flags, userId);
5342                    if (ai == null) {
5343                        continue;
5344                    }
5345                }
5346
5347                // Look for any generic query activities that are duplicates
5348                // of this specific one, and remove them from the results.
5349                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5350                N = results.size();
5351                int j;
5352                for (j=specificsPos; j<N; j++) {
5353                    ResolveInfo sri = results.get(j);
5354                    if ((sri.activityInfo.name.equals(comp.getClassName())
5355                            && sri.activityInfo.applicationInfo.packageName.equals(
5356                                    comp.getPackageName()))
5357                        || (action != null && sri.filter.matchAction(action))) {
5358                        results.remove(j);
5359                        if (DEBUG_INTENT_MATCHING) Log.v(
5360                            TAG, "Removing duplicate item from " + j
5361                            + " due to specific " + specificsPos);
5362                        if (ri == null) {
5363                            ri = sri;
5364                        }
5365                        j--;
5366                        N--;
5367                    }
5368                }
5369
5370                // Add this specific item to its proper place.
5371                if (ri == null) {
5372                    ri = new ResolveInfo();
5373                    ri.activityInfo = ai;
5374                }
5375                results.add(specificsPos, ri);
5376                ri.specificIndex = i;
5377                specificsPos++;
5378            }
5379        }
5380
5381        // Now we go through the remaining generic results and remove any
5382        // duplicate actions that are found here.
5383        N = results.size();
5384        for (int i=specificsPos; i<N-1; i++) {
5385            final ResolveInfo rii = results.get(i);
5386            if (rii.filter == null) {
5387                continue;
5388            }
5389
5390            // Iterate over all of the actions of this result's intent
5391            // filter...  typically this should be just one.
5392            final Iterator<String> it = rii.filter.actionsIterator();
5393            if (it == null) {
5394                continue;
5395            }
5396            while (it.hasNext()) {
5397                final String action = it.next();
5398                if (resultsAction != null && resultsAction.equals(action)) {
5399                    // If this action was explicitly requested, then don't
5400                    // remove things that have it.
5401                    continue;
5402                }
5403                for (int j=i+1; j<N; j++) {
5404                    final ResolveInfo rij = results.get(j);
5405                    if (rij.filter != null && rij.filter.hasAction(action)) {
5406                        results.remove(j);
5407                        if (DEBUG_INTENT_MATCHING) Log.v(
5408                            TAG, "Removing duplicate item from " + j
5409                            + " due to action " + action + " at " + i);
5410                        j--;
5411                        N--;
5412                    }
5413                }
5414            }
5415
5416            // If the caller didn't request filter information, drop it now
5417            // so we don't have to marshall/unmarshall it.
5418            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5419                rii.filter = null;
5420            }
5421        }
5422
5423        // Filter out the caller activity if so requested.
5424        if (caller != null) {
5425            N = results.size();
5426            for (int i=0; i<N; i++) {
5427                ActivityInfo ainfo = results.get(i).activityInfo;
5428                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5429                        && caller.getClassName().equals(ainfo.name)) {
5430                    results.remove(i);
5431                    break;
5432                }
5433            }
5434        }
5435
5436        // If the caller didn't request filter information,
5437        // drop them now so we don't have to
5438        // marshall/unmarshall it.
5439        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5440            N = results.size();
5441            for (int i=0; i<N; i++) {
5442                results.get(i).filter = null;
5443            }
5444        }
5445
5446        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5447        return results;
5448    }
5449
5450    @Override
5451    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5452            int userId) {
5453        if (!sUserManager.exists(userId)) return Collections.emptyList();
5454        flags = augmentFlagsForUser(flags, userId);
5455        ComponentName comp = intent.getComponent();
5456        if (comp == null) {
5457            if (intent.getSelector() != null) {
5458                intent = intent.getSelector();
5459                comp = intent.getComponent();
5460            }
5461        }
5462        if (comp != null) {
5463            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5464            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5465            if (ai != null) {
5466                ResolveInfo ri = new ResolveInfo();
5467                ri.activityInfo = ai;
5468                list.add(ri);
5469            }
5470            return list;
5471        }
5472
5473        // reader
5474        synchronized (mPackages) {
5475            String pkgName = intent.getPackage();
5476            if (pkgName == null) {
5477                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5478            }
5479            final PackageParser.Package pkg = mPackages.get(pkgName);
5480            if (pkg != null) {
5481                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5482                        userId);
5483            }
5484            return null;
5485        }
5486    }
5487
5488    @Override
5489    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5490        if (!sUserManager.exists(userId)) return null;
5491        flags = augmentFlagsForUser(flags, userId);
5492        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5493        if (query != null) {
5494            if (query.size() >= 1) {
5495                // If there is more than one service with the same priority,
5496                // just arbitrarily pick the first one.
5497                return query.get(0);
5498            }
5499        }
5500        return null;
5501    }
5502
5503    @Override
5504    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5505            int userId) {
5506        if (!sUserManager.exists(userId)) return Collections.emptyList();
5507        flags = augmentFlagsForUser(flags, userId);
5508        ComponentName comp = intent.getComponent();
5509        if (comp == null) {
5510            if (intent.getSelector() != null) {
5511                intent = intent.getSelector();
5512                comp = intent.getComponent();
5513            }
5514        }
5515        if (comp != null) {
5516            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5517            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5518            if (si != null) {
5519                final ResolveInfo ri = new ResolveInfo();
5520                ri.serviceInfo = si;
5521                list.add(ri);
5522            }
5523            return list;
5524        }
5525
5526        // reader
5527        synchronized (mPackages) {
5528            String pkgName = intent.getPackage();
5529            if (pkgName == null) {
5530                return mServices.queryIntent(intent, resolvedType, flags, userId);
5531            }
5532            final PackageParser.Package pkg = mPackages.get(pkgName);
5533            if (pkg != null) {
5534                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5535                        userId);
5536            }
5537            return null;
5538        }
5539    }
5540
5541    @Override
5542    public List<ResolveInfo> queryIntentContentProviders(
5543            Intent intent, String resolvedType, int flags, int userId) {
5544        if (!sUserManager.exists(userId)) return Collections.emptyList();
5545        flags = augmentFlagsForUser(flags, userId);
5546        ComponentName comp = intent.getComponent();
5547        if (comp == null) {
5548            if (intent.getSelector() != null) {
5549                intent = intent.getSelector();
5550                comp = intent.getComponent();
5551            }
5552        }
5553        if (comp != null) {
5554            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5555            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5556            if (pi != null) {
5557                final ResolveInfo ri = new ResolveInfo();
5558                ri.providerInfo = pi;
5559                list.add(ri);
5560            }
5561            return list;
5562        }
5563
5564        // reader
5565        synchronized (mPackages) {
5566            String pkgName = intent.getPackage();
5567            if (pkgName == null) {
5568                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5569            }
5570            final PackageParser.Package pkg = mPackages.get(pkgName);
5571            if (pkg != null) {
5572                return mProviders.queryIntentForPackage(
5573                        intent, resolvedType, flags, pkg.providers, userId);
5574            }
5575            return null;
5576        }
5577    }
5578
5579    @Override
5580    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5581        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5582
5583        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5584
5585        // writer
5586        synchronized (mPackages) {
5587            ArrayList<PackageInfo> list;
5588            if (listUninstalled) {
5589                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5590                for (PackageSetting ps : mSettings.mPackages.values()) {
5591                    PackageInfo pi;
5592                    if (ps.pkg != null) {
5593                        pi = generatePackageInfo(ps.pkg, flags, userId);
5594                    } else {
5595                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5596                    }
5597                    if (pi != null) {
5598                        list.add(pi);
5599                    }
5600                }
5601            } else {
5602                list = new ArrayList<PackageInfo>(mPackages.size());
5603                for (PackageParser.Package p : mPackages.values()) {
5604                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5605                    if (pi != null) {
5606                        list.add(pi);
5607                    }
5608                }
5609            }
5610
5611            return new ParceledListSlice<PackageInfo>(list);
5612        }
5613    }
5614
5615    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5616            String[] permissions, boolean[] tmp, int flags, int userId) {
5617        int numMatch = 0;
5618        final PermissionsState permissionsState = ps.getPermissionsState();
5619        for (int i=0; i<permissions.length; i++) {
5620            final String permission = permissions[i];
5621            if (permissionsState.hasPermission(permission, userId)) {
5622                tmp[i] = true;
5623                numMatch++;
5624            } else {
5625                tmp[i] = false;
5626            }
5627        }
5628        if (numMatch == 0) {
5629            return;
5630        }
5631        PackageInfo pi;
5632        if (ps.pkg != null) {
5633            pi = generatePackageInfo(ps.pkg, flags, userId);
5634        } else {
5635            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5636        }
5637        // The above might return null in cases of uninstalled apps or install-state
5638        // skew across users/profiles.
5639        if (pi != null) {
5640            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5641                if (numMatch == permissions.length) {
5642                    pi.requestedPermissions = permissions;
5643                } else {
5644                    pi.requestedPermissions = new String[numMatch];
5645                    numMatch = 0;
5646                    for (int i=0; i<permissions.length; i++) {
5647                        if (tmp[i]) {
5648                            pi.requestedPermissions[numMatch] = permissions[i];
5649                            numMatch++;
5650                        }
5651                    }
5652                }
5653            }
5654            list.add(pi);
5655        }
5656    }
5657
5658    @Override
5659    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5660            String[] permissions, int flags, int userId) {
5661        if (!sUserManager.exists(userId)) return null;
5662        flags = augmentFlagsForUser(flags, userId);
5663        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5664
5665        // writer
5666        synchronized (mPackages) {
5667            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5668            boolean[] tmpBools = new boolean[permissions.length];
5669            if (listUninstalled) {
5670                for (PackageSetting ps : mSettings.mPackages.values()) {
5671                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5672                }
5673            } else {
5674                for (PackageParser.Package pkg : mPackages.values()) {
5675                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5676                    if (ps != null) {
5677                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5678                                userId);
5679                    }
5680                }
5681            }
5682
5683            return new ParceledListSlice<PackageInfo>(list);
5684        }
5685    }
5686
5687    @Override
5688    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5689        if (!sUserManager.exists(userId)) return null;
5690        flags = augmentFlagsForUser(flags, userId);
5691        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5692
5693        // writer
5694        synchronized (mPackages) {
5695            ArrayList<ApplicationInfo> list;
5696            if (listUninstalled) {
5697                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5698                for (PackageSetting ps : mSettings.mPackages.values()) {
5699                    ApplicationInfo ai;
5700                    if (ps.pkg != null) {
5701                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5702                                ps.readUserState(userId), userId);
5703                    } else {
5704                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5705                    }
5706                    if (ai != null) {
5707                        list.add(ai);
5708                    }
5709                }
5710            } else {
5711                list = new ArrayList<ApplicationInfo>(mPackages.size());
5712                for (PackageParser.Package p : mPackages.values()) {
5713                    if (p.mExtras != null) {
5714                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5715                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5716                        if (ai != null) {
5717                            list.add(ai);
5718                        }
5719                    }
5720                }
5721            }
5722
5723            return new ParceledListSlice<ApplicationInfo>(list);
5724        }
5725    }
5726
5727    public List<ApplicationInfo> getPersistentApplications(int flags) {
5728        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5729
5730        // reader
5731        synchronized (mPackages) {
5732            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5733            final int userId = UserHandle.getCallingUserId();
5734            while (i.hasNext()) {
5735                final PackageParser.Package p = i.next();
5736                if (p.applicationInfo != null
5737                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5738                        && (!mSafeMode || isSystemApp(p))) {
5739                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5740                    if (ps != null) {
5741                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5742                                ps.readUserState(userId), userId);
5743                        if (ai != null) {
5744                            finalList.add(ai);
5745                        }
5746                    }
5747                }
5748            }
5749        }
5750
5751        return finalList;
5752    }
5753
5754    @Override
5755    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5756        if (!sUserManager.exists(userId)) return null;
5757        flags = augmentFlagsForUser(flags, userId);
5758        // reader
5759        synchronized (mPackages) {
5760            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5761            PackageSetting ps = provider != null
5762                    ? mSettings.mPackages.get(provider.owner.packageName)
5763                    : null;
5764            return ps != null
5765                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5766                    && (!mSafeMode || (provider.info.applicationInfo.flags
5767                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5768                    ? PackageParser.generateProviderInfo(provider, flags,
5769                            ps.readUserState(userId), userId)
5770                    : null;
5771        }
5772    }
5773
5774    /**
5775     * @deprecated
5776     */
5777    @Deprecated
5778    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5779        // reader
5780        synchronized (mPackages) {
5781            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5782                    .entrySet().iterator();
5783            final int userId = UserHandle.getCallingUserId();
5784            while (i.hasNext()) {
5785                Map.Entry<String, PackageParser.Provider> entry = i.next();
5786                PackageParser.Provider p = entry.getValue();
5787                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5788
5789                if (ps != null && p.syncable
5790                        && (!mSafeMode || (p.info.applicationInfo.flags
5791                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5792                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5793                            ps.readUserState(userId), userId);
5794                    if (info != null) {
5795                        outNames.add(entry.getKey());
5796                        outInfo.add(info);
5797                    }
5798                }
5799            }
5800        }
5801    }
5802
5803    @Override
5804    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5805            int uid, int flags) {
5806        final int userId = processName != null ? UserHandle.getUserId(uid)
5807                : UserHandle.getCallingUserId();
5808        if (!sUserManager.exists(userId)) return null;
5809        flags = augmentFlagsForUser(flags, userId);
5810
5811        ArrayList<ProviderInfo> finalList = null;
5812        // reader
5813        synchronized (mPackages) {
5814            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5815            while (i.hasNext()) {
5816                final PackageParser.Provider p = i.next();
5817                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5818                if (ps != null && p.info.authority != null
5819                        && (processName == null
5820                                || (p.info.processName.equals(processName)
5821                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5822                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5823                        && (!mSafeMode
5824                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5825                    if (finalList == null) {
5826                        finalList = new ArrayList<ProviderInfo>(3);
5827                    }
5828                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5829                            ps.readUserState(userId), userId);
5830                    if (info != null) {
5831                        finalList.add(info);
5832                    }
5833                }
5834            }
5835        }
5836
5837        if (finalList != null) {
5838            Collections.sort(finalList, mProviderInitOrderSorter);
5839            return new ParceledListSlice<ProviderInfo>(finalList);
5840        }
5841
5842        return null;
5843    }
5844
5845    @Override
5846    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5847            int flags) {
5848        // reader
5849        synchronized (mPackages) {
5850            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5851            return PackageParser.generateInstrumentationInfo(i, flags);
5852        }
5853    }
5854
5855    @Override
5856    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5857            int flags) {
5858        ArrayList<InstrumentationInfo> finalList =
5859            new ArrayList<InstrumentationInfo>();
5860
5861        // reader
5862        synchronized (mPackages) {
5863            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5864            while (i.hasNext()) {
5865                final PackageParser.Instrumentation p = i.next();
5866                if (targetPackage == null
5867                        || targetPackage.equals(p.info.targetPackage)) {
5868                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5869                            flags);
5870                    if (ii != null) {
5871                        finalList.add(ii);
5872                    }
5873                }
5874            }
5875        }
5876
5877        return finalList;
5878    }
5879
5880    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5881        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5882        if (overlays == null) {
5883            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5884            return;
5885        }
5886        for (PackageParser.Package opkg : overlays.values()) {
5887            // Not much to do if idmap fails: we already logged the error
5888            // and we certainly don't want to abort installation of pkg simply
5889            // because an overlay didn't fit properly. For these reasons,
5890            // ignore the return value of createIdmapForPackagePairLI.
5891            createIdmapForPackagePairLI(pkg, opkg);
5892        }
5893    }
5894
5895    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5896            PackageParser.Package opkg) {
5897        if (!opkg.mTrustedOverlay) {
5898            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5899                    opkg.baseCodePath + ": overlay not trusted");
5900            return false;
5901        }
5902        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5903        if (overlaySet == null) {
5904            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5905                    opkg.baseCodePath + " but target package has no known overlays");
5906            return false;
5907        }
5908        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5909        // TODO: generate idmap for split APKs
5910        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5911            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5912                    + opkg.baseCodePath);
5913            return false;
5914        }
5915        PackageParser.Package[] overlayArray =
5916            overlaySet.values().toArray(new PackageParser.Package[0]);
5917        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5918            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5919                return p1.mOverlayPriority - p2.mOverlayPriority;
5920            }
5921        };
5922        Arrays.sort(overlayArray, cmp);
5923
5924        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5925        int i = 0;
5926        for (PackageParser.Package p : overlayArray) {
5927            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5928        }
5929        return true;
5930    }
5931
5932    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5934        try {
5935            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5936        } finally {
5937            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5938        }
5939    }
5940
5941    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5942        final File[] files = dir.listFiles();
5943        if (ArrayUtils.isEmpty(files)) {
5944            Log.d(TAG, "No files in app dir " + dir);
5945            return;
5946        }
5947
5948        if (DEBUG_PACKAGE_SCANNING) {
5949            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5950                    + " flags=0x" + Integer.toHexString(parseFlags));
5951        }
5952
5953        for (File file : files) {
5954            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5955                    && !PackageInstallerService.isStageName(file.getName());
5956            if (!isPackage) {
5957                // Ignore entries which are not packages
5958                continue;
5959            }
5960            try {
5961                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5962                        scanFlags, currentTime, null);
5963            } catch (PackageManagerException e) {
5964                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5965
5966                // Delete invalid userdata apps
5967                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5968                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5969                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5970                    if (file.isDirectory()) {
5971                        mInstaller.rmPackageDir(file.getAbsolutePath());
5972                    } else {
5973                        file.delete();
5974                    }
5975                }
5976            }
5977        }
5978    }
5979
5980    private static File getSettingsProblemFile() {
5981        File dataDir = Environment.getDataDirectory();
5982        File systemDir = new File(dataDir, "system");
5983        File fname = new File(systemDir, "uiderrors.txt");
5984        return fname;
5985    }
5986
5987    static void reportSettingsProblem(int priority, String msg) {
5988        logCriticalInfo(priority, msg);
5989    }
5990
5991    static void logCriticalInfo(int priority, String msg) {
5992        Slog.println(priority, TAG, msg);
5993        EventLogTags.writePmCriticalInfo(msg);
5994        try {
5995            File fname = getSettingsProblemFile();
5996            FileOutputStream out = new FileOutputStream(fname, true);
5997            PrintWriter pw = new FastPrintWriter(out);
5998            SimpleDateFormat formatter = new SimpleDateFormat();
5999            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6000            pw.println(dateString + ": " + msg);
6001            pw.close();
6002            FileUtils.setPermissions(
6003                    fname.toString(),
6004                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6005                    -1, -1);
6006        } catch (java.io.IOException e) {
6007        }
6008    }
6009
6010    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6011            PackageParser.Package pkg, File srcFile, int parseFlags)
6012            throws PackageManagerException {
6013        if (ps != null
6014                && ps.codePath.equals(srcFile)
6015                && ps.timeStamp == srcFile.lastModified()
6016                && !isCompatSignatureUpdateNeeded(pkg)
6017                && !isRecoverSignatureUpdateNeeded(pkg)) {
6018            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6019            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6020            ArraySet<PublicKey> signingKs;
6021            synchronized (mPackages) {
6022                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6023            }
6024            if (ps.signatures.mSignatures != null
6025                    && ps.signatures.mSignatures.length != 0
6026                    && signingKs != null) {
6027                // Optimization: reuse the existing cached certificates
6028                // if the package appears to be unchanged.
6029                pkg.mSignatures = ps.signatures.mSignatures;
6030                pkg.mSigningKeys = signingKs;
6031                return;
6032            }
6033
6034            Slog.w(TAG, "PackageSetting for " + ps.name
6035                    + " is missing signatures.  Collecting certs again to recover them.");
6036        } else {
6037            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6038        }
6039
6040        try {
6041            pp.collectCertificates(pkg, parseFlags);
6042            pp.collectManifestDigest(pkg);
6043        } catch (PackageParserException e) {
6044            throw PackageManagerException.from(e);
6045        }
6046    }
6047
6048    /**
6049     *  Traces a package scan.
6050     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6051     */
6052    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6053            long currentTime, UserHandle user) throws PackageManagerException {
6054        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6055        try {
6056            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6057        } finally {
6058            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6059        }
6060    }
6061
6062    /**
6063     *  Scans a package and returns the newly parsed package.
6064     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6065     */
6066    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6067            long currentTime, UserHandle user) throws PackageManagerException {
6068        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6069        parseFlags |= mDefParseFlags;
6070        PackageParser pp = new PackageParser();
6071        pp.setSeparateProcesses(mSeparateProcesses);
6072        pp.setOnlyCoreApps(mOnlyCore);
6073        pp.setDisplayMetrics(mMetrics);
6074
6075        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6076            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6077        }
6078
6079        final PackageParser.Package pkg;
6080        try {
6081            pkg = pp.parsePackage(scanFile, parseFlags);
6082        } catch (PackageParserException e) {
6083            throw PackageManagerException.from(e);
6084        }
6085
6086        PackageSetting ps = null;
6087        PackageSetting updatedPkg;
6088        // reader
6089        synchronized (mPackages) {
6090            // Look to see if we already know about this package.
6091            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6092            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6093                // This package has been renamed to its original name.  Let's
6094                // use that.
6095                ps = mSettings.peekPackageLPr(oldName);
6096            }
6097            // If there was no original package, see one for the real package name.
6098            if (ps == null) {
6099                ps = mSettings.peekPackageLPr(pkg.packageName);
6100            }
6101            // Check to see if this package could be hiding/updating a system
6102            // package.  Must look for it either under the original or real
6103            // package name depending on our state.
6104            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6105            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6106        }
6107        boolean updatedPkgBetter = false;
6108        // First check if this is a system package that may involve an update
6109        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6110            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6111            // it needs to drop FLAG_PRIVILEGED.
6112            if (locationIsPrivileged(scanFile)) {
6113                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6114            } else {
6115                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6116            }
6117
6118            if (ps != null && !ps.codePath.equals(scanFile)) {
6119                // The path has changed from what was last scanned...  check the
6120                // version of the new path against what we have stored to determine
6121                // what to do.
6122                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6123                if (pkg.mVersionCode <= ps.versionCode) {
6124                    // The system package has been updated and the code path does not match
6125                    // Ignore entry. Skip it.
6126                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6127                            + " ignored: updated version " + ps.versionCode
6128                            + " better than this " + pkg.mVersionCode);
6129                    if (!updatedPkg.codePath.equals(scanFile)) {
6130                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6131                                + ps.name + " changing from " + updatedPkg.codePathString
6132                                + " to " + scanFile);
6133                        updatedPkg.codePath = scanFile;
6134                        updatedPkg.codePathString = scanFile.toString();
6135                        updatedPkg.resourcePath = scanFile;
6136                        updatedPkg.resourcePathString = scanFile.toString();
6137                    }
6138                    updatedPkg.pkg = pkg;
6139                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6140                            "Package " + ps.name + " at " + scanFile
6141                                    + " ignored: updated version " + ps.versionCode
6142                                    + " better than this " + pkg.mVersionCode);
6143                } else {
6144                    // The current app on the system partition is better than
6145                    // what we have updated to on the data partition; switch
6146                    // back to the system partition version.
6147                    // At this point, its safely assumed that package installation for
6148                    // apps in system partition will go through. If not there won't be a working
6149                    // version of the app
6150                    // writer
6151                    synchronized (mPackages) {
6152                        // Just remove the loaded entries from package lists.
6153                        mPackages.remove(ps.name);
6154                    }
6155
6156                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6157                            + " reverting from " + ps.codePathString
6158                            + ": new version " + pkg.mVersionCode
6159                            + " better than installed " + ps.versionCode);
6160
6161                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6162                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6163                    synchronized (mInstallLock) {
6164                        args.cleanUpResourcesLI();
6165                    }
6166                    synchronized (mPackages) {
6167                        mSettings.enableSystemPackageLPw(ps.name);
6168                    }
6169                    updatedPkgBetter = true;
6170                }
6171            }
6172        }
6173
6174        if (updatedPkg != null) {
6175            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6176            // initially
6177            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6178
6179            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6180            // flag set initially
6181            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6182                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6183            }
6184        }
6185
6186        // Verify certificates against what was last scanned
6187        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6188
6189        /*
6190         * A new system app appeared, but we already had a non-system one of the
6191         * same name installed earlier.
6192         */
6193        boolean shouldHideSystemApp = false;
6194        if (updatedPkg == null && ps != null
6195                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6196            /*
6197             * Check to make sure the signatures match first. If they don't,
6198             * wipe the installed application and its data.
6199             */
6200            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6201                    != PackageManager.SIGNATURE_MATCH) {
6202                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6203                        + " signatures don't match existing userdata copy; removing");
6204                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6205                ps = null;
6206            } else {
6207                /*
6208                 * If the newly-added system app is an older version than the
6209                 * already installed version, hide it. It will be scanned later
6210                 * and re-added like an update.
6211                 */
6212                if (pkg.mVersionCode <= ps.versionCode) {
6213                    shouldHideSystemApp = true;
6214                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6215                            + " but new version " + pkg.mVersionCode + " better than installed "
6216                            + ps.versionCode + "; hiding system");
6217                } else {
6218                    /*
6219                     * The newly found system app is a newer version that the
6220                     * one previously installed. Simply remove the
6221                     * already-installed application and replace it with our own
6222                     * while keeping the application data.
6223                     */
6224                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6225                            + " reverting from " + ps.codePathString + ": new version "
6226                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6227                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6228                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6229                    synchronized (mInstallLock) {
6230                        args.cleanUpResourcesLI();
6231                    }
6232                }
6233            }
6234        }
6235
6236        // The apk is forward locked (not public) if its code and resources
6237        // are kept in different files. (except for app in either system or
6238        // vendor path).
6239        // TODO grab this value from PackageSettings
6240        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6241            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6242                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6243            }
6244        }
6245
6246        // TODO: extend to support forward-locked splits
6247        String resourcePath = null;
6248        String baseResourcePath = null;
6249        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6250            if (ps != null && ps.resourcePathString != null) {
6251                resourcePath = ps.resourcePathString;
6252                baseResourcePath = ps.resourcePathString;
6253            } else {
6254                // Should not happen at all. Just log an error.
6255                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6256            }
6257        } else {
6258            resourcePath = pkg.codePath;
6259            baseResourcePath = pkg.baseCodePath;
6260        }
6261
6262        // Set application objects path explicitly.
6263        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6264        pkg.applicationInfo.setCodePath(pkg.codePath);
6265        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6266        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6267        pkg.applicationInfo.setResourcePath(resourcePath);
6268        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6269        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6270
6271        // Note that we invoke the following method only if we are about to unpack an application
6272        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6273                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6274
6275        /*
6276         * If the system app should be overridden by a previously installed
6277         * data, hide the system app now and let the /data/app scan pick it up
6278         * again.
6279         */
6280        if (shouldHideSystemApp) {
6281            synchronized (mPackages) {
6282                mSettings.disableSystemPackageLPw(pkg.packageName);
6283            }
6284        }
6285
6286        return scannedPkg;
6287    }
6288
6289    private static String fixProcessName(String defProcessName,
6290            String processName, int uid) {
6291        if (processName == null) {
6292            return defProcessName;
6293        }
6294        return processName;
6295    }
6296
6297    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6298            throws PackageManagerException {
6299        if (pkgSetting.signatures.mSignatures != null) {
6300            // Already existing package. Make sure signatures match
6301            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6302                    == PackageManager.SIGNATURE_MATCH;
6303            if (!match) {
6304                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6305                        == PackageManager.SIGNATURE_MATCH;
6306            }
6307            if (!match) {
6308                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6309                        == PackageManager.SIGNATURE_MATCH;
6310            }
6311            if (!match) {
6312                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6313                        + pkg.packageName + " signatures do not match the "
6314                        + "previously installed version; ignoring!");
6315            }
6316        }
6317
6318        // Check for shared user signatures
6319        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6320            // Already existing package. Make sure signatures match
6321            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6322                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6323            if (!match) {
6324                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6325                        == PackageManager.SIGNATURE_MATCH;
6326            }
6327            if (!match) {
6328                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6329                        == PackageManager.SIGNATURE_MATCH;
6330            }
6331            if (!match) {
6332                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6333                        "Package " + pkg.packageName
6334                        + " has no signatures that match those in shared user "
6335                        + pkgSetting.sharedUser.name + "; ignoring!");
6336            }
6337        }
6338    }
6339
6340    /**
6341     * Enforces that only the system UID or root's UID can call a method exposed
6342     * via Binder.
6343     *
6344     * @param message used as message if SecurityException is thrown
6345     * @throws SecurityException if the caller is not system or root
6346     */
6347    private static final void enforceSystemOrRoot(String message) {
6348        final int uid = Binder.getCallingUid();
6349        if (uid != Process.SYSTEM_UID && uid != 0) {
6350            throw new SecurityException(message);
6351        }
6352    }
6353
6354    @Override
6355    public void performFstrimIfNeeded() {
6356        enforceSystemOrRoot("Only the system can request fstrim");
6357
6358        // Before everything else, see whether we need to fstrim.
6359        try {
6360            IMountService ms = PackageHelper.getMountService();
6361            if (ms != null) {
6362                final boolean isUpgrade = isUpgrade();
6363                boolean doTrim = isUpgrade;
6364                if (doTrim) {
6365                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6366                } else {
6367                    final long interval = android.provider.Settings.Global.getLong(
6368                            mContext.getContentResolver(),
6369                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6370                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6371                    if (interval > 0) {
6372                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6373                        if (timeSinceLast > interval) {
6374                            doTrim = true;
6375                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6376                                    + "; running immediately");
6377                        }
6378                    }
6379                }
6380                if (doTrim) {
6381                    if (!isFirstBoot()) {
6382                        try {
6383                            ActivityManagerNative.getDefault().showBootMessage(
6384                                    mContext.getResources().getString(
6385                                            R.string.android_upgrading_fstrim), true);
6386                        } catch (RemoteException e) {
6387                        }
6388                    }
6389                    ms.runMaintenance();
6390                }
6391            } else {
6392                Slog.e(TAG, "Mount service unavailable!");
6393            }
6394        } catch (RemoteException e) {
6395            // Can't happen; MountService is local
6396        }
6397    }
6398
6399    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6400        List<ResolveInfo> ris = null;
6401        try {
6402            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6403                    intent, null, 0, userId);
6404        } catch (RemoteException e) {
6405        }
6406        ArraySet<String> pkgNames = new ArraySet<String>();
6407        if (ris != null) {
6408            for (ResolveInfo ri : ris) {
6409                pkgNames.add(ri.activityInfo.packageName);
6410            }
6411        }
6412        return pkgNames;
6413    }
6414
6415    @Override
6416    public void notifyPackageUse(String packageName) {
6417        synchronized (mPackages) {
6418            PackageParser.Package p = mPackages.get(packageName);
6419            if (p == null) {
6420                return;
6421            }
6422            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6423        }
6424    }
6425
6426    @Override
6427    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6428        return performDexOptTraced(packageName, instructionSet);
6429    }
6430
6431    public boolean performDexOpt(String packageName, String instructionSet) {
6432        return performDexOptTraced(packageName, instructionSet);
6433    }
6434
6435    private boolean performDexOptTraced(String packageName, String instructionSet) {
6436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6437        try {
6438            return performDexOptInternal(packageName, instructionSet);
6439        } finally {
6440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6441        }
6442    }
6443
6444    private boolean performDexOptInternal(String packageName, String instructionSet) {
6445        PackageParser.Package p;
6446        final String targetInstructionSet;
6447        synchronized (mPackages) {
6448            p = mPackages.get(packageName);
6449            if (p == null) {
6450                return false;
6451            }
6452            mPackageUsage.write(false);
6453
6454            targetInstructionSet = instructionSet != null ? instructionSet :
6455                    getPrimaryInstructionSet(p.applicationInfo);
6456            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6457                return false;
6458            }
6459        }
6460        long callingId = Binder.clearCallingIdentity();
6461        try {
6462            synchronized (mInstallLock) {
6463                final String[] instructionSets = new String[] { targetInstructionSet };
6464                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6465                        true /* inclDependencies */);
6466                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6467            }
6468        } finally {
6469            Binder.restoreCallingIdentity(callingId);
6470        }
6471    }
6472
6473    public ArraySet<String> getPackagesThatNeedDexOpt() {
6474        ArraySet<String> pkgs = null;
6475        synchronized (mPackages) {
6476            for (PackageParser.Package p : mPackages.values()) {
6477                if (DEBUG_DEXOPT) {
6478                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6479                }
6480                if (!p.mDexOptPerformed.isEmpty()) {
6481                    continue;
6482                }
6483                if (pkgs == null) {
6484                    pkgs = new ArraySet<String>();
6485                }
6486                pkgs.add(p.packageName);
6487            }
6488        }
6489        return pkgs;
6490    }
6491
6492    public void shutdown() {
6493        mPackageUsage.write(true);
6494    }
6495
6496    @Override
6497    public void forceDexOpt(String packageName) {
6498        enforceSystemOrRoot("forceDexOpt");
6499
6500        PackageParser.Package pkg;
6501        synchronized (mPackages) {
6502            pkg = mPackages.get(packageName);
6503            if (pkg == null) {
6504                throw new IllegalArgumentException("Missing package: " + packageName);
6505            }
6506        }
6507
6508        synchronized (mInstallLock) {
6509            final String[] instructionSets = new String[] {
6510                    getPrimaryInstructionSet(pkg.applicationInfo) };
6511
6512            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6513
6514            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6515                    true /* inclDependencies */);
6516
6517            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6518            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6519                throw new IllegalStateException("Failed to dexopt: " + res);
6520            }
6521        }
6522    }
6523
6524    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6525        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6526            Slog.w(TAG, "Unable to update from " + oldPkg.name
6527                    + " to " + newPkg.packageName
6528                    + ": old package not in system partition");
6529            return false;
6530        } else if (mPackages.get(oldPkg.name) != null) {
6531            Slog.w(TAG, "Unable to update from " + oldPkg.name
6532                    + " to " + newPkg.packageName
6533                    + ": old package still exists");
6534            return false;
6535        }
6536        return true;
6537    }
6538
6539    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6540            throws PackageManagerException {
6541        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6542        if (res != 0) {
6543            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6544                    "Failed to install " + packageName + ": " + res);
6545        }
6546
6547        final int[] users = sUserManager.getUserIds();
6548        for (int user : users) {
6549            if (user != 0) {
6550                res = mInstaller.createUserData(volumeUuid, packageName,
6551                        UserHandle.getUid(user, uid), user, seinfo);
6552                if (res != 0) {
6553                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6554                            "Failed to createUserData " + packageName + ": " + res);
6555                }
6556            }
6557        }
6558    }
6559
6560    private int removeDataDirsLI(String volumeUuid, String packageName) {
6561        int[] users = sUserManager.getUserIds();
6562        int res = 0;
6563        for (int user : users) {
6564            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6565            if (resInner < 0) {
6566                res = resInner;
6567            }
6568        }
6569
6570        return res;
6571    }
6572
6573    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6574        int[] users = sUserManager.getUserIds();
6575        int res = 0;
6576        for (int user : users) {
6577            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6578            if (resInner < 0) {
6579                res = resInner;
6580            }
6581        }
6582        return res;
6583    }
6584
6585    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6586            PackageParser.Package changingLib) {
6587        if (file.path != null) {
6588            usesLibraryFiles.add(file.path);
6589            return;
6590        }
6591        PackageParser.Package p = mPackages.get(file.apk);
6592        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6593            // If we are doing this while in the middle of updating a library apk,
6594            // then we need to make sure to use that new apk for determining the
6595            // dependencies here.  (We haven't yet finished committing the new apk
6596            // to the package manager state.)
6597            if (p == null || p.packageName.equals(changingLib.packageName)) {
6598                p = changingLib;
6599            }
6600        }
6601        if (p != null) {
6602            usesLibraryFiles.addAll(p.getAllCodePaths());
6603        }
6604    }
6605
6606    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6607            PackageParser.Package changingLib) throws PackageManagerException {
6608        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6609            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6610            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6611            for (int i=0; i<N; i++) {
6612                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6613                if (file == null) {
6614                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6615                            "Package " + pkg.packageName + " requires unavailable shared library "
6616                            + pkg.usesLibraries.get(i) + "; failing!");
6617                }
6618                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6619            }
6620            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6621            for (int i=0; i<N; i++) {
6622                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6623                if (file == null) {
6624                    Slog.w(TAG, "Package " + pkg.packageName
6625                            + " desires unavailable shared library "
6626                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6627                } else {
6628                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6629                }
6630            }
6631            N = usesLibraryFiles.size();
6632            if (N > 0) {
6633                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6634            } else {
6635                pkg.usesLibraryFiles = null;
6636            }
6637        }
6638    }
6639
6640    private static boolean hasString(List<String> list, List<String> which) {
6641        if (list == null) {
6642            return false;
6643        }
6644        for (int i=list.size()-1; i>=0; i--) {
6645            for (int j=which.size()-1; j>=0; j--) {
6646                if (which.get(j).equals(list.get(i))) {
6647                    return true;
6648                }
6649            }
6650        }
6651        return false;
6652    }
6653
6654    private void updateAllSharedLibrariesLPw() {
6655        for (PackageParser.Package pkg : mPackages.values()) {
6656            try {
6657                updateSharedLibrariesLPw(pkg, null);
6658            } catch (PackageManagerException e) {
6659                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6660            }
6661        }
6662    }
6663
6664    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6665            PackageParser.Package changingPkg) {
6666        ArrayList<PackageParser.Package> res = null;
6667        for (PackageParser.Package pkg : mPackages.values()) {
6668            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6669                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6670                if (res == null) {
6671                    res = new ArrayList<PackageParser.Package>();
6672                }
6673                res.add(pkg);
6674                try {
6675                    updateSharedLibrariesLPw(pkg, changingPkg);
6676                } catch (PackageManagerException e) {
6677                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6678                }
6679            }
6680        }
6681        return res;
6682    }
6683
6684    /**
6685     * Derive the value of the {@code cpuAbiOverride} based on the provided
6686     * value and an optional stored value from the package settings.
6687     */
6688    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6689        String cpuAbiOverride = null;
6690
6691        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6692            cpuAbiOverride = null;
6693        } else if (abiOverride != null) {
6694            cpuAbiOverride = abiOverride;
6695        } else if (settings != null) {
6696            cpuAbiOverride = settings.cpuAbiOverrideString;
6697        }
6698
6699        return cpuAbiOverride;
6700    }
6701
6702    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6703            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6704        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6705        try {
6706            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6707        } finally {
6708            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6709        }
6710    }
6711
6712    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6713            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6714        boolean success = false;
6715        try {
6716            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6717                    currentTime, user);
6718            success = true;
6719            return res;
6720        } finally {
6721            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6722                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6723            }
6724        }
6725    }
6726
6727    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6728            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6729        final File scanFile = new File(pkg.codePath);
6730        if (pkg.applicationInfo.getCodePath() == null ||
6731                pkg.applicationInfo.getResourcePath() == null) {
6732            // Bail out. The resource and code paths haven't been set.
6733            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6734                    "Code and resource paths haven't been set correctly");
6735        }
6736
6737        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6738            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6739        } else {
6740            // Only allow system apps to be flagged as core apps.
6741            pkg.coreApp = false;
6742        }
6743
6744        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6745            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6746        }
6747
6748        if (mCustomResolverComponentName != null &&
6749                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6750            setUpCustomResolverActivity(pkg);
6751        }
6752
6753        if (pkg.packageName.equals("android")) {
6754            synchronized (mPackages) {
6755                if (mAndroidApplication != null) {
6756                    Slog.w(TAG, "*************************************************");
6757                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6758                    Slog.w(TAG, " file=" + scanFile);
6759                    Slog.w(TAG, "*************************************************");
6760                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6761                            "Core android package being redefined.  Skipping.");
6762                }
6763
6764                // Set up information for our fall-back user intent resolution activity.
6765                mPlatformPackage = pkg;
6766                pkg.mVersionCode = mSdkVersion;
6767                mAndroidApplication = pkg.applicationInfo;
6768
6769                if (!mResolverReplaced) {
6770                    mResolveActivity.applicationInfo = mAndroidApplication;
6771                    mResolveActivity.name = ResolverActivity.class.getName();
6772                    mResolveActivity.packageName = mAndroidApplication.packageName;
6773                    mResolveActivity.processName = "system:ui";
6774                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6775                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6776                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6777                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6778                    mResolveActivity.exported = true;
6779                    mResolveActivity.enabled = true;
6780                    mResolveInfo.activityInfo = mResolveActivity;
6781                    mResolveInfo.priority = 0;
6782                    mResolveInfo.preferredOrder = 0;
6783                    mResolveInfo.match = 0;
6784                    mResolveComponentName = new ComponentName(
6785                            mAndroidApplication.packageName, mResolveActivity.name);
6786                }
6787            }
6788        }
6789
6790        if (DEBUG_PACKAGE_SCANNING) {
6791            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6792                Log.d(TAG, "Scanning package " + pkg.packageName);
6793        }
6794
6795        if (mPackages.containsKey(pkg.packageName)
6796                || mSharedLibraries.containsKey(pkg.packageName)) {
6797            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6798                    "Application package " + pkg.packageName
6799                    + " already installed.  Skipping duplicate.");
6800        }
6801
6802        // If we're only installing presumed-existing packages, require that the
6803        // scanned APK is both already known and at the path previously established
6804        // for it.  Previously unknown packages we pick up normally, but if we have an
6805        // a priori expectation about this package's install presence, enforce it.
6806        // With a singular exception for new system packages. When an OTA contains
6807        // a new system package, we allow the codepath to change from a system location
6808        // to the user-installed location. If we don't allow this change, any newer,
6809        // user-installed version of the application will be ignored.
6810        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6811            if (mExpectingBetter.containsKey(pkg.packageName)) {
6812                logCriticalInfo(Log.WARN,
6813                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6814            } else {
6815                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6816                if (known != null) {
6817                    if (DEBUG_PACKAGE_SCANNING) {
6818                        Log.d(TAG, "Examining " + pkg.codePath
6819                                + " and requiring known paths " + known.codePathString
6820                                + " & " + known.resourcePathString);
6821                    }
6822                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6823                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6824                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6825                                "Application package " + pkg.packageName
6826                                + " found at " + pkg.applicationInfo.getCodePath()
6827                                + " but expected at " + known.codePathString + "; ignoring.");
6828                    }
6829                }
6830            }
6831        }
6832
6833        // Initialize package source and resource directories
6834        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6835        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6836
6837        SharedUserSetting suid = null;
6838        PackageSetting pkgSetting = null;
6839
6840        if (!isSystemApp(pkg)) {
6841            // Only system apps can use these features.
6842            pkg.mOriginalPackages = null;
6843            pkg.mRealPackage = null;
6844            pkg.mAdoptPermissions = null;
6845        }
6846
6847        // writer
6848        synchronized (mPackages) {
6849            if (pkg.mSharedUserId != null) {
6850                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6851                if (suid == null) {
6852                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6853                            "Creating application package " + pkg.packageName
6854                            + " for shared user failed");
6855                }
6856                if (DEBUG_PACKAGE_SCANNING) {
6857                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6858                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6859                                + "): packages=" + suid.packages);
6860                }
6861            }
6862
6863            // Check if we are renaming from an original package name.
6864            PackageSetting origPackage = null;
6865            String realName = null;
6866            if (pkg.mOriginalPackages != null) {
6867                // This package may need to be renamed to a previously
6868                // installed name.  Let's check on that...
6869                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6870                if (pkg.mOriginalPackages.contains(renamed)) {
6871                    // This package had originally been installed as the
6872                    // original name, and we have already taken care of
6873                    // transitioning to the new one.  Just update the new
6874                    // one to continue using the old name.
6875                    realName = pkg.mRealPackage;
6876                    if (!pkg.packageName.equals(renamed)) {
6877                        // Callers into this function may have already taken
6878                        // care of renaming the package; only do it here if
6879                        // it is not already done.
6880                        pkg.setPackageName(renamed);
6881                    }
6882
6883                } else {
6884                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6885                        if ((origPackage = mSettings.peekPackageLPr(
6886                                pkg.mOriginalPackages.get(i))) != null) {
6887                            // We do have the package already installed under its
6888                            // original name...  should we use it?
6889                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6890                                // New package is not compatible with original.
6891                                origPackage = null;
6892                                continue;
6893                            } else if (origPackage.sharedUser != null) {
6894                                // Make sure uid is compatible between packages.
6895                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6896                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6897                                            + " to " + pkg.packageName + ": old uid "
6898                                            + origPackage.sharedUser.name
6899                                            + " differs from " + pkg.mSharedUserId);
6900                                    origPackage = null;
6901                                    continue;
6902                                }
6903                            } else {
6904                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6905                                        + pkg.packageName + " to old name " + origPackage.name);
6906                            }
6907                            break;
6908                        }
6909                    }
6910                }
6911            }
6912
6913            if (mTransferedPackages.contains(pkg.packageName)) {
6914                Slog.w(TAG, "Package " + pkg.packageName
6915                        + " was transferred to another, but its .apk remains");
6916            }
6917
6918            // Just create the setting, don't add it yet. For already existing packages
6919            // the PkgSetting exists already and doesn't have to be created.
6920            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6921                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6922                    pkg.applicationInfo.primaryCpuAbi,
6923                    pkg.applicationInfo.secondaryCpuAbi,
6924                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6925                    user, false);
6926            if (pkgSetting == null) {
6927                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6928                        "Creating application package " + pkg.packageName + " failed");
6929            }
6930
6931            if (pkgSetting.origPackage != null) {
6932                // If we are first transitioning from an original package,
6933                // fix up the new package's name now.  We need to do this after
6934                // looking up the package under its new name, so getPackageLP
6935                // can take care of fiddling things correctly.
6936                pkg.setPackageName(origPackage.name);
6937
6938                // File a report about this.
6939                String msg = "New package " + pkgSetting.realName
6940                        + " renamed to replace old package " + pkgSetting.name;
6941                reportSettingsProblem(Log.WARN, msg);
6942
6943                // Make a note of it.
6944                mTransferedPackages.add(origPackage.name);
6945
6946                // No longer need to retain this.
6947                pkgSetting.origPackage = null;
6948            }
6949
6950            if (realName != null) {
6951                // Make a note of it.
6952                mTransferedPackages.add(pkg.packageName);
6953            }
6954
6955            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6956                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6957            }
6958
6959            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6960                // Check all shared libraries and map to their actual file path.
6961                // We only do this here for apps not on a system dir, because those
6962                // are the only ones that can fail an install due to this.  We
6963                // will take care of the system apps by updating all of their
6964                // library paths after the scan is done.
6965                updateSharedLibrariesLPw(pkg, null);
6966            }
6967
6968            if (mFoundPolicyFile) {
6969                SELinuxMMAC.assignSeinfoValue(pkg);
6970            }
6971
6972            pkg.applicationInfo.uid = pkgSetting.appId;
6973            pkg.mExtras = pkgSetting;
6974            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6975                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6976                    // We just determined the app is signed correctly, so bring
6977                    // over the latest parsed certs.
6978                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6979                } else {
6980                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6981                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6982                                "Package " + pkg.packageName + " upgrade keys do not match the "
6983                                + "previously installed version");
6984                    } else {
6985                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6986                        String msg = "System package " + pkg.packageName
6987                            + " signature changed; retaining data.";
6988                        reportSettingsProblem(Log.WARN, msg);
6989                    }
6990                }
6991            } else {
6992                try {
6993                    verifySignaturesLP(pkgSetting, pkg);
6994                    // We just determined the app is signed correctly, so bring
6995                    // over the latest parsed certs.
6996                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6997                } catch (PackageManagerException e) {
6998                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6999                        throw e;
7000                    }
7001                    // The signature has changed, but this package is in the system
7002                    // image...  let's recover!
7003                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7004                    // However...  if this package is part of a shared user, but it
7005                    // doesn't match the signature of the shared user, let's fail.
7006                    // What this means is that you can't change the signatures
7007                    // associated with an overall shared user, which doesn't seem all
7008                    // that unreasonable.
7009                    if (pkgSetting.sharedUser != null) {
7010                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7011                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7012                            throw new PackageManagerException(
7013                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7014                                            "Signature mismatch for shared user : "
7015                                            + pkgSetting.sharedUser);
7016                        }
7017                    }
7018                    // File a report about this.
7019                    String msg = "System package " + pkg.packageName
7020                        + " signature changed; retaining data.";
7021                    reportSettingsProblem(Log.WARN, msg);
7022                }
7023            }
7024            // Verify that this new package doesn't have any content providers
7025            // that conflict with existing packages.  Only do this if the
7026            // package isn't already installed, since we don't want to break
7027            // things that are installed.
7028            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7029                final int N = pkg.providers.size();
7030                int i;
7031                for (i=0; i<N; i++) {
7032                    PackageParser.Provider p = pkg.providers.get(i);
7033                    if (p.info.authority != null) {
7034                        String names[] = p.info.authority.split(";");
7035                        for (int j = 0; j < names.length; j++) {
7036                            if (mProvidersByAuthority.containsKey(names[j])) {
7037                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7038                                final String otherPackageName =
7039                                        ((other != null && other.getComponentName() != null) ?
7040                                                other.getComponentName().getPackageName() : "?");
7041                                throw new PackageManagerException(
7042                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7043                                                "Can't install because provider name " + names[j]
7044                                                + " (in package " + pkg.applicationInfo.packageName
7045                                                + ") is already used by " + otherPackageName);
7046                            }
7047                        }
7048                    }
7049                }
7050            }
7051
7052            if (pkg.mAdoptPermissions != null) {
7053                // This package wants to adopt ownership of permissions from
7054                // another package.
7055                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7056                    final String origName = pkg.mAdoptPermissions.get(i);
7057                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7058                    if (orig != null) {
7059                        if (verifyPackageUpdateLPr(orig, pkg)) {
7060                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7061                                    + pkg.packageName);
7062                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7063                        }
7064                    }
7065                }
7066            }
7067        }
7068
7069        final String pkgName = pkg.packageName;
7070
7071        final long scanFileTime = scanFile.lastModified();
7072        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7073        pkg.applicationInfo.processName = fixProcessName(
7074                pkg.applicationInfo.packageName,
7075                pkg.applicationInfo.processName,
7076                pkg.applicationInfo.uid);
7077
7078        if (pkg != mPlatformPackage) {
7079            // This is a normal package, need to make its data directory.
7080            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7081                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7082
7083            boolean uidError = false;
7084            if (dataPath.exists()) {
7085                int currentUid = 0;
7086                try {
7087                    StructStat stat = Os.stat(dataPath.getPath());
7088                    currentUid = stat.st_uid;
7089                } catch (ErrnoException e) {
7090                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7091                }
7092
7093                // If we have mismatched owners for the data path, we have a problem.
7094                if (currentUid != pkg.applicationInfo.uid) {
7095                    boolean recovered = false;
7096                    if (currentUid == 0) {
7097                        // The directory somehow became owned by root.  Wow.
7098                        // This is probably because the system was stopped while
7099                        // installd was in the middle of messing with its libs
7100                        // directory.  Ask installd to fix that.
7101                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7102                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7103                        if (ret >= 0) {
7104                            recovered = true;
7105                            String msg = "Package " + pkg.packageName
7106                                    + " unexpectedly changed to uid 0; recovered to " +
7107                                    + pkg.applicationInfo.uid;
7108                            reportSettingsProblem(Log.WARN, msg);
7109                        }
7110                    }
7111                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7112                            || (scanFlags&SCAN_BOOTING) != 0)) {
7113                        // If this is a system app, we can at least delete its
7114                        // current data so the application will still work.
7115                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7116                        if (ret >= 0) {
7117                            // TODO: Kill the processes first
7118                            // Old data gone!
7119                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7120                                    ? "System package " : "Third party package ";
7121                            String msg = prefix + pkg.packageName
7122                                    + " has changed from uid: "
7123                                    + currentUid + " to "
7124                                    + pkg.applicationInfo.uid + "; old data erased";
7125                            reportSettingsProblem(Log.WARN, msg);
7126                            recovered = true;
7127                        }
7128                        if (!recovered) {
7129                            mHasSystemUidErrors = true;
7130                        }
7131                    } else if (!recovered) {
7132                        // If we allow this install to proceed, we will be broken.
7133                        // Abort, abort!
7134                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7135                                "scanPackageLI");
7136                    }
7137                    if (!recovered) {
7138                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7139                            + pkg.applicationInfo.uid + "/fs_"
7140                            + currentUid;
7141                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7142                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7143                        String msg = "Package " + pkg.packageName
7144                                + " has mismatched uid: "
7145                                + currentUid + " on disk, "
7146                                + pkg.applicationInfo.uid + " in settings";
7147                        // writer
7148                        synchronized (mPackages) {
7149                            mSettings.mReadMessages.append(msg);
7150                            mSettings.mReadMessages.append('\n');
7151                            uidError = true;
7152                            if (!pkgSetting.uidError) {
7153                                reportSettingsProblem(Log.ERROR, msg);
7154                            }
7155                        }
7156                    }
7157                }
7158
7159                // Ensure that directories are prepared
7160                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7161                        pkg.applicationInfo.seinfo);
7162
7163                if (mShouldRestoreconData) {
7164                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7165                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7166                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7167                }
7168            } else {
7169                if (DEBUG_PACKAGE_SCANNING) {
7170                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7171                        Log.v(TAG, "Want this data dir: " + dataPath);
7172                }
7173                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7174                        pkg.applicationInfo.seinfo);
7175            }
7176
7177            // Get all of our default paths setup
7178            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7179
7180            pkgSetting.uidError = uidError;
7181        }
7182
7183        final String path = scanFile.getPath();
7184        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7185
7186        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7187            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7188
7189            // Some system apps still use directory structure for native libraries
7190            // in which case we might end up not detecting abi solely based on apk
7191            // structure. Try to detect abi based on directory structure.
7192            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7193                    pkg.applicationInfo.primaryCpuAbi == null) {
7194                setBundledAppAbisAndRoots(pkg, pkgSetting);
7195                setNativeLibraryPaths(pkg);
7196            }
7197
7198        } else {
7199            if ((scanFlags & SCAN_MOVE) != 0) {
7200                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7201                // but we already have this packages package info in the PackageSetting. We just
7202                // use that and derive the native library path based on the new codepath.
7203                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7204                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7205            }
7206
7207            // Set native library paths again. For moves, the path will be updated based on the
7208            // ABIs we've determined above. For non-moves, the path will be updated based on the
7209            // ABIs we determined during compilation, but the path will depend on the final
7210            // package path (after the rename away from the stage path).
7211            setNativeLibraryPaths(pkg);
7212        }
7213
7214        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7215        final int[] userIds = sUserManager.getUserIds();
7216        synchronized (mInstallLock) {
7217            // Make sure all user data directories are ready to roll; we're okay
7218            // if they already exist
7219            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7220                for (int userId : userIds) {
7221                    if (userId != UserHandle.USER_SYSTEM) {
7222                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7223                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7224                                pkg.applicationInfo.seinfo);
7225                    }
7226                }
7227            }
7228
7229            // Create a native library symlink only if we have native libraries
7230            // and if the native libraries are 32 bit libraries. We do not provide
7231            // this symlink for 64 bit libraries.
7232            if (pkg.applicationInfo.primaryCpuAbi != null &&
7233                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7234                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7235                try {
7236                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7237                    for (int userId : userIds) {
7238                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7239                                nativeLibPath, userId) < 0) {
7240                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7241                                    "Failed linking native library dir (user=" + userId + ")");
7242                        }
7243                    }
7244                } finally {
7245                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7246                }
7247            }
7248        }
7249
7250        // This is a special case for the "system" package, where the ABI is
7251        // dictated by the zygote configuration (and init.rc). We should keep track
7252        // of this ABI so that we can deal with "normal" applications that run under
7253        // the same UID correctly.
7254        if (mPlatformPackage == pkg) {
7255            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7256                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7257        }
7258
7259        // If there's a mismatch between the abi-override in the package setting
7260        // and the abiOverride specified for the install. Warn about this because we
7261        // would've already compiled the app without taking the package setting into
7262        // account.
7263        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7264            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7265                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7266                        " for package: " + pkg.packageName);
7267            }
7268        }
7269
7270        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7271        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7272        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7273
7274        // Copy the derived override back to the parsed package, so that we can
7275        // update the package settings accordingly.
7276        pkg.cpuAbiOverride = cpuAbiOverride;
7277
7278        if (DEBUG_ABI_SELECTION) {
7279            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7280                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7281                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7282        }
7283
7284        // Push the derived path down into PackageSettings so we know what to
7285        // clean up at uninstall time.
7286        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7287
7288        if (DEBUG_ABI_SELECTION) {
7289            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7290                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7291                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7292        }
7293
7294        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7295            // We don't do this here during boot because we can do it all
7296            // at once after scanning all existing packages.
7297            //
7298            // We also do this *before* we perform dexopt on this package, so that
7299            // we can avoid redundant dexopts, and also to make sure we've got the
7300            // code and package path correct.
7301            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7302                    pkg, true /* boot complete */);
7303        }
7304
7305        if (mFactoryTest && pkg.requestedPermissions.contains(
7306                android.Manifest.permission.FACTORY_TEST)) {
7307            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7308        }
7309
7310        ArrayList<PackageParser.Package> clientLibPkgs = null;
7311
7312        // writer
7313        synchronized (mPackages) {
7314            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7315                // Only system apps can add new shared libraries.
7316                if (pkg.libraryNames != null) {
7317                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7318                        String name = pkg.libraryNames.get(i);
7319                        boolean allowed = false;
7320                        if (pkg.isUpdatedSystemApp()) {
7321                            // New library entries can only be added through the
7322                            // system image.  This is important to get rid of a lot
7323                            // of nasty edge cases: for example if we allowed a non-
7324                            // system update of the app to add a library, then uninstalling
7325                            // the update would make the library go away, and assumptions
7326                            // we made such as through app install filtering would now
7327                            // have allowed apps on the device which aren't compatible
7328                            // with it.  Better to just have the restriction here, be
7329                            // conservative, and create many fewer cases that can negatively
7330                            // impact the user experience.
7331                            final PackageSetting sysPs = mSettings
7332                                    .getDisabledSystemPkgLPr(pkg.packageName);
7333                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7334                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7335                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7336                                        allowed = true;
7337                                        break;
7338                                    }
7339                                }
7340                            }
7341                        } else {
7342                            allowed = true;
7343                        }
7344                        if (allowed) {
7345                            if (!mSharedLibraries.containsKey(name)) {
7346                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7347                            } else if (!name.equals(pkg.packageName)) {
7348                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7349                                        + name + " already exists; skipping");
7350                            }
7351                        } else {
7352                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7353                                    + name + " that is not declared on system image; skipping");
7354                        }
7355                    }
7356                    if ((scanFlags & SCAN_BOOTING) == 0) {
7357                        // If we are not booting, we need to update any applications
7358                        // that are clients of our shared library.  If we are booting,
7359                        // this will all be done once the scan is complete.
7360                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7361                    }
7362                }
7363            }
7364        }
7365
7366        // Request the ActivityManager to kill the process(only for existing packages)
7367        // so that we do not end up in a confused state while the user is still using the older
7368        // version of the application while the new one gets installed.
7369        if ((scanFlags & SCAN_REPLACING) != 0) {
7370            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7371
7372            killApplication(pkg.applicationInfo.packageName,
7373                        pkg.applicationInfo.uid, "replace pkg");
7374
7375            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7376        }
7377
7378        // Also need to kill any apps that are dependent on the library.
7379        if (clientLibPkgs != null) {
7380            for (int i=0; i<clientLibPkgs.size(); i++) {
7381                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7382                killApplication(clientPkg.applicationInfo.packageName,
7383                        clientPkg.applicationInfo.uid, "update lib");
7384            }
7385        }
7386
7387        // Make sure we're not adding any bogus keyset info
7388        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7389        ksms.assertScannedPackageValid(pkg);
7390
7391        // writer
7392        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7393
7394        boolean createIdmapFailed = false;
7395        synchronized (mPackages) {
7396            // We don't expect installation to fail beyond this point
7397
7398            // Add the new setting to mSettings
7399            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7400            // Add the new setting to mPackages
7401            mPackages.put(pkg.applicationInfo.packageName, pkg);
7402            // Make sure we don't accidentally delete its data.
7403            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7404            while (iter.hasNext()) {
7405                PackageCleanItem item = iter.next();
7406                if (pkgName.equals(item.packageName)) {
7407                    iter.remove();
7408                }
7409            }
7410
7411            // Take care of first install / last update times.
7412            if (currentTime != 0) {
7413                if (pkgSetting.firstInstallTime == 0) {
7414                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7415                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7416                    pkgSetting.lastUpdateTime = currentTime;
7417                }
7418            } else if (pkgSetting.firstInstallTime == 0) {
7419                // We need *something*.  Take time time stamp of the file.
7420                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7421            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7422                if (scanFileTime != pkgSetting.timeStamp) {
7423                    // A package on the system image has changed; consider this
7424                    // to be an update.
7425                    pkgSetting.lastUpdateTime = scanFileTime;
7426                }
7427            }
7428
7429            // Add the package's KeySets to the global KeySetManagerService
7430            ksms.addScannedPackageLPw(pkg);
7431
7432            int N = pkg.providers.size();
7433            StringBuilder r = null;
7434            int i;
7435            for (i=0; i<N; i++) {
7436                PackageParser.Provider p = pkg.providers.get(i);
7437                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7438                        p.info.processName, pkg.applicationInfo.uid);
7439                mProviders.addProvider(p);
7440                p.syncable = p.info.isSyncable;
7441                if (p.info.authority != null) {
7442                    String names[] = p.info.authority.split(";");
7443                    p.info.authority = null;
7444                    for (int j = 0; j < names.length; j++) {
7445                        if (j == 1 && p.syncable) {
7446                            // We only want the first authority for a provider to possibly be
7447                            // syncable, so if we already added this provider using a different
7448                            // authority clear the syncable flag. We copy the provider before
7449                            // changing it because the mProviders object contains a reference
7450                            // to a provider that we don't want to change.
7451                            // Only do this for the second authority since the resulting provider
7452                            // object can be the same for all future authorities for this provider.
7453                            p = new PackageParser.Provider(p);
7454                            p.syncable = false;
7455                        }
7456                        if (!mProvidersByAuthority.containsKey(names[j])) {
7457                            mProvidersByAuthority.put(names[j], p);
7458                            if (p.info.authority == null) {
7459                                p.info.authority = names[j];
7460                            } else {
7461                                p.info.authority = p.info.authority + ";" + names[j];
7462                            }
7463                            if (DEBUG_PACKAGE_SCANNING) {
7464                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7465                                    Log.d(TAG, "Registered content provider: " + names[j]
7466                                            + ", className = " + p.info.name + ", isSyncable = "
7467                                            + p.info.isSyncable);
7468                            }
7469                        } else {
7470                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7471                            Slog.w(TAG, "Skipping provider name " + names[j] +
7472                                    " (in package " + pkg.applicationInfo.packageName +
7473                                    "): name already used by "
7474                                    + ((other != null && other.getComponentName() != null)
7475                                            ? other.getComponentName().getPackageName() : "?"));
7476                        }
7477                    }
7478                }
7479                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7480                    if (r == null) {
7481                        r = new StringBuilder(256);
7482                    } else {
7483                        r.append(' ');
7484                    }
7485                    r.append(p.info.name);
7486                }
7487            }
7488            if (r != null) {
7489                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7490            }
7491
7492            N = pkg.services.size();
7493            r = null;
7494            for (i=0; i<N; i++) {
7495                PackageParser.Service s = pkg.services.get(i);
7496                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7497                        s.info.processName, pkg.applicationInfo.uid);
7498                mServices.addService(s);
7499                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7500                    if (r == null) {
7501                        r = new StringBuilder(256);
7502                    } else {
7503                        r.append(' ');
7504                    }
7505                    r.append(s.info.name);
7506                }
7507            }
7508            if (r != null) {
7509                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7510            }
7511
7512            N = pkg.receivers.size();
7513            r = null;
7514            for (i=0; i<N; i++) {
7515                PackageParser.Activity a = pkg.receivers.get(i);
7516                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7517                        a.info.processName, pkg.applicationInfo.uid);
7518                mReceivers.addActivity(a, "receiver");
7519                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7520                    if (r == null) {
7521                        r = new StringBuilder(256);
7522                    } else {
7523                        r.append(' ');
7524                    }
7525                    r.append(a.info.name);
7526                }
7527            }
7528            if (r != null) {
7529                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7530            }
7531
7532            N = pkg.activities.size();
7533            r = null;
7534            for (i=0; i<N; i++) {
7535                PackageParser.Activity a = pkg.activities.get(i);
7536                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7537                        a.info.processName, pkg.applicationInfo.uid);
7538                mActivities.addActivity(a, "activity");
7539                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7540                    if (r == null) {
7541                        r = new StringBuilder(256);
7542                    } else {
7543                        r.append(' ');
7544                    }
7545                    r.append(a.info.name);
7546                }
7547            }
7548            if (r != null) {
7549                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7550            }
7551
7552            N = pkg.permissionGroups.size();
7553            r = null;
7554            for (i=0; i<N; i++) {
7555                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7556                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7557                if (cur == null) {
7558                    mPermissionGroups.put(pg.info.name, pg);
7559                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7560                        if (r == null) {
7561                            r = new StringBuilder(256);
7562                        } else {
7563                            r.append(' ');
7564                        }
7565                        r.append(pg.info.name);
7566                    }
7567                } else {
7568                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7569                            + pg.info.packageName + " ignored: original from "
7570                            + cur.info.packageName);
7571                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7572                        if (r == null) {
7573                            r = new StringBuilder(256);
7574                        } else {
7575                            r.append(' ');
7576                        }
7577                        r.append("DUP:");
7578                        r.append(pg.info.name);
7579                    }
7580                }
7581            }
7582            if (r != null) {
7583                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7584            }
7585
7586            N = pkg.permissions.size();
7587            r = null;
7588            for (i=0; i<N; i++) {
7589                PackageParser.Permission p = pkg.permissions.get(i);
7590
7591                // Assume by default that we did not install this permission into the system.
7592                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7593
7594                // Now that permission groups have a special meaning, we ignore permission
7595                // groups for legacy apps to prevent unexpected behavior. In particular,
7596                // permissions for one app being granted to someone just becuase they happen
7597                // to be in a group defined by another app (before this had no implications).
7598                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7599                    p.group = mPermissionGroups.get(p.info.group);
7600                    // Warn for a permission in an unknown group.
7601                    if (p.info.group != null && p.group == null) {
7602                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7603                                + p.info.packageName + " in an unknown group " + p.info.group);
7604                    }
7605                }
7606
7607                ArrayMap<String, BasePermission> permissionMap =
7608                        p.tree ? mSettings.mPermissionTrees
7609                                : mSettings.mPermissions;
7610                BasePermission bp = permissionMap.get(p.info.name);
7611
7612                // Allow system apps to redefine non-system permissions
7613                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7614                    final boolean currentOwnerIsSystem = (bp.perm != null
7615                            && isSystemApp(bp.perm.owner));
7616                    if (isSystemApp(p.owner)) {
7617                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7618                            // It's a built-in permission and no owner, take ownership now
7619                            bp.packageSetting = pkgSetting;
7620                            bp.perm = p;
7621                            bp.uid = pkg.applicationInfo.uid;
7622                            bp.sourcePackage = p.info.packageName;
7623                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7624                        } else if (!currentOwnerIsSystem) {
7625                            String msg = "New decl " + p.owner + " of permission  "
7626                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7627                            reportSettingsProblem(Log.WARN, msg);
7628                            bp = null;
7629                        }
7630                    }
7631                }
7632
7633                if (bp == null) {
7634                    bp = new BasePermission(p.info.name, p.info.packageName,
7635                            BasePermission.TYPE_NORMAL);
7636                    permissionMap.put(p.info.name, bp);
7637                }
7638
7639                if (bp.perm == null) {
7640                    if (bp.sourcePackage == null
7641                            || bp.sourcePackage.equals(p.info.packageName)) {
7642                        BasePermission tree = findPermissionTreeLP(p.info.name);
7643                        if (tree == null
7644                                || tree.sourcePackage.equals(p.info.packageName)) {
7645                            bp.packageSetting = pkgSetting;
7646                            bp.perm = p;
7647                            bp.uid = pkg.applicationInfo.uid;
7648                            bp.sourcePackage = p.info.packageName;
7649                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7650                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7651                                if (r == null) {
7652                                    r = new StringBuilder(256);
7653                                } else {
7654                                    r.append(' ');
7655                                }
7656                                r.append(p.info.name);
7657                            }
7658                        } else {
7659                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7660                                    + p.info.packageName + " ignored: base tree "
7661                                    + tree.name + " is from package "
7662                                    + tree.sourcePackage);
7663                        }
7664                    } else {
7665                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7666                                + p.info.packageName + " ignored: original from "
7667                                + bp.sourcePackage);
7668                    }
7669                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7670                    if (r == null) {
7671                        r = new StringBuilder(256);
7672                    } else {
7673                        r.append(' ');
7674                    }
7675                    r.append("DUP:");
7676                    r.append(p.info.name);
7677                }
7678                if (bp.perm == p) {
7679                    bp.protectionLevel = p.info.protectionLevel;
7680                }
7681            }
7682
7683            if (r != null) {
7684                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7685            }
7686
7687            N = pkg.instrumentation.size();
7688            r = null;
7689            for (i=0; i<N; i++) {
7690                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7691                a.info.packageName = pkg.applicationInfo.packageName;
7692                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7693                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7694                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7695                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7696                a.info.dataDir = pkg.applicationInfo.dataDir;
7697                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7698                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7699
7700                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7701                // need other information about the application, like the ABI and what not ?
7702                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7703                mInstrumentation.put(a.getComponentName(), a);
7704                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7705                    if (r == null) {
7706                        r = new StringBuilder(256);
7707                    } else {
7708                        r.append(' ');
7709                    }
7710                    r.append(a.info.name);
7711                }
7712            }
7713            if (r != null) {
7714                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7715            }
7716
7717            if (pkg.protectedBroadcasts != null) {
7718                N = pkg.protectedBroadcasts.size();
7719                for (i=0; i<N; i++) {
7720                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7721                }
7722            }
7723
7724            pkgSetting.setTimeStamp(scanFileTime);
7725
7726            // Create idmap files for pairs of (packages, overlay packages).
7727            // Note: "android", ie framework-res.apk, is handled by native layers.
7728            if (pkg.mOverlayTarget != null) {
7729                // This is an overlay package.
7730                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7731                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7732                        mOverlays.put(pkg.mOverlayTarget,
7733                                new ArrayMap<String, PackageParser.Package>());
7734                    }
7735                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7736                    map.put(pkg.packageName, pkg);
7737                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7738                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7739                        createIdmapFailed = true;
7740                    }
7741                }
7742            } else if (mOverlays.containsKey(pkg.packageName) &&
7743                    !pkg.packageName.equals("android")) {
7744                // This is a regular package, with one or more known overlay packages.
7745                createIdmapsForPackageLI(pkg);
7746            }
7747        }
7748
7749        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7750
7751        if (createIdmapFailed) {
7752            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7753                    "scanPackageLI failed to createIdmap");
7754        }
7755        return pkg;
7756    }
7757
7758    /**
7759     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7760     * is derived purely on the basis of the contents of {@code scanFile} and
7761     * {@code cpuAbiOverride}.
7762     *
7763     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7764     */
7765    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7766                                 String cpuAbiOverride, boolean extractLibs)
7767            throws PackageManagerException {
7768        // TODO: We can probably be smarter about this stuff. For installed apps,
7769        // we can calculate this information at install time once and for all. For
7770        // system apps, we can probably assume that this information doesn't change
7771        // after the first boot scan. As things stand, we do lots of unnecessary work.
7772
7773        // Give ourselves some initial paths; we'll come back for another
7774        // pass once we've determined ABI below.
7775        setNativeLibraryPaths(pkg);
7776
7777        // We would never need to extract libs for forward-locked and external packages,
7778        // since the container service will do it for us. We shouldn't attempt to
7779        // extract libs from system app when it was not updated.
7780        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7781                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7782            extractLibs = false;
7783        }
7784
7785        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7786        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7787
7788        NativeLibraryHelper.Handle handle = null;
7789        try {
7790            handle = NativeLibraryHelper.Handle.create(pkg);
7791            // TODO(multiArch): This can be null for apps that didn't go through the
7792            // usual installation process. We can calculate it again, like we
7793            // do during install time.
7794            //
7795            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7796            // unnecessary.
7797            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7798
7799            // Null out the abis so that they can be recalculated.
7800            pkg.applicationInfo.primaryCpuAbi = null;
7801            pkg.applicationInfo.secondaryCpuAbi = null;
7802            if (isMultiArch(pkg.applicationInfo)) {
7803                // Warn if we've set an abiOverride for multi-lib packages..
7804                // By definition, we need to copy both 32 and 64 bit libraries for
7805                // such packages.
7806                if (pkg.cpuAbiOverride != null
7807                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7808                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7809                }
7810
7811                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7812                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7813                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7814                    if (extractLibs) {
7815                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7816                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7817                                useIsaSpecificSubdirs);
7818                    } else {
7819                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7820                    }
7821                }
7822
7823                maybeThrowExceptionForMultiArchCopy(
7824                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7825
7826                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7827                    if (extractLibs) {
7828                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7829                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7830                                useIsaSpecificSubdirs);
7831                    } else {
7832                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7833                    }
7834                }
7835
7836                maybeThrowExceptionForMultiArchCopy(
7837                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7838
7839                if (abi64 >= 0) {
7840                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7841                }
7842
7843                if (abi32 >= 0) {
7844                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7845                    if (abi64 >= 0) {
7846                        pkg.applicationInfo.secondaryCpuAbi = abi;
7847                    } else {
7848                        pkg.applicationInfo.primaryCpuAbi = abi;
7849                    }
7850                }
7851            } else {
7852                String[] abiList = (cpuAbiOverride != null) ?
7853                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7854
7855                // Enable gross and lame hacks for apps that are built with old
7856                // SDK tools. We must scan their APKs for renderscript bitcode and
7857                // not launch them if it's present. Don't bother checking on devices
7858                // that don't have 64 bit support.
7859                boolean needsRenderScriptOverride = false;
7860                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7861                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7862                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7863                    needsRenderScriptOverride = true;
7864                }
7865
7866                final int copyRet;
7867                if (extractLibs) {
7868                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7869                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7870                } else {
7871                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7872                }
7873
7874                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7875                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7876                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7877                }
7878
7879                if (copyRet >= 0) {
7880                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7881                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7882                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7883                } else if (needsRenderScriptOverride) {
7884                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7885                }
7886            }
7887        } catch (IOException ioe) {
7888            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7889        } finally {
7890            IoUtils.closeQuietly(handle);
7891        }
7892
7893        // Now that we've calculated the ABIs and determined if it's an internal app,
7894        // we will go ahead and populate the nativeLibraryPath.
7895        setNativeLibraryPaths(pkg);
7896    }
7897
7898    /**
7899     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7900     * i.e, so that all packages can be run inside a single process if required.
7901     *
7902     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7903     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7904     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7905     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7906     * updating a package that belongs to a shared user.
7907     *
7908     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7909     * adds unnecessary complexity.
7910     */
7911    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7912            PackageParser.Package scannedPackage, boolean bootComplete) {
7913        String requiredInstructionSet = null;
7914        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7915            requiredInstructionSet = VMRuntime.getInstructionSet(
7916                     scannedPackage.applicationInfo.primaryCpuAbi);
7917        }
7918
7919        PackageSetting requirer = null;
7920        for (PackageSetting ps : packagesForUser) {
7921            // If packagesForUser contains scannedPackage, we skip it. This will happen
7922            // when scannedPackage is an update of an existing package. Without this check,
7923            // we will never be able to change the ABI of any package belonging to a shared
7924            // user, even if it's compatible with other packages.
7925            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7926                if (ps.primaryCpuAbiString == null) {
7927                    continue;
7928                }
7929
7930                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7931                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7932                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7933                    // this but there's not much we can do.
7934                    String errorMessage = "Instruction set mismatch, "
7935                            + ((requirer == null) ? "[caller]" : requirer)
7936                            + " requires " + requiredInstructionSet + " whereas " + ps
7937                            + " requires " + instructionSet;
7938                    Slog.w(TAG, errorMessage);
7939                }
7940
7941                if (requiredInstructionSet == null) {
7942                    requiredInstructionSet = instructionSet;
7943                    requirer = ps;
7944                }
7945            }
7946        }
7947
7948        if (requiredInstructionSet != null) {
7949            String adjustedAbi;
7950            if (requirer != null) {
7951                // requirer != null implies that either scannedPackage was null or that scannedPackage
7952                // did not require an ABI, in which case we have to adjust scannedPackage to match
7953                // the ABI of the set (which is the same as requirer's ABI)
7954                adjustedAbi = requirer.primaryCpuAbiString;
7955                if (scannedPackage != null) {
7956                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7957                }
7958            } else {
7959                // requirer == null implies that we're updating all ABIs in the set to
7960                // match scannedPackage.
7961                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7962            }
7963
7964            for (PackageSetting ps : packagesForUser) {
7965                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7966                    if (ps.primaryCpuAbiString != null) {
7967                        continue;
7968                    }
7969
7970                    ps.primaryCpuAbiString = adjustedAbi;
7971                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7972                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7973                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7974                        mInstaller.rmdex(ps.codePathString,
7975                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7976                    }
7977                }
7978            }
7979        }
7980    }
7981
7982    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7983        synchronized (mPackages) {
7984            mResolverReplaced = true;
7985            // Set up information for custom user intent resolution activity.
7986            mResolveActivity.applicationInfo = pkg.applicationInfo;
7987            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7988            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7989            mResolveActivity.processName = pkg.applicationInfo.packageName;
7990            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7991            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7992                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7993            mResolveActivity.theme = 0;
7994            mResolveActivity.exported = true;
7995            mResolveActivity.enabled = true;
7996            mResolveInfo.activityInfo = mResolveActivity;
7997            mResolveInfo.priority = 0;
7998            mResolveInfo.preferredOrder = 0;
7999            mResolveInfo.match = 0;
8000            mResolveComponentName = mCustomResolverComponentName;
8001            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8002                    mResolveComponentName);
8003        }
8004    }
8005
8006    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8007        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8008
8009        // Set up information for ephemeral installer activity
8010        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8011        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8012        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8013        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8014        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8015        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8016                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8017        mEphemeralInstallerActivity.theme = 0;
8018        mEphemeralInstallerActivity.exported = true;
8019        mEphemeralInstallerActivity.enabled = true;
8020        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8021        mEphemeralInstallerInfo.priority = 0;
8022        mEphemeralInstallerInfo.preferredOrder = 0;
8023        mEphemeralInstallerInfo.match = 0;
8024
8025        if (DEBUG_EPHEMERAL) {
8026            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8027        }
8028    }
8029
8030    private static String calculateBundledApkRoot(final String codePathString) {
8031        final File codePath = new File(codePathString);
8032        final File codeRoot;
8033        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8034            codeRoot = Environment.getRootDirectory();
8035        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8036            codeRoot = Environment.getOemDirectory();
8037        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8038            codeRoot = Environment.getVendorDirectory();
8039        } else {
8040            // Unrecognized code path; take its top real segment as the apk root:
8041            // e.g. /something/app/blah.apk => /something
8042            try {
8043                File f = codePath.getCanonicalFile();
8044                File parent = f.getParentFile();    // non-null because codePath is a file
8045                File tmp;
8046                while ((tmp = parent.getParentFile()) != null) {
8047                    f = parent;
8048                    parent = tmp;
8049                }
8050                codeRoot = f;
8051                Slog.w(TAG, "Unrecognized code path "
8052                        + codePath + " - using " + codeRoot);
8053            } catch (IOException e) {
8054                // Can't canonicalize the code path -- shenanigans?
8055                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8056                return Environment.getRootDirectory().getPath();
8057            }
8058        }
8059        return codeRoot.getPath();
8060    }
8061
8062    /**
8063     * Derive and set the location of native libraries for the given package,
8064     * which varies depending on where and how the package was installed.
8065     */
8066    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8067        final ApplicationInfo info = pkg.applicationInfo;
8068        final String codePath = pkg.codePath;
8069        final File codeFile = new File(codePath);
8070        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8071        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8072
8073        info.nativeLibraryRootDir = null;
8074        info.nativeLibraryRootRequiresIsa = false;
8075        info.nativeLibraryDir = null;
8076        info.secondaryNativeLibraryDir = null;
8077
8078        if (isApkFile(codeFile)) {
8079            // Monolithic install
8080            if (bundledApp) {
8081                // If "/system/lib64/apkname" exists, assume that is the per-package
8082                // native library directory to use; otherwise use "/system/lib/apkname".
8083                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8084                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8085                        getPrimaryInstructionSet(info));
8086
8087                // This is a bundled system app so choose the path based on the ABI.
8088                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8089                // is just the default path.
8090                final String apkName = deriveCodePathName(codePath);
8091                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8092                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8093                        apkName).getAbsolutePath();
8094
8095                if (info.secondaryCpuAbi != null) {
8096                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8097                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8098                            secondaryLibDir, apkName).getAbsolutePath();
8099                }
8100            } else if (asecApp) {
8101                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8102                        .getAbsolutePath();
8103            } else {
8104                final String apkName = deriveCodePathName(codePath);
8105                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8106                        .getAbsolutePath();
8107            }
8108
8109            info.nativeLibraryRootRequiresIsa = false;
8110            info.nativeLibraryDir = info.nativeLibraryRootDir;
8111        } else {
8112            // Cluster install
8113            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8114            info.nativeLibraryRootRequiresIsa = true;
8115
8116            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8117                    getPrimaryInstructionSet(info)).getAbsolutePath();
8118
8119            if (info.secondaryCpuAbi != null) {
8120                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8121                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8122            }
8123        }
8124    }
8125
8126    /**
8127     * Calculate the abis and roots for a bundled app. These can uniquely
8128     * be determined from the contents of the system partition, i.e whether
8129     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8130     * of this information, and instead assume that the system was built
8131     * sensibly.
8132     */
8133    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8134                                           PackageSetting pkgSetting) {
8135        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8136
8137        // If "/system/lib64/apkname" exists, assume that is the per-package
8138        // native library directory to use; otherwise use "/system/lib/apkname".
8139        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8140        setBundledAppAbi(pkg, apkRoot, apkName);
8141        // pkgSetting might be null during rescan following uninstall of updates
8142        // to a bundled app, so accommodate that possibility.  The settings in
8143        // that case will be established later from the parsed package.
8144        //
8145        // If the settings aren't null, sync them up with what we've just derived.
8146        // note that apkRoot isn't stored in the package settings.
8147        if (pkgSetting != null) {
8148            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8149            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8150        }
8151    }
8152
8153    /**
8154     * Deduces the ABI of a bundled app and sets the relevant fields on the
8155     * parsed pkg object.
8156     *
8157     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8158     *        under which system libraries are installed.
8159     * @param apkName the name of the installed package.
8160     */
8161    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8162        final File codeFile = new File(pkg.codePath);
8163
8164        final boolean has64BitLibs;
8165        final boolean has32BitLibs;
8166        if (isApkFile(codeFile)) {
8167            // Monolithic install
8168            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8169            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8170        } else {
8171            // Cluster install
8172            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8173            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8174                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8175                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8176                has64BitLibs = (new File(rootDir, isa)).exists();
8177            } else {
8178                has64BitLibs = false;
8179            }
8180            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8181                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8182                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8183                has32BitLibs = (new File(rootDir, isa)).exists();
8184            } else {
8185                has32BitLibs = false;
8186            }
8187        }
8188
8189        if (has64BitLibs && !has32BitLibs) {
8190            // The package has 64 bit libs, but not 32 bit libs. Its primary
8191            // ABI should be 64 bit. We can safely assume here that the bundled
8192            // native libraries correspond to the most preferred ABI in the list.
8193
8194            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8195            pkg.applicationInfo.secondaryCpuAbi = null;
8196        } else if (has32BitLibs && !has64BitLibs) {
8197            // The package has 32 bit libs but not 64 bit libs. Its primary
8198            // ABI should be 32 bit.
8199
8200            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8201            pkg.applicationInfo.secondaryCpuAbi = null;
8202        } else if (has32BitLibs && has64BitLibs) {
8203            // The application has both 64 and 32 bit bundled libraries. We check
8204            // here that the app declares multiArch support, and warn if it doesn't.
8205            //
8206            // We will be lenient here and record both ABIs. The primary will be the
8207            // ABI that's higher on the list, i.e, a device that's configured to prefer
8208            // 64 bit apps will see a 64 bit primary ABI,
8209
8210            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8211                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8212            }
8213
8214            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8215                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8216                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8217            } else {
8218                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8219                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8220            }
8221        } else {
8222            pkg.applicationInfo.primaryCpuAbi = null;
8223            pkg.applicationInfo.secondaryCpuAbi = null;
8224        }
8225    }
8226
8227    private void killApplication(String pkgName, int appId, String reason) {
8228        // Request the ActivityManager to kill the process(only for existing packages)
8229        // so that we do not end up in a confused state while the user is still using the older
8230        // version of the application while the new one gets installed.
8231        IActivityManager am = ActivityManagerNative.getDefault();
8232        if (am != null) {
8233            try {
8234                am.killApplicationWithAppId(pkgName, appId, reason);
8235            } catch (RemoteException e) {
8236            }
8237        }
8238    }
8239
8240    void removePackageLI(PackageSetting ps, boolean chatty) {
8241        if (DEBUG_INSTALL) {
8242            if (chatty)
8243                Log.d(TAG, "Removing package " + ps.name);
8244        }
8245
8246        // writer
8247        synchronized (mPackages) {
8248            mPackages.remove(ps.name);
8249            final PackageParser.Package pkg = ps.pkg;
8250            if (pkg != null) {
8251                cleanPackageDataStructuresLILPw(pkg, chatty);
8252            }
8253        }
8254    }
8255
8256    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8257        if (DEBUG_INSTALL) {
8258            if (chatty)
8259                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8260        }
8261
8262        // writer
8263        synchronized (mPackages) {
8264            mPackages.remove(pkg.applicationInfo.packageName);
8265            cleanPackageDataStructuresLILPw(pkg, chatty);
8266        }
8267    }
8268
8269    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8270        int N = pkg.providers.size();
8271        StringBuilder r = null;
8272        int i;
8273        for (i=0; i<N; i++) {
8274            PackageParser.Provider p = pkg.providers.get(i);
8275            mProviders.removeProvider(p);
8276            if (p.info.authority == null) {
8277
8278                /* There was another ContentProvider with this authority when
8279                 * this app was installed so this authority is null,
8280                 * Ignore it as we don't have to unregister the provider.
8281                 */
8282                continue;
8283            }
8284            String names[] = p.info.authority.split(";");
8285            for (int j = 0; j < names.length; j++) {
8286                if (mProvidersByAuthority.get(names[j]) == p) {
8287                    mProvidersByAuthority.remove(names[j]);
8288                    if (DEBUG_REMOVE) {
8289                        if (chatty)
8290                            Log.d(TAG, "Unregistered content provider: " + names[j]
8291                                    + ", className = " + p.info.name + ", isSyncable = "
8292                                    + p.info.isSyncable);
8293                    }
8294                }
8295            }
8296            if (DEBUG_REMOVE && chatty) {
8297                if (r == null) {
8298                    r = new StringBuilder(256);
8299                } else {
8300                    r.append(' ');
8301                }
8302                r.append(p.info.name);
8303            }
8304        }
8305        if (r != null) {
8306            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8307        }
8308
8309        N = pkg.services.size();
8310        r = null;
8311        for (i=0; i<N; i++) {
8312            PackageParser.Service s = pkg.services.get(i);
8313            mServices.removeService(s);
8314            if (chatty) {
8315                if (r == null) {
8316                    r = new StringBuilder(256);
8317                } else {
8318                    r.append(' ');
8319                }
8320                r.append(s.info.name);
8321            }
8322        }
8323        if (r != null) {
8324            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8325        }
8326
8327        N = pkg.receivers.size();
8328        r = null;
8329        for (i=0; i<N; i++) {
8330            PackageParser.Activity a = pkg.receivers.get(i);
8331            mReceivers.removeActivity(a, "receiver");
8332            if (DEBUG_REMOVE && chatty) {
8333                if (r == null) {
8334                    r = new StringBuilder(256);
8335                } else {
8336                    r.append(' ');
8337                }
8338                r.append(a.info.name);
8339            }
8340        }
8341        if (r != null) {
8342            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8343        }
8344
8345        N = pkg.activities.size();
8346        r = null;
8347        for (i=0; i<N; i++) {
8348            PackageParser.Activity a = pkg.activities.get(i);
8349            mActivities.removeActivity(a, "activity");
8350            if (DEBUG_REMOVE && chatty) {
8351                if (r == null) {
8352                    r = new StringBuilder(256);
8353                } else {
8354                    r.append(' ');
8355                }
8356                r.append(a.info.name);
8357            }
8358        }
8359        if (r != null) {
8360            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8361        }
8362
8363        N = pkg.permissions.size();
8364        r = null;
8365        for (i=0; i<N; i++) {
8366            PackageParser.Permission p = pkg.permissions.get(i);
8367            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8368            if (bp == null) {
8369                bp = mSettings.mPermissionTrees.get(p.info.name);
8370            }
8371            if (bp != null && bp.perm == p) {
8372                bp.perm = null;
8373                if (DEBUG_REMOVE && chatty) {
8374                    if (r == null) {
8375                        r = new StringBuilder(256);
8376                    } else {
8377                        r.append(' ');
8378                    }
8379                    r.append(p.info.name);
8380                }
8381            }
8382            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8383                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8384                if (appOpPerms != null) {
8385                    appOpPerms.remove(pkg.packageName);
8386                }
8387            }
8388        }
8389        if (r != null) {
8390            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8391        }
8392
8393        N = pkg.requestedPermissions.size();
8394        r = null;
8395        for (i=0; i<N; i++) {
8396            String perm = pkg.requestedPermissions.get(i);
8397            BasePermission bp = mSettings.mPermissions.get(perm);
8398            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8399                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8400                if (appOpPerms != null) {
8401                    appOpPerms.remove(pkg.packageName);
8402                    if (appOpPerms.isEmpty()) {
8403                        mAppOpPermissionPackages.remove(perm);
8404                    }
8405                }
8406            }
8407        }
8408        if (r != null) {
8409            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8410        }
8411
8412        N = pkg.instrumentation.size();
8413        r = null;
8414        for (i=0; i<N; i++) {
8415            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8416            mInstrumentation.remove(a.getComponentName());
8417            if (DEBUG_REMOVE && chatty) {
8418                if (r == null) {
8419                    r = new StringBuilder(256);
8420                } else {
8421                    r.append(' ');
8422                }
8423                r.append(a.info.name);
8424            }
8425        }
8426        if (r != null) {
8427            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8428        }
8429
8430        r = null;
8431        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8432            // Only system apps can hold shared libraries.
8433            if (pkg.libraryNames != null) {
8434                for (i=0; i<pkg.libraryNames.size(); i++) {
8435                    String name = pkg.libraryNames.get(i);
8436                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8437                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8438                        mSharedLibraries.remove(name);
8439                        if (DEBUG_REMOVE && chatty) {
8440                            if (r == null) {
8441                                r = new StringBuilder(256);
8442                            } else {
8443                                r.append(' ');
8444                            }
8445                            r.append(name);
8446                        }
8447                    }
8448                }
8449            }
8450        }
8451        if (r != null) {
8452            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8453        }
8454    }
8455
8456    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8457        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8458            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8459                return true;
8460            }
8461        }
8462        return false;
8463    }
8464
8465    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8466    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8467    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8468
8469    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8470            int flags) {
8471        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8472        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8473    }
8474
8475    private void updatePermissionsLPw(String changingPkg,
8476            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8477        // Make sure there are no dangling permission trees.
8478        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8479        while (it.hasNext()) {
8480            final BasePermission bp = it.next();
8481            if (bp.packageSetting == null) {
8482                // We may not yet have parsed the package, so just see if
8483                // we still know about its settings.
8484                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8485            }
8486            if (bp.packageSetting == null) {
8487                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8488                        + " from package " + bp.sourcePackage);
8489                it.remove();
8490            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8491                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8492                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8493                            + " from package " + bp.sourcePackage);
8494                    flags |= UPDATE_PERMISSIONS_ALL;
8495                    it.remove();
8496                }
8497            }
8498        }
8499
8500        // Make sure all dynamic permissions have been assigned to a package,
8501        // and make sure there are no dangling permissions.
8502        it = mSettings.mPermissions.values().iterator();
8503        while (it.hasNext()) {
8504            final BasePermission bp = it.next();
8505            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8506                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8507                        + bp.name + " pkg=" + bp.sourcePackage
8508                        + " info=" + bp.pendingInfo);
8509                if (bp.packageSetting == null && bp.pendingInfo != null) {
8510                    final BasePermission tree = findPermissionTreeLP(bp.name);
8511                    if (tree != null && tree.perm != null) {
8512                        bp.packageSetting = tree.packageSetting;
8513                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8514                                new PermissionInfo(bp.pendingInfo));
8515                        bp.perm.info.packageName = tree.perm.info.packageName;
8516                        bp.perm.info.name = bp.name;
8517                        bp.uid = tree.uid;
8518                    }
8519                }
8520            }
8521            if (bp.packageSetting == null) {
8522                // We may not yet have parsed the package, so just see if
8523                // we still know about its settings.
8524                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8525            }
8526            if (bp.packageSetting == null) {
8527                Slog.w(TAG, "Removing dangling permission: " + bp.name
8528                        + " from package " + bp.sourcePackage);
8529                it.remove();
8530            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8531                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8532                    Slog.i(TAG, "Removing old permission: " + bp.name
8533                            + " from package " + bp.sourcePackage);
8534                    flags |= UPDATE_PERMISSIONS_ALL;
8535                    it.remove();
8536                }
8537            }
8538        }
8539
8540        // Now update the permissions for all packages, in particular
8541        // replace the granted permissions of the system packages.
8542        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8543            for (PackageParser.Package pkg : mPackages.values()) {
8544                if (pkg != pkgInfo) {
8545                    // Only replace for packages on requested volume
8546                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8547                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8548                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8549                    grantPermissionsLPw(pkg, replace, changingPkg);
8550                }
8551            }
8552        }
8553
8554        if (pkgInfo != null) {
8555            // Only replace for packages on requested volume
8556            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8557            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8558                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8559            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8560        }
8561    }
8562
8563    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8564            String packageOfInterest) {
8565        // IMPORTANT: There are two types of permissions: install and runtime.
8566        // Install time permissions are granted when the app is installed to
8567        // all device users and users added in the future. Runtime permissions
8568        // are granted at runtime explicitly to specific users. Normal and signature
8569        // protected permissions are install time permissions. Dangerous permissions
8570        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8571        // otherwise they are runtime permissions. This function does not manage
8572        // runtime permissions except for the case an app targeting Lollipop MR1
8573        // being upgraded to target a newer SDK, in which case dangerous permissions
8574        // are transformed from install time to runtime ones.
8575
8576        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8577        if (ps == null) {
8578            return;
8579        }
8580
8581        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8582
8583        PermissionsState permissionsState = ps.getPermissionsState();
8584        PermissionsState origPermissions = permissionsState;
8585
8586        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8587
8588        boolean runtimePermissionsRevoked = false;
8589        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8590
8591        boolean changedInstallPermission = false;
8592
8593        if (replace) {
8594            ps.installPermissionsFixed = false;
8595            if (!ps.isSharedUser()) {
8596                origPermissions = new PermissionsState(permissionsState);
8597                permissionsState.reset();
8598            } else {
8599                // We need to know only about runtime permission changes since the
8600                // calling code always writes the install permissions state but
8601                // the runtime ones are written only if changed. The only cases of
8602                // changed runtime permissions here are promotion of an install to
8603                // runtime and revocation of a runtime from a shared user.
8604                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8605                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8606                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8607                    runtimePermissionsRevoked = true;
8608                }
8609            }
8610        }
8611
8612        permissionsState.setGlobalGids(mGlobalGids);
8613
8614        final int N = pkg.requestedPermissions.size();
8615        for (int i=0; i<N; i++) {
8616            final String name = pkg.requestedPermissions.get(i);
8617            final BasePermission bp = mSettings.mPermissions.get(name);
8618
8619            if (DEBUG_INSTALL) {
8620                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8621            }
8622
8623            if (bp == null || bp.packageSetting == null) {
8624                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8625                    Slog.w(TAG, "Unknown permission " + name
8626                            + " in package " + pkg.packageName);
8627                }
8628                continue;
8629            }
8630
8631            final String perm = bp.name;
8632            boolean allowedSig = false;
8633            int grant = GRANT_DENIED;
8634
8635            // Keep track of app op permissions.
8636            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8637                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8638                if (pkgs == null) {
8639                    pkgs = new ArraySet<>();
8640                    mAppOpPermissionPackages.put(bp.name, pkgs);
8641                }
8642                pkgs.add(pkg.packageName);
8643            }
8644
8645            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8646            switch (level) {
8647                case PermissionInfo.PROTECTION_NORMAL: {
8648                    // For all apps normal permissions are install time ones.
8649                    grant = GRANT_INSTALL;
8650                } break;
8651
8652                case PermissionInfo.PROTECTION_DANGEROUS: {
8653                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8654                        // For legacy apps dangerous permissions are install time ones.
8655                        grant = GRANT_INSTALL_LEGACY;
8656                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8657                        // For legacy apps that became modern, install becomes runtime.
8658                        grant = GRANT_UPGRADE;
8659                    } else if (mPromoteSystemApps
8660                            && isSystemApp(ps)
8661                            && mExistingSystemPackages.contains(ps.name)) {
8662                        // For legacy system apps, install becomes runtime.
8663                        // We cannot check hasInstallPermission() for system apps since those
8664                        // permissions were granted implicitly and not persisted pre-M.
8665                        grant = GRANT_UPGRADE;
8666                    } else {
8667                        // For modern apps keep runtime permissions unchanged.
8668                        grant = GRANT_RUNTIME;
8669                    }
8670                } break;
8671
8672                case PermissionInfo.PROTECTION_SIGNATURE: {
8673                    // For all apps signature permissions are install time ones.
8674                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8675                    if (allowedSig) {
8676                        grant = GRANT_INSTALL;
8677                    }
8678                } break;
8679            }
8680
8681            if (DEBUG_INSTALL) {
8682                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8683            }
8684
8685            if (grant != GRANT_DENIED) {
8686                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8687                    // If this is an existing, non-system package, then
8688                    // we can't add any new permissions to it.
8689                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8690                        // Except...  if this is a permission that was added
8691                        // to the platform (note: need to only do this when
8692                        // updating the platform).
8693                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8694                            grant = GRANT_DENIED;
8695                        }
8696                    }
8697                }
8698
8699                switch (grant) {
8700                    case GRANT_INSTALL: {
8701                        // Revoke this as runtime permission to handle the case of
8702                        // a runtime permission being downgraded to an install one.
8703                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8704                            if (origPermissions.getRuntimePermissionState(
8705                                    bp.name, userId) != null) {
8706                                // Revoke the runtime permission and clear the flags.
8707                                origPermissions.revokeRuntimePermission(bp, userId);
8708                                origPermissions.updatePermissionFlags(bp, userId,
8709                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8710                                // If we revoked a permission permission, we have to write.
8711                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8712                                        changedRuntimePermissionUserIds, userId);
8713                            }
8714                        }
8715                        // Grant an install permission.
8716                        if (permissionsState.grantInstallPermission(bp) !=
8717                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8718                            changedInstallPermission = true;
8719                        }
8720                    } break;
8721
8722                    case GRANT_INSTALL_LEGACY: {
8723                        // Grant an install permission.
8724                        if (permissionsState.grantInstallPermission(bp) !=
8725                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8726                            changedInstallPermission = true;
8727                        }
8728                    } break;
8729
8730                    case GRANT_RUNTIME: {
8731                        // Grant previously granted runtime permissions.
8732                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8733                            PermissionState permissionState = origPermissions
8734                                    .getRuntimePermissionState(bp.name, userId);
8735                            final int flags = permissionState != null
8736                                    ? permissionState.getFlags() : 0;
8737                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8738                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8739                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8740                                    // If we cannot put the permission as it was, we have to write.
8741                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8742                                            changedRuntimePermissionUserIds, userId);
8743                                }
8744                            }
8745                            // Propagate the permission flags.
8746                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8747                        }
8748                    } break;
8749
8750                    case GRANT_UPGRADE: {
8751                        // Grant runtime permissions for a previously held install permission.
8752                        PermissionState permissionState = origPermissions
8753                                .getInstallPermissionState(bp.name);
8754                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8755
8756                        if (origPermissions.revokeInstallPermission(bp)
8757                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8758                            // We will be transferring the permission flags, so clear them.
8759                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8760                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8761                            changedInstallPermission = true;
8762                        }
8763
8764                        // If the permission is not to be promoted to runtime we ignore it and
8765                        // also its other flags as they are not applicable to install permissions.
8766                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8767                            for (int userId : currentUserIds) {
8768                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8769                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8770                                    // Transfer the permission flags.
8771                                    permissionsState.updatePermissionFlags(bp, userId,
8772                                            flags, flags);
8773                                    // If we granted the permission, we have to write.
8774                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8775                                            changedRuntimePermissionUserIds, userId);
8776                                }
8777                            }
8778                        }
8779                    } break;
8780
8781                    default: {
8782                        if (packageOfInterest == null
8783                                || packageOfInterest.equals(pkg.packageName)) {
8784                            Slog.w(TAG, "Not granting permission " + perm
8785                                    + " to package " + pkg.packageName
8786                                    + " because it was previously installed without");
8787                        }
8788                    } break;
8789                }
8790            } else {
8791                if (permissionsState.revokeInstallPermission(bp) !=
8792                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8793                    // Also drop the permission flags.
8794                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8795                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8796                    changedInstallPermission = true;
8797                    Slog.i(TAG, "Un-granting permission " + perm
8798                            + " from package " + pkg.packageName
8799                            + " (protectionLevel=" + bp.protectionLevel
8800                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8801                            + ")");
8802                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8803                    // Don't print warning for app op permissions, since it is fine for them
8804                    // not to be granted, there is a UI for the user to decide.
8805                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8806                        Slog.w(TAG, "Not granting permission " + perm
8807                                + " to package " + pkg.packageName
8808                                + " (protectionLevel=" + bp.protectionLevel
8809                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8810                                + ")");
8811                    }
8812                }
8813            }
8814        }
8815
8816        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8817                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8818            // This is the first that we have heard about this package, so the
8819            // permissions we have now selected are fixed until explicitly
8820            // changed.
8821            ps.installPermissionsFixed = true;
8822        }
8823
8824        // Persist the runtime permissions state for users with changes. If permissions
8825        // were revoked because no app in the shared user declares them we have to
8826        // write synchronously to avoid losing runtime permissions state.
8827        for (int userId : changedRuntimePermissionUserIds) {
8828            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8829        }
8830
8831        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8832    }
8833
8834    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8835        boolean allowed = false;
8836        final int NP = PackageParser.NEW_PERMISSIONS.length;
8837        for (int ip=0; ip<NP; ip++) {
8838            final PackageParser.NewPermissionInfo npi
8839                    = PackageParser.NEW_PERMISSIONS[ip];
8840            if (npi.name.equals(perm)
8841                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8842                allowed = true;
8843                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8844                        + pkg.packageName);
8845                break;
8846            }
8847        }
8848        return allowed;
8849    }
8850
8851    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8852            BasePermission bp, PermissionsState origPermissions) {
8853        boolean allowed;
8854        allowed = (compareSignatures(
8855                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8856                        == PackageManager.SIGNATURE_MATCH)
8857                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8858                        == PackageManager.SIGNATURE_MATCH);
8859        if (!allowed && (bp.protectionLevel
8860                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8861            if (isSystemApp(pkg)) {
8862                // For updated system applications, a system permission
8863                // is granted only if it had been defined by the original application.
8864                if (pkg.isUpdatedSystemApp()) {
8865                    final PackageSetting sysPs = mSettings
8866                            .getDisabledSystemPkgLPr(pkg.packageName);
8867                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8868                        // If the original was granted this permission, we take
8869                        // that grant decision as read and propagate it to the
8870                        // update.
8871                        if (sysPs.isPrivileged()) {
8872                            allowed = true;
8873                        }
8874                    } else {
8875                        // The system apk may have been updated with an older
8876                        // version of the one on the data partition, but which
8877                        // granted a new system permission that it didn't have
8878                        // before.  In this case we do want to allow the app to
8879                        // now get the new permission if the ancestral apk is
8880                        // privileged to get it.
8881                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8882                            for (int j=0;
8883                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8884                                if (perm.equals(
8885                                        sysPs.pkg.requestedPermissions.get(j))) {
8886                                    allowed = true;
8887                                    break;
8888                                }
8889                            }
8890                        }
8891                    }
8892                } else {
8893                    allowed = isPrivilegedApp(pkg);
8894                }
8895            }
8896        }
8897        if (!allowed) {
8898            if (!allowed && (bp.protectionLevel
8899                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8900                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8901                // If this was a previously normal/dangerous permission that got moved
8902                // to a system permission as part of the runtime permission redesign, then
8903                // we still want to blindly grant it to old apps.
8904                allowed = true;
8905            }
8906            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8907                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8908                // If this permission is to be granted to the system installer and
8909                // this app is an installer, then it gets the permission.
8910                allowed = true;
8911            }
8912            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8913                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8914                // If this permission is to be granted to the system verifier and
8915                // this app is a verifier, then it gets the permission.
8916                allowed = true;
8917            }
8918            if (!allowed && (bp.protectionLevel
8919                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8920                    && isSystemApp(pkg)) {
8921                // Any pre-installed system app is allowed to get this permission.
8922                allowed = true;
8923            }
8924            if (!allowed && (bp.protectionLevel
8925                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8926                // For development permissions, a development permission
8927                // is granted only if it was already granted.
8928                allowed = origPermissions.hasInstallPermission(perm);
8929            }
8930        }
8931        return allowed;
8932    }
8933
8934    final class ActivityIntentResolver
8935            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8936        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8937                boolean defaultOnly, int userId) {
8938            if (!sUserManager.exists(userId)) return null;
8939            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8940            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8941        }
8942
8943        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8944                int userId) {
8945            if (!sUserManager.exists(userId)) return null;
8946            mFlags = flags;
8947            return super.queryIntent(intent, resolvedType,
8948                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8949        }
8950
8951        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8952                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8953            if (!sUserManager.exists(userId)) return null;
8954            if (packageActivities == null) {
8955                return null;
8956            }
8957            mFlags = flags;
8958            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8959            final int N = packageActivities.size();
8960            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8961                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8962
8963            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8964            for (int i = 0; i < N; ++i) {
8965                intentFilters = packageActivities.get(i).intents;
8966                if (intentFilters != null && intentFilters.size() > 0) {
8967                    PackageParser.ActivityIntentInfo[] array =
8968                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8969                    intentFilters.toArray(array);
8970                    listCut.add(array);
8971                }
8972            }
8973            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8974        }
8975
8976        public final void addActivity(PackageParser.Activity a, String type) {
8977            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8978            mActivities.put(a.getComponentName(), a);
8979            if (DEBUG_SHOW_INFO)
8980                Log.v(
8981                TAG, "  " + type + " " +
8982                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8983            if (DEBUG_SHOW_INFO)
8984                Log.v(TAG, "    Class=" + a.info.name);
8985            final int NI = a.intents.size();
8986            for (int j=0; j<NI; j++) {
8987                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8988                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8989                    intent.setPriority(0);
8990                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8991                            + a.className + " with priority > 0, forcing to 0");
8992                }
8993                if (DEBUG_SHOW_INFO) {
8994                    Log.v(TAG, "    IntentFilter:");
8995                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8996                }
8997                if (!intent.debugCheck()) {
8998                    Log.w(TAG, "==> For Activity " + a.info.name);
8999                }
9000                addFilter(intent);
9001            }
9002        }
9003
9004        public final void removeActivity(PackageParser.Activity a, String type) {
9005            mActivities.remove(a.getComponentName());
9006            if (DEBUG_SHOW_INFO) {
9007                Log.v(TAG, "  " + type + " "
9008                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9009                                : a.info.name) + ":");
9010                Log.v(TAG, "    Class=" + a.info.name);
9011            }
9012            final int NI = a.intents.size();
9013            for (int j=0; j<NI; j++) {
9014                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9015                if (DEBUG_SHOW_INFO) {
9016                    Log.v(TAG, "    IntentFilter:");
9017                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9018                }
9019                removeFilter(intent);
9020            }
9021        }
9022
9023        @Override
9024        protected boolean allowFilterResult(
9025                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9026            ActivityInfo filterAi = filter.activity.info;
9027            for (int i=dest.size()-1; i>=0; i--) {
9028                ActivityInfo destAi = dest.get(i).activityInfo;
9029                if (destAi.name == filterAi.name
9030                        && destAi.packageName == filterAi.packageName) {
9031                    return false;
9032                }
9033            }
9034            return true;
9035        }
9036
9037        @Override
9038        protected ActivityIntentInfo[] newArray(int size) {
9039            return new ActivityIntentInfo[size];
9040        }
9041
9042        @Override
9043        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9044            if (!sUserManager.exists(userId)) return true;
9045            PackageParser.Package p = filter.activity.owner;
9046            if (p != null) {
9047                PackageSetting ps = (PackageSetting)p.mExtras;
9048                if (ps != null) {
9049                    // System apps are never considered stopped for purposes of
9050                    // filtering, because there may be no way for the user to
9051                    // actually re-launch them.
9052                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9053                            && ps.getStopped(userId);
9054                }
9055            }
9056            return false;
9057        }
9058
9059        @Override
9060        protected boolean isPackageForFilter(String packageName,
9061                PackageParser.ActivityIntentInfo info) {
9062            return packageName.equals(info.activity.owner.packageName);
9063        }
9064
9065        @Override
9066        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9067                int match, int userId) {
9068            if (!sUserManager.exists(userId)) return null;
9069            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9070                return null;
9071            }
9072            final PackageParser.Activity activity = info.activity;
9073            if (mSafeMode && (activity.info.applicationInfo.flags
9074                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9075                return null;
9076            }
9077            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9078            if (ps == null) {
9079                return null;
9080            }
9081            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9082                    ps.readUserState(userId), userId);
9083            if (ai == null) {
9084                return null;
9085            }
9086            final ResolveInfo res = new ResolveInfo();
9087            res.activityInfo = ai;
9088            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9089                res.filter = info;
9090            }
9091            if (info != null) {
9092                res.handleAllWebDataURI = info.handleAllWebDataURI();
9093            }
9094            res.priority = info.getPriority();
9095            res.preferredOrder = activity.owner.mPreferredOrder;
9096            //System.out.println("Result: " + res.activityInfo.className +
9097            //                   " = " + res.priority);
9098            res.match = match;
9099            res.isDefault = info.hasDefault;
9100            res.labelRes = info.labelRes;
9101            res.nonLocalizedLabel = info.nonLocalizedLabel;
9102            if (userNeedsBadging(userId)) {
9103                res.noResourceId = true;
9104            } else {
9105                res.icon = info.icon;
9106            }
9107            res.iconResourceId = info.icon;
9108            res.system = res.activityInfo.applicationInfo.isSystemApp();
9109            return res;
9110        }
9111
9112        @Override
9113        protected void sortResults(List<ResolveInfo> results) {
9114            Collections.sort(results, mResolvePrioritySorter);
9115        }
9116
9117        @Override
9118        protected void dumpFilter(PrintWriter out, String prefix,
9119                PackageParser.ActivityIntentInfo filter) {
9120            out.print(prefix); out.print(
9121                    Integer.toHexString(System.identityHashCode(filter.activity)));
9122                    out.print(' ');
9123                    filter.activity.printComponentShortName(out);
9124                    out.print(" filter ");
9125                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9126        }
9127
9128        @Override
9129        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9130            return filter.activity;
9131        }
9132
9133        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9134            PackageParser.Activity activity = (PackageParser.Activity)label;
9135            out.print(prefix); out.print(
9136                    Integer.toHexString(System.identityHashCode(activity)));
9137                    out.print(' ');
9138                    activity.printComponentShortName(out);
9139            if (count > 1) {
9140                out.print(" ("); out.print(count); out.print(" filters)");
9141            }
9142            out.println();
9143        }
9144
9145//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9146//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9147//            final List<ResolveInfo> retList = Lists.newArrayList();
9148//            while (i.hasNext()) {
9149//                final ResolveInfo resolveInfo = i.next();
9150//                if (isEnabledLP(resolveInfo.activityInfo)) {
9151//                    retList.add(resolveInfo);
9152//                }
9153//            }
9154//            return retList;
9155//        }
9156
9157        // Keys are String (activity class name), values are Activity.
9158        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9159                = new ArrayMap<ComponentName, PackageParser.Activity>();
9160        private int mFlags;
9161    }
9162
9163    private final class ServiceIntentResolver
9164            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9165        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9166                boolean defaultOnly, int userId) {
9167            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9168            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9169        }
9170
9171        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9172                int userId) {
9173            if (!sUserManager.exists(userId)) return null;
9174            mFlags = flags;
9175            return super.queryIntent(intent, resolvedType,
9176                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9177        }
9178
9179        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9180                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9181            if (!sUserManager.exists(userId)) return null;
9182            if (packageServices == null) {
9183                return null;
9184            }
9185            mFlags = flags;
9186            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9187            final int N = packageServices.size();
9188            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9189                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9190
9191            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9192            for (int i = 0; i < N; ++i) {
9193                intentFilters = packageServices.get(i).intents;
9194                if (intentFilters != null && intentFilters.size() > 0) {
9195                    PackageParser.ServiceIntentInfo[] array =
9196                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9197                    intentFilters.toArray(array);
9198                    listCut.add(array);
9199                }
9200            }
9201            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9202        }
9203
9204        public final void addService(PackageParser.Service s) {
9205            mServices.put(s.getComponentName(), s);
9206            if (DEBUG_SHOW_INFO) {
9207                Log.v(TAG, "  "
9208                        + (s.info.nonLocalizedLabel != null
9209                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9210                Log.v(TAG, "    Class=" + s.info.name);
9211            }
9212            final int NI = s.intents.size();
9213            int j;
9214            for (j=0; j<NI; j++) {
9215                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9216                if (DEBUG_SHOW_INFO) {
9217                    Log.v(TAG, "    IntentFilter:");
9218                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9219                }
9220                if (!intent.debugCheck()) {
9221                    Log.w(TAG, "==> For Service " + s.info.name);
9222                }
9223                addFilter(intent);
9224            }
9225        }
9226
9227        public final void removeService(PackageParser.Service s) {
9228            mServices.remove(s.getComponentName());
9229            if (DEBUG_SHOW_INFO) {
9230                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9231                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9232                Log.v(TAG, "    Class=" + s.info.name);
9233            }
9234            final int NI = s.intents.size();
9235            int j;
9236            for (j=0; j<NI; j++) {
9237                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9238                if (DEBUG_SHOW_INFO) {
9239                    Log.v(TAG, "    IntentFilter:");
9240                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9241                }
9242                removeFilter(intent);
9243            }
9244        }
9245
9246        @Override
9247        protected boolean allowFilterResult(
9248                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9249            ServiceInfo filterSi = filter.service.info;
9250            for (int i=dest.size()-1; i>=0; i--) {
9251                ServiceInfo destAi = dest.get(i).serviceInfo;
9252                if (destAi.name == filterSi.name
9253                        && destAi.packageName == filterSi.packageName) {
9254                    return false;
9255                }
9256            }
9257            return true;
9258        }
9259
9260        @Override
9261        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9262            return new PackageParser.ServiceIntentInfo[size];
9263        }
9264
9265        @Override
9266        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9267            if (!sUserManager.exists(userId)) return true;
9268            PackageParser.Package p = filter.service.owner;
9269            if (p != null) {
9270                PackageSetting ps = (PackageSetting)p.mExtras;
9271                if (ps != null) {
9272                    // System apps are never considered stopped for purposes of
9273                    // filtering, because there may be no way for the user to
9274                    // actually re-launch them.
9275                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9276                            && ps.getStopped(userId);
9277                }
9278            }
9279            return false;
9280        }
9281
9282        @Override
9283        protected boolean isPackageForFilter(String packageName,
9284                PackageParser.ServiceIntentInfo info) {
9285            return packageName.equals(info.service.owner.packageName);
9286        }
9287
9288        @Override
9289        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9290                int match, int userId) {
9291            if (!sUserManager.exists(userId)) return null;
9292            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9293            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9294                return null;
9295            }
9296            final PackageParser.Service service = info.service;
9297            if (mSafeMode && (service.info.applicationInfo.flags
9298                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9299                return null;
9300            }
9301            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9302            if (ps == null) {
9303                return null;
9304            }
9305            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9306                    ps.readUserState(userId), userId);
9307            if (si == null) {
9308                return null;
9309            }
9310            final ResolveInfo res = new ResolveInfo();
9311            res.serviceInfo = si;
9312            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9313                res.filter = filter;
9314            }
9315            res.priority = info.getPriority();
9316            res.preferredOrder = service.owner.mPreferredOrder;
9317            res.match = match;
9318            res.isDefault = info.hasDefault;
9319            res.labelRes = info.labelRes;
9320            res.nonLocalizedLabel = info.nonLocalizedLabel;
9321            res.icon = info.icon;
9322            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9323            return res;
9324        }
9325
9326        @Override
9327        protected void sortResults(List<ResolveInfo> results) {
9328            Collections.sort(results, mResolvePrioritySorter);
9329        }
9330
9331        @Override
9332        protected void dumpFilter(PrintWriter out, String prefix,
9333                PackageParser.ServiceIntentInfo filter) {
9334            out.print(prefix); out.print(
9335                    Integer.toHexString(System.identityHashCode(filter.service)));
9336                    out.print(' ');
9337                    filter.service.printComponentShortName(out);
9338                    out.print(" filter ");
9339                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9340        }
9341
9342        @Override
9343        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9344            return filter.service;
9345        }
9346
9347        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9348            PackageParser.Service service = (PackageParser.Service)label;
9349            out.print(prefix); out.print(
9350                    Integer.toHexString(System.identityHashCode(service)));
9351                    out.print(' ');
9352                    service.printComponentShortName(out);
9353            if (count > 1) {
9354                out.print(" ("); out.print(count); out.print(" filters)");
9355            }
9356            out.println();
9357        }
9358
9359//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9360//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9361//            final List<ResolveInfo> retList = Lists.newArrayList();
9362//            while (i.hasNext()) {
9363//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9364//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9365//                    retList.add(resolveInfo);
9366//                }
9367//            }
9368//            return retList;
9369//        }
9370
9371        // Keys are String (activity class name), values are Activity.
9372        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9373                = new ArrayMap<ComponentName, PackageParser.Service>();
9374        private int mFlags;
9375    };
9376
9377    private final class ProviderIntentResolver
9378            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9379        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9380                boolean defaultOnly, int userId) {
9381            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9382            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9383        }
9384
9385        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9386                int userId) {
9387            if (!sUserManager.exists(userId))
9388                return null;
9389            mFlags = flags;
9390            return super.queryIntent(intent, resolvedType,
9391                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9392        }
9393
9394        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9395                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9396            if (!sUserManager.exists(userId))
9397                return null;
9398            if (packageProviders == null) {
9399                return null;
9400            }
9401            mFlags = flags;
9402            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9403            final int N = packageProviders.size();
9404            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9405                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9406
9407            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9408            for (int i = 0; i < N; ++i) {
9409                intentFilters = packageProviders.get(i).intents;
9410                if (intentFilters != null && intentFilters.size() > 0) {
9411                    PackageParser.ProviderIntentInfo[] array =
9412                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9413                    intentFilters.toArray(array);
9414                    listCut.add(array);
9415                }
9416            }
9417            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9418        }
9419
9420        public final void addProvider(PackageParser.Provider p) {
9421            if (mProviders.containsKey(p.getComponentName())) {
9422                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9423                return;
9424            }
9425
9426            mProviders.put(p.getComponentName(), p);
9427            if (DEBUG_SHOW_INFO) {
9428                Log.v(TAG, "  "
9429                        + (p.info.nonLocalizedLabel != null
9430                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9431                Log.v(TAG, "    Class=" + p.info.name);
9432            }
9433            final int NI = p.intents.size();
9434            int j;
9435            for (j = 0; j < NI; j++) {
9436                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9437                if (DEBUG_SHOW_INFO) {
9438                    Log.v(TAG, "    IntentFilter:");
9439                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9440                }
9441                if (!intent.debugCheck()) {
9442                    Log.w(TAG, "==> For Provider " + p.info.name);
9443                }
9444                addFilter(intent);
9445            }
9446        }
9447
9448        public final void removeProvider(PackageParser.Provider p) {
9449            mProviders.remove(p.getComponentName());
9450            if (DEBUG_SHOW_INFO) {
9451                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9452                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9453                Log.v(TAG, "    Class=" + p.info.name);
9454            }
9455            final int NI = p.intents.size();
9456            int j;
9457            for (j = 0; j < NI; j++) {
9458                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9459                if (DEBUG_SHOW_INFO) {
9460                    Log.v(TAG, "    IntentFilter:");
9461                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9462                }
9463                removeFilter(intent);
9464            }
9465        }
9466
9467        @Override
9468        protected boolean allowFilterResult(
9469                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9470            ProviderInfo filterPi = filter.provider.info;
9471            for (int i = dest.size() - 1; i >= 0; i--) {
9472                ProviderInfo destPi = dest.get(i).providerInfo;
9473                if (destPi.name == filterPi.name
9474                        && destPi.packageName == filterPi.packageName) {
9475                    return false;
9476                }
9477            }
9478            return true;
9479        }
9480
9481        @Override
9482        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9483            return new PackageParser.ProviderIntentInfo[size];
9484        }
9485
9486        @Override
9487        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9488            if (!sUserManager.exists(userId))
9489                return true;
9490            PackageParser.Package p = filter.provider.owner;
9491            if (p != null) {
9492                PackageSetting ps = (PackageSetting) p.mExtras;
9493                if (ps != null) {
9494                    // System apps are never considered stopped for purposes of
9495                    // filtering, because there may be no way for the user to
9496                    // actually re-launch them.
9497                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9498                            && ps.getStopped(userId);
9499                }
9500            }
9501            return false;
9502        }
9503
9504        @Override
9505        protected boolean isPackageForFilter(String packageName,
9506                PackageParser.ProviderIntentInfo info) {
9507            return packageName.equals(info.provider.owner.packageName);
9508        }
9509
9510        @Override
9511        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9512                int match, int userId) {
9513            if (!sUserManager.exists(userId))
9514                return null;
9515            final PackageParser.ProviderIntentInfo info = filter;
9516            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9517                return null;
9518            }
9519            final PackageParser.Provider provider = info.provider;
9520            if (mSafeMode && (provider.info.applicationInfo.flags
9521                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9522                return null;
9523            }
9524            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9525            if (ps == null) {
9526                return null;
9527            }
9528            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9529                    ps.readUserState(userId), userId);
9530            if (pi == null) {
9531                return null;
9532            }
9533            final ResolveInfo res = new ResolveInfo();
9534            res.providerInfo = pi;
9535            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9536                res.filter = filter;
9537            }
9538            res.priority = info.getPriority();
9539            res.preferredOrder = provider.owner.mPreferredOrder;
9540            res.match = match;
9541            res.isDefault = info.hasDefault;
9542            res.labelRes = info.labelRes;
9543            res.nonLocalizedLabel = info.nonLocalizedLabel;
9544            res.icon = info.icon;
9545            res.system = res.providerInfo.applicationInfo.isSystemApp();
9546            return res;
9547        }
9548
9549        @Override
9550        protected void sortResults(List<ResolveInfo> results) {
9551            Collections.sort(results, mResolvePrioritySorter);
9552        }
9553
9554        @Override
9555        protected void dumpFilter(PrintWriter out, String prefix,
9556                PackageParser.ProviderIntentInfo filter) {
9557            out.print(prefix);
9558            out.print(
9559                    Integer.toHexString(System.identityHashCode(filter.provider)));
9560            out.print(' ');
9561            filter.provider.printComponentShortName(out);
9562            out.print(" filter ");
9563            out.println(Integer.toHexString(System.identityHashCode(filter)));
9564        }
9565
9566        @Override
9567        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9568            return filter.provider;
9569        }
9570
9571        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9572            PackageParser.Provider provider = (PackageParser.Provider)label;
9573            out.print(prefix); out.print(
9574                    Integer.toHexString(System.identityHashCode(provider)));
9575                    out.print(' ');
9576                    provider.printComponentShortName(out);
9577            if (count > 1) {
9578                out.print(" ("); out.print(count); out.print(" filters)");
9579            }
9580            out.println();
9581        }
9582
9583        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9584                = new ArrayMap<ComponentName, PackageParser.Provider>();
9585        private int mFlags;
9586    }
9587
9588    private static final class EphemeralIntentResolver
9589            extends IntentResolver<IntentFilter, ResolveInfo> {
9590        @Override
9591        protected IntentFilter[] newArray(int size) {
9592            return new IntentFilter[size];
9593        }
9594
9595        @Override
9596        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9597            return true;
9598        }
9599
9600        @Override
9601        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9602            if (!sUserManager.exists(userId)) return null;
9603            final ResolveInfo res = new ResolveInfo();
9604            res.filter = info;
9605            return res;
9606        }
9607    }
9608
9609    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9610            new Comparator<ResolveInfo>() {
9611        public int compare(ResolveInfo r1, ResolveInfo r2) {
9612            int v1 = r1.priority;
9613            int v2 = r2.priority;
9614            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9615            if (v1 != v2) {
9616                return (v1 > v2) ? -1 : 1;
9617            }
9618            v1 = r1.preferredOrder;
9619            v2 = r2.preferredOrder;
9620            if (v1 != v2) {
9621                return (v1 > v2) ? -1 : 1;
9622            }
9623            if (r1.isDefault != r2.isDefault) {
9624                return r1.isDefault ? -1 : 1;
9625            }
9626            v1 = r1.match;
9627            v2 = r2.match;
9628            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9629            if (v1 != v2) {
9630                return (v1 > v2) ? -1 : 1;
9631            }
9632            if (r1.system != r2.system) {
9633                return r1.system ? -1 : 1;
9634            }
9635            return 0;
9636        }
9637    };
9638
9639    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9640            new Comparator<ProviderInfo>() {
9641        public int compare(ProviderInfo p1, ProviderInfo p2) {
9642            final int v1 = p1.initOrder;
9643            final int v2 = p2.initOrder;
9644            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9645        }
9646    };
9647
9648    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9649            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9650            final int[] userIds) {
9651        mHandler.post(new Runnable() {
9652            @Override
9653            public void run() {
9654                try {
9655                    final IActivityManager am = ActivityManagerNative.getDefault();
9656                    if (am == null) return;
9657                    final int[] resolvedUserIds;
9658                    if (userIds == null) {
9659                        resolvedUserIds = am.getRunningUserIds();
9660                    } else {
9661                        resolvedUserIds = userIds;
9662                    }
9663                    for (int id : resolvedUserIds) {
9664                        final Intent intent = new Intent(action,
9665                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9666                        if (extras != null) {
9667                            intent.putExtras(extras);
9668                        }
9669                        if (targetPkg != null) {
9670                            intent.setPackage(targetPkg);
9671                        }
9672                        // Modify the UID when posting to other users
9673                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9674                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9675                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9676                            intent.putExtra(Intent.EXTRA_UID, uid);
9677                        }
9678                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9679                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9680                        if (DEBUG_BROADCASTS) {
9681                            RuntimeException here = new RuntimeException("here");
9682                            here.fillInStackTrace();
9683                            Slog.d(TAG, "Sending to user " + id + ": "
9684                                    + intent.toShortString(false, true, false, false)
9685                                    + " " + intent.getExtras(), here);
9686                        }
9687                        am.broadcastIntent(null, intent, null, finishedReceiver,
9688                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9689                                null, finishedReceiver != null, false, id);
9690                    }
9691                } catch (RemoteException ex) {
9692                }
9693            }
9694        });
9695    }
9696
9697    /**
9698     * Check if the external storage media is available. This is true if there
9699     * is a mounted external storage medium or if the external storage is
9700     * emulated.
9701     */
9702    private boolean isExternalMediaAvailable() {
9703        return mMediaMounted || Environment.isExternalStorageEmulated();
9704    }
9705
9706    @Override
9707    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9708        // writer
9709        synchronized (mPackages) {
9710            if (!isExternalMediaAvailable()) {
9711                // If the external storage is no longer mounted at this point,
9712                // the caller may not have been able to delete all of this
9713                // packages files and can not delete any more.  Bail.
9714                return null;
9715            }
9716            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9717            if (lastPackage != null) {
9718                pkgs.remove(lastPackage);
9719            }
9720            if (pkgs.size() > 0) {
9721                return pkgs.get(0);
9722            }
9723        }
9724        return null;
9725    }
9726
9727    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9728        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9729                userId, andCode ? 1 : 0, packageName);
9730        if (mSystemReady) {
9731            msg.sendToTarget();
9732        } else {
9733            if (mPostSystemReadyMessages == null) {
9734                mPostSystemReadyMessages = new ArrayList<>();
9735            }
9736            mPostSystemReadyMessages.add(msg);
9737        }
9738    }
9739
9740    void startCleaningPackages() {
9741        // reader
9742        synchronized (mPackages) {
9743            if (!isExternalMediaAvailable()) {
9744                return;
9745            }
9746            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9747                return;
9748            }
9749        }
9750        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9751        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9752        IActivityManager am = ActivityManagerNative.getDefault();
9753        if (am != null) {
9754            try {
9755                am.startService(null, intent, null, mContext.getOpPackageName(),
9756                        UserHandle.USER_SYSTEM);
9757            } catch (RemoteException e) {
9758            }
9759        }
9760    }
9761
9762    @Override
9763    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9764            int installFlags, String installerPackageName, VerificationParams verificationParams,
9765            String packageAbiOverride) {
9766        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9767                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9768    }
9769
9770    @Override
9771    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9772            int installFlags, String installerPackageName, VerificationParams verificationParams,
9773            String packageAbiOverride, int userId) {
9774        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9775
9776        final int callingUid = Binder.getCallingUid();
9777        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9778
9779        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9780            try {
9781                if (observer != null) {
9782                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9783                }
9784            } catch (RemoteException re) {
9785            }
9786            return;
9787        }
9788
9789        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9790            installFlags |= PackageManager.INSTALL_FROM_ADB;
9791
9792        } else {
9793            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9794            // about installerPackageName.
9795
9796            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9797            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9798        }
9799
9800        UserHandle user;
9801        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9802            user = UserHandle.ALL;
9803        } else {
9804            user = new UserHandle(userId);
9805        }
9806
9807        // Only system components can circumvent runtime permissions when installing.
9808        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9809                && mContext.checkCallingOrSelfPermission(Manifest.permission
9810                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9811            throw new SecurityException("You need the "
9812                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9813                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9814        }
9815
9816        verificationParams.setInstallerUid(callingUid);
9817
9818        final File originFile = new File(originPath);
9819        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9820
9821        final Message msg = mHandler.obtainMessage(INIT_COPY);
9822        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9823                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9824        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9825        msg.obj = params;
9826
9827        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9828                System.identityHashCode(msg.obj));
9829        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9830                System.identityHashCode(msg.obj));
9831
9832        mHandler.sendMessage(msg);
9833    }
9834
9835    void installStage(String packageName, File stagedDir, String stagedCid,
9836            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9837            String installerPackageName, int installerUid, UserHandle user) {
9838        final VerificationParams verifParams = new VerificationParams(
9839                null, sessionParams.originatingUri, sessionParams.referrerUri,
9840                sessionParams.originatingUid, null);
9841        verifParams.setInstallerUid(installerUid);
9842
9843        final OriginInfo origin;
9844        if (stagedDir != null) {
9845            origin = OriginInfo.fromStagedFile(stagedDir);
9846        } else {
9847            origin = OriginInfo.fromStagedContainer(stagedCid);
9848        }
9849
9850        final Message msg = mHandler.obtainMessage(INIT_COPY);
9851        final InstallParams params = new InstallParams(origin, null, observer,
9852                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9853                verifParams, user, sessionParams.abiOverride,
9854                sessionParams.grantedRuntimePermissions);
9855        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9856        msg.obj = params;
9857
9858        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9859                System.identityHashCode(msg.obj));
9860        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9861                System.identityHashCode(msg.obj));
9862
9863        mHandler.sendMessage(msg);
9864    }
9865
9866    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9867        Bundle extras = new Bundle(1);
9868        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9869
9870        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9871                packageName, extras, 0, null, null, new int[] {userId});
9872        try {
9873            IActivityManager am = ActivityManagerNative.getDefault();
9874            final boolean isSystem =
9875                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9876            if (isSystem && am.isUserRunning(userId, 0)) {
9877                // The just-installed/enabled app is bundled on the system, so presumed
9878                // to be able to run automatically without needing an explicit launch.
9879                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9880                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9881                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9882                        .setPackage(packageName);
9883                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9884                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9885            }
9886        } catch (RemoteException e) {
9887            // shouldn't happen
9888            Slog.w(TAG, "Unable to bootstrap installed package", e);
9889        }
9890    }
9891
9892    @Override
9893    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9894            int userId) {
9895        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9896        PackageSetting pkgSetting;
9897        final int uid = Binder.getCallingUid();
9898        enforceCrossUserPermission(uid, userId, true, true,
9899                "setApplicationHiddenSetting for user " + userId);
9900
9901        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9902            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9903            return false;
9904        }
9905
9906        long callingId = Binder.clearCallingIdentity();
9907        try {
9908            boolean sendAdded = false;
9909            boolean sendRemoved = false;
9910            // writer
9911            synchronized (mPackages) {
9912                pkgSetting = mSettings.mPackages.get(packageName);
9913                if (pkgSetting == null) {
9914                    return false;
9915                }
9916                if (pkgSetting.getHidden(userId) != hidden) {
9917                    pkgSetting.setHidden(hidden, userId);
9918                    mSettings.writePackageRestrictionsLPr(userId);
9919                    if (hidden) {
9920                        sendRemoved = true;
9921                    } else {
9922                        sendAdded = true;
9923                    }
9924                }
9925            }
9926            if (sendAdded) {
9927                sendPackageAddedForUser(packageName, pkgSetting, userId);
9928                return true;
9929            }
9930            if (sendRemoved) {
9931                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9932                        "hiding pkg");
9933                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9934                return true;
9935            }
9936        } finally {
9937            Binder.restoreCallingIdentity(callingId);
9938        }
9939        return false;
9940    }
9941
9942    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9943            int userId) {
9944        final PackageRemovedInfo info = new PackageRemovedInfo();
9945        info.removedPackage = packageName;
9946        info.removedUsers = new int[] {userId};
9947        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9948        info.sendBroadcast(false, false, false);
9949    }
9950
9951    /**
9952     * Returns true if application is not found or there was an error. Otherwise it returns
9953     * the hidden state of the package for the given user.
9954     */
9955    @Override
9956    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9958        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9959                false, "getApplicationHidden for user " + userId);
9960        PackageSetting pkgSetting;
9961        long callingId = Binder.clearCallingIdentity();
9962        try {
9963            // writer
9964            synchronized (mPackages) {
9965                pkgSetting = mSettings.mPackages.get(packageName);
9966                if (pkgSetting == null) {
9967                    return true;
9968                }
9969                return pkgSetting.getHidden(userId);
9970            }
9971        } finally {
9972            Binder.restoreCallingIdentity(callingId);
9973        }
9974    }
9975
9976    /**
9977     * @hide
9978     */
9979    @Override
9980    public int installExistingPackageAsUser(String packageName, int userId) {
9981        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9982                null);
9983        PackageSetting pkgSetting;
9984        final int uid = Binder.getCallingUid();
9985        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9986                + userId);
9987        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9988            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9989        }
9990
9991        long callingId = Binder.clearCallingIdentity();
9992        try {
9993            boolean sendAdded = false;
9994
9995            // writer
9996            synchronized (mPackages) {
9997                pkgSetting = mSettings.mPackages.get(packageName);
9998                if (pkgSetting == null) {
9999                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10000                }
10001                if (!pkgSetting.getInstalled(userId)) {
10002                    pkgSetting.setInstalled(true, userId);
10003                    pkgSetting.setHidden(false, userId);
10004                    mSettings.writePackageRestrictionsLPr(userId);
10005                    sendAdded = true;
10006                }
10007            }
10008
10009            if (sendAdded) {
10010                sendPackageAddedForUser(packageName, pkgSetting, userId);
10011            }
10012        } finally {
10013            Binder.restoreCallingIdentity(callingId);
10014        }
10015
10016        return PackageManager.INSTALL_SUCCEEDED;
10017    }
10018
10019    boolean isUserRestricted(int userId, String restrictionKey) {
10020        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10021        if (restrictions.getBoolean(restrictionKey, false)) {
10022            Log.w(TAG, "User is restricted: " + restrictionKey);
10023            return true;
10024        }
10025        return false;
10026    }
10027
10028    @Override
10029    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10030        mContext.enforceCallingOrSelfPermission(
10031                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10032                "Only package verification agents can verify applications");
10033
10034        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10035        final PackageVerificationResponse response = new PackageVerificationResponse(
10036                verificationCode, Binder.getCallingUid());
10037        msg.arg1 = id;
10038        msg.obj = response;
10039        mHandler.sendMessage(msg);
10040    }
10041
10042    @Override
10043    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10044            long millisecondsToDelay) {
10045        mContext.enforceCallingOrSelfPermission(
10046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10047                "Only package verification agents can extend verification timeouts");
10048
10049        final PackageVerificationState state = mPendingVerification.get(id);
10050        final PackageVerificationResponse response = new PackageVerificationResponse(
10051                verificationCodeAtTimeout, Binder.getCallingUid());
10052
10053        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10054            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10055        }
10056        if (millisecondsToDelay < 0) {
10057            millisecondsToDelay = 0;
10058        }
10059        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10060                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10061            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10062        }
10063
10064        if ((state != null) && !state.timeoutExtended()) {
10065            state.extendTimeout();
10066
10067            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10068            msg.arg1 = id;
10069            msg.obj = response;
10070            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10071        }
10072    }
10073
10074    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10075            int verificationCode, UserHandle user) {
10076        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10077        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10078        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10079        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10080        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10081
10082        mContext.sendBroadcastAsUser(intent, user,
10083                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10084    }
10085
10086    private ComponentName matchComponentForVerifier(String packageName,
10087            List<ResolveInfo> receivers) {
10088        ActivityInfo targetReceiver = null;
10089
10090        final int NR = receivers.size();
10091        for (int i = 0; i < NR; i++) {
10092            final ResolveInfo info = receivers.get(i);
10093            if (info.activityInfo == null) {
10094                continue;
10095            }
10096
10097            if (packageName.equals(info.activityInfo.packageName)) {
10098                targetReceiver = info.activityInfo;
10099                break;
10100            }
10101        }
10102
10103        if (targetReceiver == null) {
10104            return null;
10105        }
10106
10107        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10108    }
10109
10110    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10111            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10112        if (pkgInfo.verifiers.length == 0) {
10113            return null;
10114        }
10115
10116        final int N = pkgInfo.verifiers.length;
10117        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10118        for (int i = 0; i < N; i++) {
10119            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10120
10121            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10122                    receivers);
10123            if (comp == null) {
10124                continue;
10125            }
10126
10127            final int verifierUid = getUidForVerifier(verifierInfo);
10128            if (verifierUid == -1) {
10129                continue;
10130            }
10131
10132            if (DEBUG_VERIFY) {
10133                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10134                        + " with the correct signature");
10135            }
10136            sufficientVerifiers.add(comp);
10137            verificationState.addSufficientVerifier(verifierUid);
10138        }
10139
10140        return sufficientVerifiers;
10141    }
10142
10143    private int getUidForVerifier(VerifierInfo verifierInfo) {
10144        synchronized (mPackages) {
10145            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10146            if (pkg == null) {
10147                return -1;
10148            } else if (pkg.mSignatures.length != 1) {
10149                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10150                        + " has more than one signature; ignoring");
10151                return -1;
10152            }
10153
10154            /*
10155             * If the public key of the package's signature does not match
10156             * our expected public key, then this is a different package and
10157             * we should skip.
10158             */
10159
10160            final byte[] expectedPublicKey;
10161            try {
10162                final Signature verifierSig = pkg.mSignatures[0];
10163                final PublicKey publicKey = verifierSig.getPublicKey();
10164                expectedPublicKey = publicKey.getEncoded();
10165            } catch (CertificateException e) {
10166                return -1;
10167            }
10168
10169            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10170
10171            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10172                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10173                        + " does not have the expected public key; ignoring");
10174                return -1;
10175            }
10176
10177            return pkg.applicationInfo.uid;
10178        }
10179    }
10180
10181    @Override
10182    public void finishPackageInstall(int token) {
10183        enforceSystemOrRoot("Only the system is allowed to finish installs");
10184
10185        if (DEBUG_INSTALL) {
10186            Slog.v(TAG, "BM finishing package install for " + token);
10187        }
10188        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10189
10190        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10191        mHandler.sendMessage(msg);
10192    }
10193
10194    /**
10195     * Get the verification agent timeout.
10196     *
10197     * @return verification timeout in milliseconds
10198     */
10199    private long getVerificationTimeout() {
10200        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10201                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10202                DEFAULT_VERIFICATION_TIMEOUT);
10203    }
10204
10205    /**
10206     * Get the default verification agent response code.
10207     *
10208     * @return default verification response code
10209     */
10210    private int getDefaultVerificationResponse() {
10211        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10212                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10213                DEFAULT_VERIFICATION_RESPONSE);
10214    }
10215
10216    /**
10217     * Check whether or not package verification has been enabled.
10218     *
10219     * @return true if verification should be performed
10220     */
10221    private boolean isVerificationEnabled(int userId, int installFlags) {
10222        if (!DEFAULT_VERIFY_ENABLE) {
10223            return false;
10224        }
10225        // TODO: fix b/25118622; don't bypass verification
10226        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10227            return false;
10228        }
10229
10230        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10231
10232        // Check if installing from ADB
10233        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10234            // Do not run verification in a test harness environment
10235            if (ActivityManager.isRunningInTestHarness()) {
10236                return false;
10237            }
10238            if (ensureVerifyAppsEnabled) {
10239                return true;
10240            }
10241            // Check if the developer does not want package verification for ADB installs
10242            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10243                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10244                return false;
10245            }
10246        }
10247
10248        if (ensureVerifyAppsEnabled) {
10249            return true;
10250        }
10251
10252        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10253                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10254    }
10255
10256    @Override
10257    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10258            throws RemoteException {
10259        mContext.enforceCallingOrSelfPermission(
10260                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10261                "Only intentfilter verification agents can verify applications");
10262
10263        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10264        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10265                Binder.getCallingUid(), verificationCode, failedDomains);
10266        msg.arg1 = id;
10267        msg.obj = response;
10268        mHandler.sendMessage(msg);
10269    }
10270
10271    @Override
10272    public int getIntentVerificationStatus(String packageName, int userId) {
10273        synchronized (mPackages) {
10274            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10275        }
10276    }
10277
10278    @Override
10279    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10280        mContext.enforceCallingOrSelfPermission(
10281                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10282
10283        boolean result = false;
10284        synchronized (mPackages) {
10285            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10286        }
10287        if (result) {
10288            scheduleWritePackageRestrictionsLocked(userId);
10289        }
10290        return result;
10291    }
10292
10293    @Override
10294    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10295        synchronized (mPackages) {
10296            return mSettings.getIntentFilterVerificationsLPr(packageName);
10297        }
10298    }
10299
10300    @Override
10301    public List<IntentFilter> getAllIntentFilters(String packageName) {
10302        if (TextUtils.isEmpty(packageName)) {
10303            return Collections.<IntentFilter>emptyList();
10304        }
10305        synchronized (mPackages) {
10306            PackageParser.Package pkg = mPackages.get(packageName);
10307            if (pkg == null || pkg.activities == null) {
10308                return Collections.<IntentFilter>emptyList();
10309            }
10310            final int count = pkg.activities.size();
10311            ArrayList<IntentFilter> result = new ArrayList<>();
10312            for (int n=0; n<count; n++) {
10313                PackageParser.Activity activity = pkg.activities.get(n);
10314                if (activity.intents != null || activity.intents.size() > 0) {
10315                    result.addAll(activity.intents);
10316                }
10317            }
10318            return result;
10319        }
10320    }
10321
10322    @Override
10323    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10324        mContext.enforceCallingOrSelfPermission(
10325                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10326
10327        synchronized (mPackages) {
10328            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10329            if (packageName != null) {
10330                result |= updateIntentVerificationStatus(packageName,
10331                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10332                        userId);
10333                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10334                        packageName, userId);
10335            }
10336            return result;
10337        }
10338    }
10339
10340    @Override
10341    public String getDefaultBrowserPackageName(int userId) {
10342        synchronized (mPackages) {
10343            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10344        }
10345    }
10346
10347    /**
10348     * Get the "allow unknown sources" setting.
10349     *
10350     * @return the current "allow unknown sources" setting
10351     */
10352    private int getUnknownSourcesSettings() {
10353        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10354                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10355                -1);
10356    }
10357
10358    @Override
10359    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10360        final int uid = Binder.getCallingUid();
10361        // writer
10362        synchronized (mPackages) {
10363            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10364            if (targetPackageSetting == null) {
10365                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10366            }
10367
10368            PackageSetting installerPackageSetting;
10369            if (installerPackageName != null) {
10370                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10371                if (installerPackageSetting == null) {
10372                    throw new IllegalArgumentException("Unknown installer package: "
10373                            + installerPackageName);
10374                }
10375            } else {
10376                installerPackageSetting = null;
10377            }
10378
10379            Signature[] callerSignature;
10380            Object obj = mSettings.getUserIdLPr(uid);
10381            if (obj != null) {
10382                if (obj instanceof SharedUserSetting) {
10383                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10384                } else if (obj instanceof PackageSetting) {
10385                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10386                } else {
10387                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10388                }
10389            } else {
10390                throw new SecurityException("Unknown calling uid " + uid);
10391            }
10392
10393            // Verify: can't set installerPackageName to a package that is
10394            // not signed with the same cert as the caller.
10395            if (installerPackageSetting != null) {
10396                if (compareSignatures(callerSignature,
10397                        installerPackageSetting.signatures.mSignatures)
10398                        != PackageManager.SIGNATURE_MATCH) {
10399                    throw new SecurityException(
10400                            "Caller does not have same cert as new installer package "
10401                            + installerPackageName);
10402                }
10403            }
10404
10405            // Verify: if target already has an installer package, it must
10406            // be signed with the same cert as the caller.
10407            if (targetPackageSetting.installerPackageName != null) {
10408                PackageSetting setting = mSettings.mPackages.get(
10409                        targetPackageSetting.installerPackageName);
10410                // If the currently set package isn't valid, then it's always
10411                // okay to change it.
10412                if (setting != null) {
10413                    if (compareSignatures(callerSignature,
10414                            setting.signatures.mSignatures)
10415                            != PackageManager.SIGNATURE_MATCH) {
10416                        throw new SecurityException(
10417                                "Caller does not have same cert as old installer package "
10418                                + targetPackageSetting.installerPackageName);
10419                    }
10420                }
10421            }
10422
10423            // Okay!
10424            targetPackageSetting.installerPackageName = installerPackageName;
10425            scheduleWriteSettingsLocked();
10426        }
10427    }
10428
10429    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10430        // Queue up an async operation since the package installation may take a little while.
10431        mHandler.post(new Runnable() {
10432            public void run() {
10433                mHandler.removeCallbacks(this);
10434                 // Result object to be returned
10435                PackageInstalledInfo res = new PackageInstalledInfo();
10436                res.returnCode = currentStatus;
10437                res.uid = -1;
10438                res.pkg = null;
10439                res.removedInfo = new PackageRemovedInfo();
10440                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10441                    args.doPreInstall(res.returnCode);
10442                    synchronized (mInstallLock) {
10443                        installPackageTracedLI(args, res);
10444                    }
10445                    args.doPostInstall(res.returnCode, res.uid);
10446                }
10447
10448                // A restore should be performed at this point if (a) the install
10449                // succeeded, (b) the operation is not an update, and (c) the new
10450                // package has not opted out of backup participation.
10451                final boolean update = res.removedInfo.removedPackage != null;
10452                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10453                boolean doRestore = !update
10454                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10455
10456                // Set up the post-install work request bookkeeping.  This will be used
10457                // and cleaned up by the post-install event handling regardless of whether
10458                // there's a restore pass performed.  Token values are >= 1.
10459                int token;
10460                if (mNextInstallToken < 0) mNextInstallToken = 1;
10461                token = mNextInstallToken++;
10462
10463                PostInstallData data = new PostInstallData(args, res);
10464                mRunningInstalls.put(token, data);
10465                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10466
10467                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10468                    // Pass responsibility to the Backup Manager.  It will perform a
10469                    // restore if appropriate, then pass responsibility back to the
10470                    // Package Manager to run the post-install observer callbacks
10471                    // and broadcasts.
10472                    IBackupManager bm = IBackupManager.Stub.asInterface(
10473                            ServiceManager.getService(Context.BACKUP_SERVICE));
10474                    if (bm != null) {
10475                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10476                                + " to BM for possible restore");
10477                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10478                        try {
10479                            // TODO: http://b/22388012
10480                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10481                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10482                            } else {
10483                                doRestore = false;
10484                            }
10485                        } catch (RemoteException e) {
10486                            // can't happen; the backup manager is local
10487                        } catch (Exception e) {
10488                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10489                            doRestore = false;
10490                        }
10491                    } else {
10492                        Slog.e(TAG, "Backup Manager not found!");
10493                        doRestore = false;
10494                    }
10495                }
10496
10497                if (!doRestore) {
10498                    // No restore possible, or the Backup Manager was mysteriously not
10499                    // available -- just fire the post-install work request directly.
10500                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10501
10502                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10503
10504                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10505                    mHandler.sendMessage(msg);
10506                }
10507            }
10508        });
10509    }
10510
10511    private abstract class HandlerParams {
10512        private static final int MAX_RETRIES = 4;
10513
10514        /**
10515         * Number of times startCopy() has been attempted and had a non-fatal
10516         * error.
10517         */
10518        private int mRetries = 0;
10519
10520        /** User handle for the user requesting the information or installation. */
10521        private final UserHandle mUser;
10522        String traceMethod;
10523        int traceCookie;
10524
10525        HandlerParams(UserHandle user) {
10526            mUser = user;
10527        }
10528
10529        UserHandle getUser() {
10530            return mUser;
10531        }
10532
10533        HandlerParams setTraceMethod(String traceMethod) {
10534            this.traceMethod = traceMethod;
10535            return this;
10536        }
10537
10538        HandlerParams setTraceCookie(int traceCookie) {
10539            this.traceCookie = traceCookie;
10540            return this;
10541        }
10542
10543        final boolean startCopy() {
10544            boolean res;
10545            try {
10546                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10547
10548                if (++mRetries > MAX_RETRIES) {
10549                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10550                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10551                    handleServiceError();
10552                    return false;
10553                } else {
10554                    handleStartCopy();
10555                    res = true;
10556                }
10557            } catch (RemoteException e) {
10558                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10559                mHandler.sendEmptyMessage(MCS_RECONNECT);
10560                res = false;
10561            }
10562            handleReturnCode();
10563            return res;
10564        }
10565
10566        final void serviceError() {
10567            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10568            handleServiceError();
10569            handleReturnCode();
10570        }
10571
10572        abstract void handleStartCopy() throws RemoteException;
10573        abstract void handleServiceError();
10574        abstract void handleReturnCode();
10575    }
10576
10577    class MeasureParams extends HandlerParams {
10578        private final PackageStats mStats;
10579        private boolean mSuccess;
10580
10581        private final IPackageStatsObserver mObserver;
10582
10583        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10584            super(new UserHandle(stats.userHandle));
10585            mObserver = observer;
10586            mStats = stats;
10587        }
10588
10589        @Override
10590        public String toString() {
10591            return "MeasureParams{"
10592                + Integer.toHexString(System.identityHashCode(this))
10593                + " " + mStats.packageName + "}";
10594        }
10595
10596        @Override
10597        void handleStartCopy() throws RemoteException {
10598            synchronized (mInstallLock) {
10599                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10600            }
10601
10602            if (mSuccess) {
10603                final boolean mounted;
10604                if (Environment.isExternalStorageEmulated()) {
10605                    mounted = true;
10606                } else {
10607                    final String status = Environment.getExternalStorageState();
10608                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10609                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10610                }
10611
10612                if (mounted) {
10613                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10614
10615                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10616                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10617
10618                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10619                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10620
10621                    // Always subtract cache size, since it's a subdirectory
10622                    mStats.externalDataSize -= mStats.externalCacheSize;
10623
10624                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10625                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10626
10627                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10628                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10629                }
10630            }
10631        }
10632
10633        @Override
10634        void handleReturnCode() {
10635            if (mObserver != null) {
10636                try {
10637                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10638                } catch (RemoteException e) {
10639                    Slog.i(TAG, "Observer no longer exists.");
10640                }
10641            }
10642        }
10643
10644        @Override
10645        void handleServiceError() {
10646            Slog.e(TAG, "Could not measure application " + mStats.packageName
10647                            + " external storage");
10648        }
10649    }
10650
10651    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10652            throws RemoteException {
10653        long result = 0;
10654        for (File path : paths) {
10655            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10656        }
10657        return result;
10658    }
10659
10660    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10661        for (File path : paths) {
10662            try {
10663                mcs.clearDirectory(path.getAbsolutePath());
10664            } catch (RemoteException e) {
10665            }
10666        }
10667    }
10668
10669    static class OriginInfo {
10670        /**
10671         * Location where install is coming from, before it has been
10672         * copied/renamed into place. This could be a single monolithic APK
10673         * file, or a cluster directory. This location may be untrusted.
10674         */
10675        final File file;
10676        final String cid;
10677
10678        /**
10679         * Flag indicating that {@link #file} or {@link #cid} has already been
10680         * staged, meaning downstream users don't need to defensively copy the
10681         * contents.
10682         */
10683        final boolean staged;
10684
10685        /**
10686         * Flag indicating that {@link #file} or {@link #cid} is an already
10687         * installed app that is being moved.
10688         */
10689        final boolean existing;
10690
10691        final String resolvedPath;
10692        final File resolvedFile;
10693
10694        static OriginInfo fromNothing() {
10695            return new OriginInfo(null, null, false, false);
10696        }
10697
10698        static OriginInfo fromUntrustedFile(File file) {
10699            return new OriginInfo(file, null, false, false);
10700        }
10701
10702        static OriginInfo fromExistingFile(File file) {
10703            return new OriginInfo(file, null, false, true);
10704        }
10705
10706        static OriginInfo fromStagedFile(File file) {
10707            return new OriginInfo(file, null, true, false);
10708        }
10709
10710        static OriginInfo fromStagedContainer(String cid) {
10711            return new OriginInfo(null, cid, true, false);
10712        }
10713
10714        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10715            this.file = file;
10716            this.cid = cid;
10717            this.staged = staged;
10718            this.existing = existing;
10719
10720            if (cid != null) {
10721                resolvedPath = PackageHelper.getSdDir(cid);
10722                resolvedFile = new File(resolvedPath);
10723            } else if (file != null) {
10724                resolvedPath = file.getAbsolutePath();
10725                resolvedFile = file;
10726            } else {
10727                resolvedPath = null;
10728                resolvedFile = null;
10729            }
10730        }
10731    }
10732
10733    class MoveInfo {
10734        final int moveId;
10735        final String fromUuid;
10736        final String toUuid;
10737        final String packageName;
10738        final String dataAppName;
10739        final int appId;
10740        final String seinfo;
10741
10742        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10743                String dataAppName, int appId, String seinfo) {
10744            this.moveId = moveId;
10745            this.fromUuid = fromUuid;
10746            this.toUuid = toUuid;
10747            this.packageName = packageName;
10748            this.dataAppName = dataAppName;
10749            this.appId = appId;
10750            this.seinfo = seinfo;
10751        }
10752    }
10753
10754    class InstallParams extends HandlerParams {
10755        final OriginInfo origin;
10756        final MoveInfo move;
10757        final IPackageInstallObserver2 observer;
10758        int installFlags;
10759        final String installerPackageName;
10760        final String volumeUuid;
10761        final VerificationParams verificationParams;
10762        private InstallArgs mArgs;
10763        private int mRet;
10764        final String packageAbiOverride;
10765        final String[] grantedRuntimePermissions;
10766
10767        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10768                int installFlags, String installerPackageName, String volumeUuid,
10769                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10770                String[] grantedPermissions) {
10771            super(user);
10772            this.origin = origin;
10773            this.move = move;
10774            this.observer = observer;
10775            this.installFlags = installFlags;
10776            this.installerPackageName = installerPackageName;
10777            this.volumeUuid = volumeUuid;
10778            this.verificationParams = verificationParams;
10779            this.packageAbiOverride = packageAbiOverride;
10780            this.grantedRuntimePermissions = grantedPermissions;
10781        }
10782
10783        @Override
10784        public String toString() {
10785            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10786                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10787        }
10788
10789        public ManifestDigest getManifestDigest() {
10790            if (verificationParams == null) {
10791                return null;
10792            }
10793            return verificationParams.getManifestDigest();
10794        }
10795
10796        private int installLocationPolicy(PackageInfoLite pkgLite) {
10797            String packageName = pkgLite.packageName;
10798            int installLocation = pkgLite.installLocation;
10799            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10800            // reader
10801            synchronized (mPackages) {
10802                PackageParser.Package pkg = mPackages.get(packageName);
10803                if (pkg != null) {
10804                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10805                        // Check for downgrading.
10806                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10807                            try {
10808                                checkDowngrade(pkg, pkgLite);
10809                            } catch (PackageManagerException e) {
10810                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10811                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10812                            }
10813                        }
10814                        // Check for updated system application.
10815                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10816                            if (onSd) {
10817                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10818                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10819                            }
10820                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10821                        } else {
10822                            if (onSd) {
10823                                // Install flag overrides everything.
10824                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10825                            }
10826                            // If current upgrade specifies particular preference
10827                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10828                                // Application explicitly specified internal.
10829                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10830                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10831                                // App explictly prefers external. Let policy decide
10832                            } else {
10833                                // Prefer previous location
10834                                if (isExternal(pkg)) {
10835                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10836                                }
10837                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10838                            }
10839                        }
10840                    } else {
10841                        // Invalid install. Return error code
10842                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10843                    }
10844                }
10845            }
10846            // All the special cases have been taken care of.
10847            // Return result based on recommended install location.
10848            if (onSd) {
10849                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10850            }
10851            return pkgLite.recommendedInstallLocation;
10852        }
10853
10854        /*
10855         * Invoke remote method to get package information and install
10856         * location values. Override install location based on default
10857         * policy if needed and then create install arguments based
10858         * on the install location.
10859         */
10860        public void handleStartCopy() throws RemoteException {
10861            int ret = PackageManager.INSTALL_SUCCEEDED;
10862
10863            // If we're already staged, we've firmly committed to an install location
10864            if (origin.staged) {
10865                if (origin.file != null) {
10866                    installFlags |= PackageManager.INSTALL_INTERNAL;
10867                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10868                } else if (origin.cid != null) {
10869                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10870                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10871                } else {
10872                    throw new IllegalStateException("Invalid stage location");
10873                }
10874            }
10875
10876            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10877            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10878            PackageInfoLite pkgLite = null;
10879
10880            if (onInt && onSd) {
10881                // Check if both bits are set.
10882                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10883                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10884            } else {
10885                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10886                        packageAbiOverride);
10887
10888                /*
10889                 * If we have too little free space, try to free cache
10890                 * before giving up.
10891                 */
10892                if (!origin.staged && pkgLite.recommendedInstallLocation
10893                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10894                    // TODO: focus freeing disk space on the target device
10895                    final StorageManager storage = StorageManager.from(mContext);
10896                    final long lowThreshold = storage.getStorageLowBytes(
10897                            Environment.getDataDirectory());
10898
10899                    final long sizeBytes = mContainerService.calculateInstalledSize(
10900                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10901
10902                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10903                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10904                                installFlags, packageAbiOverride);
10905                    }
10906
10907                    /*
10908                     * The cache free must have deleted the file we
10909                     * downloaded to install.
10910                     *
10911                     * TODO: fix the "freeCache" call to not delete
10912                     *       the file we care about.
10913                     */
10914                    if (pkgLite.recommendedInstallLocation
10915                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10916                        pkgLite.recommendedInstallLocation
10917                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10918                    }
10919                }
10920            }
10921
10922            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10923                int loc = pkgLite.recommendedInstallLocation;
10924                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10925                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10926                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10927                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10928                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10929                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10930                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10931                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10932                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10933                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10934                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10935                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10936                } else {
10937                    // Override with defaults if needed.
10938                    loc = installLocationPolicy(pkgLite);
10939                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10940                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10941                    } else if (!onSd && !onInt) {
10942                        // Override install location with flags
10943                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10944                            // Set the flag to install on external media.
10945                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10946                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10947                        } else {
10948                            // Make sure the flag for installing on external
10949                            // media is unset
10950                            installFlags |= PackageManager.INSTALL_INTERNAL;
10951                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10952                        }
10953                    }
10954                }
10955            }
10956
10957            final InstallArgs args = createInstallArgs(this);
10958            mArgs = args;
10959
10960            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10961                // TODO: http://b/22976637
10962                // Apps installed for "all" users use the device owner to verify the app
10963                UserHandle verifierUser = getUser();
10964                if (verifierUser == UserHandle.ALL) {
10965                    verifierUser = UserHandle.SYSTEM;
10966                }
10967
10968                /*
10969                 * Determine if we have any installed package verifiers. If we
10970                 * do, then we'll defer to them to verify the packages.
10971                 */
10972                final int requiredUid = mRequiredVerifierPackage == null ? -1
10973                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10974                if (!origin.existing && requiredUid != -1
10975                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10976                    final Intent verification = new Intent(
10977                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10978                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10979                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10980                            PACKAGE_MIME_TYPE);
10981                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10982
10983                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10984                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10985                            verifierUser.getIdentifier());
10986
10987                    if (DEBUG_VERIFY) {
10988                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10989                                + verification.toString() + " with " + pkgLite.verifiers.length
10990                                + " optional verifiers");
10991                    }
10992
10993                    final int verificationId = mPendingVerificationToken++;
10994
10995                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10996
10997                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10998                            installerPackageName);
10999
11000                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11001                            installFlags);
11002
11003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11004                            pkgLite.packageName);
11005
11006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11007                            pkgLite.versionCode);
11008
11009                    if (verificationParams != null) {
11010                        if (verificationParams.getVerificationURI() != null) {
11011                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11012                                 verificationParams.getVerificationURI());
11013                        }
11014                        if (verificationParams.getOriginatingURI() != null) {
11015                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11016                                  verificationParams.getOriginatingURI());
11017                        }
11018                        if (verificationParams.getReferrer() != null) {
11019                            verification.putExtra(Intent.EXTRA_REFERRER,
11020                                  verificationParams.getReferrer());
11021                        }
11022                        if (verificationParams.getOriginatingUid() >= 0) {
11023                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11024                                  verificationParams.getOriginatingUid());
11025                        }
11026                        if (verificationParams.getInstallerUid() >= 0) {
11027                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11028                                  verificationParams.getInstallerUid());
11029                        }
11030                    }
11031
11032                    final PackageVerificationState verificationState = new PackageVerificationState(
11033                            requiredUid, args);
11034
11035                    mPendingVerification.append(verificationId, verificationState);
11036
11037                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11038                            receivers, verificationState);
11039
11040                    /*
11041                     * If any sufficient verifiers were listed in the package
11042                     * manifest, attempt to ask them.
11043                     */
11044                    if (sufficientVerifiers != null) {
11045                        final int N = sufficientVerifiers.size();
11046                        if (N == 0) {
11047                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11048                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11049                        } else {
11050                            for (int i = 0; i < N; i++) {
11051                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11052
11053                                final Intent sufficientIntent = new Intent(verification);
11054                                sufficientIntent.setComponent(verifierComponent);
11055                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11056                            }
11057                        }
11058                    }
11059
11060                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11061                            mRequiredVerifierPackage, receivers);
11062                    if (ret == PackageManager.INSTALL_SUCCEEDED
11063                            && mRequiredVerifierPackage != null) {
11064                        Trace.asyncTraceBegin(
11065                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11066                        /*
11067                         * Send the intent to the required verification agent,
11068                         * but only start the verification timeout after the
11069                         * target BroadcastReceivers have run.
11070                         */
11071                        verification.setComponent(requiredVerifierComponent);
11072                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11073                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11074                                new BroadcastReceiver() {
11075                                    @Override
11076                                    public void onReceive(Context context, Intent intent) {
11077                                        final Message msg = mHandler
11078                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11079                                        msg.arg1 = verificationId;
11080                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11081                                    }
11082                                }, null, 0, null, null);
11083
11084                        /*
11085                         * We don't want the copy to proceed until verification
11086                         * succeeds, so null out this field.
11087                         */
11088                        mArgs = null;
11089                    }
11090                } else {
11091                    /*
11092                     * No package verification is enabled, so immediately start
11093                     * the remote call to initiate copy using temporary file.
11094                     */
11095                    ret = args.copyApk(mContainerService, true);
11096                }
11097            }
11098
11099            mRet = ret;
11100        }
11101
11102        @Override
11103        void handleReturnCode() {
11104            // If mArgs is null, then MCS couldn't be reached. When it
11105            // reconnects, it will try again to install. At that point, this
11106            // will succeed.
11107            if (mArgs != null) {
11108                processPendingInstall(mArgs, mRet);
11109            }
11110        }
11111
11112        @Override
11113        void handleServiceError() {
11114            mArgs = createInstallArgs(this);
11115            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11116        }
11117
11118        public boolean isForwardLocked() {
11119            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11120        }
11121    }
11122
11123    /**
11124     * Used during creation of InstallArgs
11125     *
11126     * @param installFlags package installation flags
11127     * @return true if should be installed on external storage
11128     */
11129    private static boolean installOnExternalAsec(int installFlags) {
11130        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11131            return false;
11132        }
11133        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11134            return true;
11135        }
11136        return false;
11137    }
11138
11139    /**
11140     * Used during creation of InstallArgs
11141     *
11142     * @param installFlags package installation flags
11143     * @return true if should be installed as forward locked
11144     */
11145    private static boolean installForwardLocked(int installFlags) {
11146        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11147    }
11148
11149    private InstallArgs createInstallArgs(InstallParams params) {
11150        if (params.move != null) {
11151            return new MoveInstallArgs(params);
11152        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11153            return new AsecInstallArgs(params);
11154        } else {
11155            return new FileInstallArgs(params);
11156        }
11157    }
11158
11159    /**
11160     * Create args that describe an existing installed package. Typically used
11161     * when cleaning up old installs, or used as a move source.
11162     */
11163    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11164            String resourcePath, String[] instructionSets) {
11165        final boolean isInAsec;
11166        if (installOnExternalAsec(installFlags)) {
11167            /* Apps on SD card are always in ASEC containers. */
11168            isInAsec = true;
11169        } else if (installForwardLocked(installFlags)
11170                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11171            /*
11172             * Forward-locked apps are only in ASEC containers if they're the
11173             * new style
11174             */
11175            isInAsec = true;
11176        } else {
11177            isInAsec = false;
11178        }
11179
11180        if (isInAsec) {
11181            return new AsecInstallArgs(codePath, instructionSets,
11182                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11183        } else {
11184            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11185        }
11186    }
11187
11188    static abstract class InstallArgs {
11189        /** @see InstallParams#origin */
11190        final OriginInfo origin;
11191        /** @see InstallParams#move */
11192        final MoveInfo move;
11193
11194        final IPackageInstallObserver2 observer;
11195        // Always refers to PackageManager flags only
11196        final int installFlags;
11197        final String installerPackageName;
11198        final String volumeUuid;
11199        final ManifestDigest manifestDigest;
11200        final UserHandle user;
11201        final String abiOverride;
11202        final String[] installGrantPermissions;
11203        /** If non-null, drop an async trace when the install completes */
11204        final String traceMethod;
11205        final int traceCookie;
11206
11207        // The list of instruction sets supported by this app. This is currently
11208        // only used during the rmdex() phase to clean up resources. We can get rid of this
11209        // if we move dex files under the common app path.
11210        /* nullable */ String[] instructionSets;
11211
11212        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11213                int installFlags, String installerPackageName, String volumeUuid,
11214                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11215                String abiOverride, String[] installGrantPermissions,
11216                String traceMethod, int traceCookie) {
11217            this.origin = origin;
11218            this.move = move;
11219            this.installFlags = installFlags;
11220            this.observer = observer;
11221            this.installerPackageName = installerPackageName;
11222            this.volumeUuid = volumeUuid;
11223            this.manifestDigest = manifestDigest;
11224            this.user = user;
11225            this.instructionSets = instructionSets;
11226            this.abiOverride = abiOverride;
11227            this.installGrantPermissions = installGrantPermissions;
11228            this.traceMethod = traceMethod;
11229            this.traceCookie = traceCookie;
11230        }
11231
11232        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11233        abstract int doPreInstall(int status);
11234
11235        /**
11236         * Rename package into final resting place. All paths on the given
11237         * scanned package should be updated to reflect the rename.
11238         */
11239        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11240        abstract int doPostInstall(int status, int uid);
11241
11242        /** @see PackageSettingBase#codePathString */
11243        abstract String getCodePath();
11244        /** @see PackageSettingBase#resourcePathString */
11245        abstract String getResourcePath();
11246
11247        // Need installer lock especially for dex file removal.
11248        abstract void cleanUpResourcesLI();
11249        abstract boolean doPostDeleteLI(boolean delete);
11250
11251        /**
11252         * Called before the source arguments are copied. This is used mostly
11253         * for MoveParams when it needs to read the source file to put it in the
11254         * destination.
11255         */
11256        int doPreCopy() {
11257            return PackageManager.INSTALL_SUCCEEDED;
11258        }
11259
11260        /**
11261         * Called after the source arguments are copied. This is used mostly for
11262         * MoveParams when it needs to read the source file to put it in the
11263         * destination.
11264         *
11265         * @return
11266         */
11267        int doPostCopy(int uid) {
11268            return PackageManager.INSTALL_SUCCEEDED;
11269        }
11270
11271        protected boolean isFwdLocked() {
11272            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11273        }
11274
11275        protected boolean isExternalAsec() {
11276            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11277        }
11278
11279        UserHandle getUser() {
11280            return user;
11281        }
11282    }
11283
11284    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11285        if (!allCodePaths.isEmpty()) {
11286            if (instructionSets == null) {
11287                throw new IllegalStateException("instructionSet == null");
11288            }
11289            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11290            for (String codePath : allCodePaths) {
11291                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11292                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11293                    if (retCode < 0) {
11294                        Slog.w(TAG, "Couldn't remove dex file for package: "
11295                                + " at location " + codePath + ", retcode=" + retCode);
11296                        // we don't consider this to be a failure of the core package deletion
11297                    }
11298                }
11299            }
11300        }
11301    }
11302
11303    /**
11304     * Logic to handle installation of non-ASEC applications, including copying
11305     * and renaming logic.
11306     */
11307    class FileInstallArgs extends InstallArgs {
11308        private File codeFile;
11309        private File resourceFile;
11310
11311        // Example topology:
11312        // /data/app/com.example/base.apk
11313        // /data/app/com.example/split_foo.apk
11314        // /data/app/com.example/lib/arm/libfoo.so
11315        // /data/app/com.example/lib/arm64/libfoo.so
11316        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11317
11318        /** New install */
11319        FileInstallArgs(InstallParams params) {
11320            super(params.origin, params.move, params.observer, params.installFlags,
11321                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11322                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11323                    params.grantedRuntimePermissions,
11324                    params.traceMethod, params.traceCookie);
11325            if (isFwdLocked()) {
11326                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11327            }
11328        }
11329
11330        /** Existing install */
11331        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11332            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11333                    null, null, null, 0);
11334            this.codeFile = (codePath != null) ? new File(codePath) : null;
11335            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11336        }
11337
11338        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11340            try {
11341                return doCopyApk(imcs, temp);
11342            } finally {
11343                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11344            }
11345        }
11346
11347        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11348            if (origin.staged) {
11349                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11350                codeFile = origin.file;
11351                resourceFile = origin.file;
11352                return PackageManager.INSTALL_SUCCEEDED;
11353            }
11354
11355            try {
11356                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11357                codeFile = tempDir;
11358                resourceFile = tempDir;
11359            } catch (IOException e) {
11360                Slog.w(TAG, "Failed to create copy file: " + e);
11361                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11362            }
11363
11364            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11365                @Override
11366                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11367                    if (!FileUtils.isValidExtFilename(name)) {
11368                        throw new IllegalArgumentException("Invalid filename: " + name);
11369                    }
11370                    try {
11371                        final File file = new File(codeFile, name);
11372                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11373                                O_RDWR | O_CREAT, 0644);
11374                        Os.chmod(file.getAbsolutePath(), 0644);
11375                        return new ParcelFileDescriptor(fd);
11376                    } catch (ErrnoException e) {
11377                        throw new RemoteException("Failed to open: " + e.getMessage());
11378                    }
11379                }
11380            };
11381
11382            int ret = PackageManager.INSTALL_SUCCEEDED;
11383            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11384            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11385                Slog.e(TAG, "Failed to copy package");
11386                return ret;
11387            }
11388
11389            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11390            NativeLibraryHelper.Handle handle = null;
11391            try {
11392                handle = NativeLibraryHelper.Handle.create(codeFile);
11393                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11394                        abiOverride);
11395            } catch (IOException e) {
11396                Slog.e(TAG, "Copying native libraries failed", e);
11397                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11398            } finally {
11399                IoUtils.closeQuietly(handle);
11400            }
11401
11402            return ret;
11403        }
11404
11405        int doPreInstall(int status) {
11406            if (status != PackageManager.INSTALL_SUCCEEDED) {
11407                cleanUp();
11408            }
11409            return status;
11410        }
11411
11412        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11413            if (status != PackageManager.INSTALL_SUCCEEDED) {
11414                cleanUp();
11415                return false;
11416            }
11417
11418            final File targetDir = codeFile.getParentFile();
11419            final File beforeCodeFile = codeFile;
11420            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11421
11422            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11423            try {
11424                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11425            } catch (ErrnoException e) {
11426                Slog.w(TAG, "Failed to rename", e);
11427                return false;
11428            }
11429
11430            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11431                Slog.w(TAG, "Failed to restorecon");
11432                return false;
11433            }
11434
11435            // Reflect the rename internally
11436            codeFile = afterCodeFile;
11437            resourceFile = afterCodeFile;
11438
11439            // Reflect the rename in scanned details
11440            pkg.codePath = afterCodeFile.getAbsolutePath();
11441            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11442                    pkg.baseCodePath);
11443            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11444                    pkg.splitCodePaths);
11445
11446            // Reflect the rename in app info
11447            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11448            pkg.applicationInfo.setCodePath(pkg.codePath);
11449            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11450            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11451            pkg.applicationInfo.setResourcePath(pkg.codePath);
11452            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11453            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11454
11455            return true;
11456        }
11457
11458        int doPostInstall(int status, int uid) {
11459            if (status != PackageManager.INSTALL_SUCCEEDED) {
11460                cleanUp();
11461            }
11462            return status;
11463        }
11464
11465        @Override
11466        String getCodePath() {
11467            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11468        }
11469
11470        @Override
11471        String getResourcePath() {
11472            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11473        }
11474
11475        private boolean cleanUp() {
11476            if (codeFile == null || !codeFile.exists()) {
11477                return false;
11478            }
11479
11480            if (codeFile.isDirectory()) {
11481                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11482            } else {
11483                codeFile.delete();
11484            }
11485
11486            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11487                resourceFile.delete();
11488            }
11489
11490            return true;
11491        }
11492
11493        void cleanUpResourcesLI() {
11494            // Try enumerating all code paths before deleting
11495            List<String> allCodePaths = Collections.EMPTY_LIST;
11496            if (codeFile != null && codeFile.exists()) {
11497                try {
11498                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11499                    allCodePaths = pkg.getAllCodePaths();
11500                } catch (PackageParserException e) {
11501                    // Ignored; we tried our best
11502                }
11503            }
11504
11505            cleanUp();
11506            removeDexFiles(allCodePaths, instructionSets);
11507        }
11508
11509        boolean doPostDeleteLI(boolean delete) {
11510            // XXX err, shouldn't we respect the delete flag?
11511            cleanUpResourcesLI();
11512            return true;
11513        }
11514    }
11515
11516    private boolean isAsecExternal(String cid) {
11517        final String asecPath = PackageHelper.getSdFilesystem(cid);
11518        return !asecPath.startsWith(mAsecInternalPath);
11519    }
11520
11521    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11522            PackageManagerException {
11523        if (copyRet < 0) {
11524            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11525                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11526                throw new PackageManagerException(copyRet, message);
11527            }
11528        }
11529    }
11530
11531    /**
11532     * Extract the MountService "container ID" from the full code path of an
11533     * .apk.
11534     */
11535    static String cidFromCodePath(String fullCodePath) {
11536        int eidx = fullCodePath.lastIndexOf("/");
11537        String subStr1 = fullCodePath.substring(0, eidx);
11538        int sidx = subStr1.lastIndexOf("/");
11539        return subStr1.substring(sidx+1, eidx);
11540    }
11541
11542    /**
11543     * Logic to handle installation of ASEC applications, including copying and
11544     * renaming logic.
11545     */
11546    class AsecInstallArgs extends InstallArgs {
11547        static final String RES_FILE_NAME = "pkg.apk";
11548        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11549
11550        String cid;
11551        String packagePath;
11552        String resourcePath;
11553
11554        /** New install */
11555        AsecInstallArgs(InstallParams params) {
11556            super(params.origin, params.move, params.observer, params.installFlags,
11557                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11558                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11559                    params.grantedRuntimePermissions,
11560                    params.traceMethod, params.traceCookie);
11561        }
11562
11563        /** Existing install */
11564        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11565                        boolean isExternal, boolean isForwardLocked) {
11566            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11567                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11568                    instructionSets, null, null, null, 0);
11569            // Hackily pretend we're still looking at a full code path
11570            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11571                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11572            }
11573
11574            // Extract cid from fullCodePath
11575            int eidx = fullCodePath.lastIndexOf("/");
11576            String subStr1 = fullCodePath.substring(0, eidx);
11577            int sidx = subStr1.lastIndexOf("/");
11578            cid = subStr1.substring(sidx+1, eidx);
11579            setMountPath(subStr1);
11580        }
11581
11582        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11583            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11584                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11585                    instructionSets, null, null, null, 0);
11586            this.cid = cid;
11587            setMountPath(PackageHelper.getSdDir(cid));
11588        }
11589
11590        void createCopyFile() {
11591            cid = mInstallerService.allocateExternalStageCidLegacy();
11592        }
11593
11594        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11595            if (origin.staged) {
11596                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11597                cid = origin.cid;
11598                setMountPath(PackageHelper.getSdDir(cid));
11599                return PackageManager.INSTALL_SUCCEEDED;
11600            }
11601
11602            if (temp) {
11603                createCopyFile();
11604            } else {
11605                /*
11606                 * Pre-emptively destroy the container since it's destroyed if
11607                 * copying fails due to it existing anyway.
11608                 */
11609                PackageHelper.destroySdDir(cid);
11610            }
11611
11612            final String newMountPath = imcs.copyPackageToContainer(
11613                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11614                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11615
11616            if (newMountPath != null) {
11617                setMountPath(newMountPath);
11618                return PackageManager.INSTALL_SUCCEEDED;
11619            } else {
11620                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11621            }
11622        }
11623
11624        @Override
11625        String getCodePath() {
11626            return packagePath;
11627        }
11628
11629        @Override
11630        String getResourcePath() {
11631            return resourcePath;
11632        }
11633
11634        int doPreInstall(int status) {
11635            if (status != PackageManager.INSTALL_SUCCEEDED) {
11636                // Destroy container
11637                PackageHelper.destroySdDir(cid);
11638            } else {
11639                boolean mounted = PackageHelper.isContainerMounted(cid);
11640                if (!mounted) {
11641                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11642                            Process.SYSTEM_UID);
11643                    if (newMountPath != null) {
11644                        setMountPath(newMountPath);
11645                    } else {
11646                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11647                    }
11648                }
11649            }
11650            return status;
11651        }
11652
11653        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11654            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11655            String newMountPath = null;
11656            if (PackageHelper.isContainerMounted(cid)) {
11657                // Unmount the container
11658                if (!PackageHelper.unMountSdDir(cid)) {
11659                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11660                    return false;
11661                }
11662            }
11663            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11664                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11665                        " which might be stale. Will try to clean up.");
11666                // Clean up the stale container and proceed to recreate.
11667                if (!PackageHelper.destroySdDir(newCacheId)) {
11668                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11669                    return false;
11670                }
11671                // Successfully cleaned up stale container. Try to rename again.
11672                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11673                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11674                            + " inspite of cleaning it up.");
11675                    return false;
11676                }
11677            }
11678            if (!PackageHelper.isContainerMounted(newCacheId)) {
11679                Slog.w(TAG, "Mounting container " + newCacheId);
11680                newMountPath = PackageHelper.mountSdDir(newCacheId,
11681                        getEncryptKey(), Process.SYSTEM_UID);
11682            } else {
11683                newMountPath = PackageHelper.getSdDir(newCacheId);
11684            }
11685            if (newMountPath == null) {
11686                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11687                return false;
11688            }
11689            Log.i(TAG, "Succesfully renamed " + cid +
11690                    " to " + newCacheId +
11691                    " at new path: " + newMountPath);
11692            cid = newCacheId;
11693
11694            final File beforeCodeFile = new File(packagePath);
11695            setMountPath(newMountPath);
11696            final File afterCodeFile = new File(packagePath);
11697
11698            // Reflect the rename in scanned details
11699            pkg.codePath = afterCodeFile.getAbsolutePath();
11700            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11701                    pkg.baseCodePath);
11702            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11703                    pkg.splitCodePaths);
11704
11705            // Reflect the rename in app info
11706            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11707            pkg.applicationInfo.setCodePath(pkg.codePath);
11708            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11709            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11710            pkg.applicationInfo.setResourcePath(pkg.codePath);
11711            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11712            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11713
11714            return true;
11715        }
11716
11717        private void setMountPath(String mountPath) {
11718            final File mountFile = new File(mountPath);
11719
11720            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11721            if (monolithicFile.exists()) {
11722                packagePath = monolithicFile.getAbsolutePath();
11723                if (isFwdLocked()) {
11724                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11725                } else {
11726                    resourcePath = packagePath;
11727                }
11728            } else {
11729                packagePath = mountFile.getAbsolutePath();
11730                resourcePath = packagePath;
11731            }
11732        }
11733
11734        int doPostInstall(int status, int uid) {
11735            if (status != PackageManager.INSTALL_SUCCEEDED) {
11736                cleanUp();
11737            } else {
11738                final int groupOwner;
11739                final String protectedFile;
11740                if (isFwdLocked()) {
11741                    groupOwner = UserHandle.getSharedAppGid(uid);
11742                    protectedFile = RES_FILE_NAME;
11743                } else {
11744                    groupOwner = -1;
11745                    protectedFile = null;
11746                }
11747
11748                if (uid < Process.FIRST_APPLICATION_UID
11749                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11750                    Slog.e(TAG, "Failed to finalize " + cid);
11751                    PackageHelper.destroySdDir(cid);
11752                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11753                }
11754
11755                boolean mounted = PackageHelper.isContainerMounted(cid);
11756                if (!mounted) {
11757                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11758                }
11759            }
11760            return status;
11761        }
11762
11763        private void cleanUp() {
11764            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11765
11766            // Destroy secure container
11767            PackageHelper.destroySdDir(cid);
11768        }
11769
11770        private List<String> getAllCodePaths() {
11771            final File codeFile = new File(getCodePath());
11772            if (codeFile != null && codeFile.exists()) {
11773                try {
11774                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11775                    return pkg.getAllCodePaths();
11776                } catch (PackageParserException e) {
11777                    // Ignored; we tried our best
11778                }
11779            }
11780            return Collections.EMPTY_LIST;
11781        }
11782
11783        void cleanUpResourcesLI() {
11784            // Enumerate all code paths before deleting
11785            cleanUpResourcesLI(getAllCodePaths());
11786        }
11787
11788        private void cleanUpResourcesLI(List<String> allCodePaths) {
11789            cleanUp();
11790            removeDexFiles(allCodePaths, instructionSets);
11791        }
11792
11793        String getPackageName() {
11794            return getAsecPackageName(cid);
11795        }
11796
11797        boolean doPostDeleteLI(boolean delete) {
11798            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11799            final List<String> allCodePaths = getAllCodePaths();
11800            boolean mounted = PackageHelper.isContainerMounted(cid);
11801            if (mounted) {
11802                // Unmount first
11803                if (PackageHelper.unMountSdDir(cid)) {
11804                    mounted = false;
11805                }
11806            }
11807            if (!mounted && delete) {
11808                cleanUpResourcesLI(allCodePaths);
11809            }
11810            return !mounted;
11811        }
11812
11813        @Override
11814        int doPreCopy() {
11815            if (isFwdLocked()) {
11816                if (!PackageHelper.fixSdPermissions(cid,
11817                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11818                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11819                }
11820            }
11821
11822            return PackageManager.INSTALL_SUCCEEDED;
11823        }
11824
11825        @Override
11826        int doPostCopy(int uid) {
11827            if (isFwdLocked()) {
11828                if (uid < Process.FIRST_APPLICATION_UID
11829                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11830                                RES_FILE_NAME)) {
11831                    Slog.e(TAG, "Failed to finalize " + cid);
11832                    PackageHelper.destroySdDir(cid);
11833                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11834                }
11835            }
11836
11837            return PackageManager.INSTALL_SUCCEEDED;
11838        }
11839    }
11840
11841    /**
11842     * Logic to handle movement of existing installed applications.
11843     */
11844    class MoveInstallArgs extends InstallArgs {
11845        private File codeFile;
11846        private File resourceFile;
11847
11848        /** New install */
11849        MoveInstallArgs(InstallParams params) {
11850            super(params.origin, params.move, params.observer, params.installFlags,
11851                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11852                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11853                    params.grantedRuntimePermissions,
11854                    params.traceMethod, params.traceCookie);
11855        }
11856
11857        int copyApk(IMediaContainerService imcs, boolean temp) {
11858            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11859                    + move.fromUuid + " to " + move.toUuid);
11860            synchronized (mInstaller) {
11861                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11862                        move.dataAppName, move.appId, move.seinfo) != 0) {
11863                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11864                }
11865            }
11866
11867            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11868            resourceFile = codeFile;
11869            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11870
11871            return PackageManager.INSTALL_SUCCEEDED;
11872        }
11873
11874        int doPreInstall(int status) {
11875            if (status != PackageManager.INSTALL_SUCCEEDED) {
11876                cleanUp(move.toUuid);
11877            }
11878            return status;
11879        }
11880
11881        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11882            if (status != PackageManager.INSTALL_SUCCEEDED) {
11883                cleanUp(move.toUuid);
11884                return false;
11885            }
11886
11887            // Reflect the move in app info
11888            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11889            pkg.applicationInfo.setCodePath(pkg.codePath);
11890            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11891            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11892            pkg.applicationInfo.setResourcePath(pkg.codePath);
11893            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11894            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11895
11896            return true;
11897        }
11898
11899        int doPostInstall(int status, int uid) {
11900            if (status == PackageManager.INSTALL_SUCCEEDED) {
11901                cleanUp(move.fromUuid);
11902            } else {
11903                cleanUp(move.toUuid);
11904            }
11905            return status;
11906        }
11907
11908        @Override
11909        String getCodePath() {
11910            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11911        }
11912
11913        @Override
11914        String getResourcePath() {
11915            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11916        }
11917
11918        private boolean cleanUp(String volumeUuid) {
11919            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11920                    move.dataAppName);
11921            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11922            synchronized (mInstallLock) {
11923                // Clean up both app data and code
11924                removeDataDirsLI(volumeUuid, move.packageName);
11925                if (codeFile.isDirectory()) {
11926                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11927                } else {
11928                    codeFile.delete();
11929                }
11930            }
11931            return true;
11932        }
11933
11934        void cleanUpResourcesLI() {
11935            throw new UnsupportedOperationException();
11936        }
11937
11938        boolean doPostDeleteLI(boolean delete) {
11939            throw new UnsupportedOperationException();
11940        }
11941    }
11942
11943    static String getAsecPackageName(String packageCid) {
11944        int idx = packageCid.lastIndexOf("-");
11945        if (idx == -1) {
11946            return packageCid;
11947        }
11948        return packageCid.substring(0, idx);
11949    }
11950
11951    // Utility method used to create code paths based on package name and available index.
11952    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11953        String idxStr = "";
11954        int idx = 1;
11955        // Fall back to default value of idx=1 if prefix is not
11956        // part of oldCodePath
11957        if (oldCodePath != null) {
11958            String subStr = oldCodePath;
11959            // Drop the suffix right away
11960            if (suffix != null && subStr.endsWith(suffix)) {
11961                subStr = subStr.substring(0, subStr.length() - suffix.length());
11962            }
11963            // If oldCodePath already contains prefix find out the
11964            // ending index to either increment or decrement.
11965            int sidx = subStr.lastIndexOf(prefix);
11966            if (sidx != -1) {
11967                subStr = subStr.substring(sidx + prefix.length());
11968                if (subStr != null) {
11969                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11970                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11971                    }
11972                    try {
11973                        idx = Integer.parseInt(subStr);
11974                        if (idx <= 1) {
11975                            idx++;
11976                        } else {
11977                            idx--;
11978                        }
11979                    } catch(NumberFormatException e) {
11980                    }
11981                }
11982            }
11983        }
11984        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11985        return prefix + idxStr;
11986    }
11987
11988    private File getNextCodePath(File targetDir, String packageName) {
11989        int suffix = 1;
11990        File result;
11991        do {
11992            result = new File(targetDir, packageName + "-" + suffix);
11993            suffix++;
11994        } while (result.exists());
11995        return result;
11996    }
11997
11998    // Utility method that returns the relative package path with respect
11999    // to the installation directory. Like say for /data/data/com.test-1.apk
12000    // string com.test-1 is returned.
12001    static String deriveCodePathName(String codePath) {
12002        if (codePath == null) {
12003            return null;
12004        }
12005        final File codeFile = new File(codePath);
12006        final String name = codeFile.getName();
12007        if (codeFile.isDirectory()) {
12008            return name;
12009        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12010            final int lastDot = name.lastIndexOf('.');
12011            return name.substring(0, lastDot);
12012        } else {
12013            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12014            return null;
12015        }
12016    }
12017
12018    class PackageInstalledInfo {
12019        String name;
12020        int uid;
12021        // The set of users that originally had this package installed.
12022        int[] origUsers;
12023        // The set of users that now have this package installed.
12024        int[] newUsers;
12025        PackageParser.Package pkg;
12026        int returnCode;
12027        String returnMsg;
12028        PackageRemovedInfo removedInfo;
12029
12030        public void setError(int code, String msg) {
12031            returnCode = code;
12032            returnMsg = msg;
12033            Slog.w(TAG, msg);
12034        }
12035
12036        public void setError(String msg, PackageParserException e) {
12037            returnCode = e.error;
12038            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12039            Slog.w(TAG, msg, e);
12040        }
12041
12042        public void setError(String msg, PackageManagerException e) {
12043            returnCode = e.error;
12044            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12045            Slog.w(TAG, msg, e);
12046        }
12047
12048        // In some error cases we want to convey more info back to the observer
12049        String origPackage;
12050        String origPermission;
12051    }
12052
12053    /*
12054     * Install a non-existing package.
12055     */
12056    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12057            UserHandle user, String installerPackageName, String volumeUuid,
12058            PackageInstalledInfo res) {
12059        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12060
12061        // Remember this for later, in case we need to rollback this install
12062        String pkgName = pkg.packageName;
12063
12064        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12065        // TODO: b/23350563
12066        final boolean dataDirExists = Environment
12067                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12068
12069        synchronized(mPackages) {
12070            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12071                // A package with the same name is already installed, though
12072                // it has been renamed to an older name.  The package we
12073                // are trying to install should be installed as an update to
12074                // the existing one, but that has not been requested, so bail.
12075                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12076                        + " without first uninstalling package running as "
12077                        + mSettings.mRenamedPackages.get(pkgName));
12078                return;
12079            }
12080            if (mPackages.containsKey(pkgName)) {
12081                // Don't allow installation over an existing package with the same name.
12082                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12083                        + " without first uninstalling.");
12084                return;
12085            }
12086        }
12087
12088        try {
12089            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12090                    System.currentTimeMillis(), user);
12091
12092            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12093            // delete the partially installed application. the data directory will have to be
12094            // restored if it was already existing
12095            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12096                // remove package from internal structures.  Note that we want deletePackageX to
12097                // delete the package data and cache directories that it created in
12098                // scanPackageLocked, unless those directories existed before we even tried to
12099                // install.
12100                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12101                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12102                                res.removedInfo, true);
12103            }
12104
12105        } catch (PackageManagerException e) {
12106            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12107        }
12108
12109        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12110    }
12111
12112    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12113        // Can't rotate keys during boot or if sharedUser.
12114        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12115                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12116            return false;
12117        }
12118        // app is using upgradeKeySets; make sure all are valid
12119        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12120        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12121        for (int i = 0; i < upgradeKeySets.length; i++) {
12122            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12123                Slog.wtf(TAG, "Package "
12124                         + (oldPs.name != null ? oldPs.name : "<null>")
12125                         + " contains upgrade-key-set reference to unknown key-set: "
12126                         + upgradeKeySets[i]
12127                         + " reverting to signatures check.");
12128                return false;
12129            }
12130        }
12131        return true;
12132    }
12133
12134    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12135        // Upgrade keysets are being used.  Determine if new package has a superset of the
12136        // required keys.
12137        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12138        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12139        for (int i = 0; i < upgradeKeySets.length; i++) {
12140            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12141            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12142                return true;
12143            }
12144        }
12145        return false;
12146    }
12147
12148    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12149            UserHandle user, String installerPackageName, String volumeUuid,
12150            PackageInstalledInfo res) {
12151        final PackageParser.Package oldPackage;
12152        final String pkgName = pkg.packageName;
12153        final int[] allUsers;
12154        final boolean[] perUserInstalled;
12155
12156        // First find the old package info and check signatures
12157        synchronized(mPackages) {
12158            oldPackage = mPackages.get(pkgName);
12159            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12160            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12161            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12162                if(!checkUpgradeKeySetLP(ps, pkg)) {
12163                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12164                            "New package not signed by keys specified by upgrade-keysets: "
12165                            + pkgName);
12166                    return;
12167                }
12168            } else {
12169                // default to original signature matching
12170                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12171                    != PackageManager.SIGNATURE_MATCH) {
12172                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12173                            "New package has a different signature: " + pkgName);
12174                    return;
12175                }
12176            }
12177
12178            // In case of rollback, remember per-user/profile install state
12179            allUsers = sUserManager.getUserIds();
12180            perUserInstalled = new boolean[allUsers.length];
12181            for (int i = 0; i < allUsers.length; i++) {
12182                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12183            }
12184        }
12185
12186        boolean sysPkg = (isSystemApp(oldPackage));
12187        if (sysPkg) {
12188            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12189                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12190        } else {
12191            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12192                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12193        }
12194    }
12195
12196    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12197            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12198            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12199            String volumeUuid, PackageInstalledInfo res) {
12200        String pkgName = deletedPackage.packageName;
12201        boolean deletedPkg = true;
12202        boolean updatedSettings = false;
12203
12204        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12205                + deletedPackage);
12206        long origUpdateTime;
12207        if (pkg.mExtras != null) {
12208            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12209        } else {
12210            origUpdateTime = 0;
12211        }
12212
12213        // First delete the existing package while retaining the data directory
12214        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12215                res.removedInfo, true)) {
12216            // If the existing package wasn't successfully deleted
12217            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12218            deletedPkg = false;
12219        } else {
12220            // Successfully deleted the old package; proceed with replace.
12221
12222            // If deleted package lived in a container, give users a chance to
12223            // relinquish resources before killing.
12224            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12225                if (DEBUG_INSTALL) {
12226                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12227                }
12228                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12229                final ArrayList<String> pkgList = new ArrayList<String>(1);
12230                pkgList.add(deletedPackage.applicationInfo.packageName);
12231                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12232            }
12233
12234            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12235            try {
12236                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12237                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12238                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12239                        perUserInstalled, res, user);
12240                updatedSettings = true;
12241            } catch (PackageManagerException e) {
12242                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12243            }
12244        }
12245
12246        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12247            // remove package from internal structures.  Note that we want deletePackageX to
12248            // delete the package data and cache directories that it created in
12249            // scanPackageLocked, unless those directories existed before we even tried to
12250            // install.
12251            if(updatedSettings) {
12252                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12253                deletePackageLI(
12254                        pkgName, null, true, allUsers, perUserInstalled,
12255                        PackageManager.DELETE_KEEP_DATA,
12256                                res.removedInfo, true);
12257            }
12258            // Since we failed to install the new package we need to restore the old
12259            // package that we deleted.
12260            if (deletedPkg) {
12261                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12262                File restoreFile = new File(deletedPackage.codePath);
12263                // Parse old package
12264                boolean oldExternal = isExternal(deletedPackage);
12265                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12266                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12267                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12268                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12269                try {
12270                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12271                            null);
12272                } catch (PackageManagerException e) {
12273                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12274                            + e.getMessage());
12275                    return;
12276                }
12277                // Restore of old package succeeded. Update permissions.
12278                // writer
12279                synchronized (mPackages) {
12280                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12281                            UPDATE_PERMISSIONS_ALL);
12282                    // can downgrade to reader
12283                    mSettings.writeLPr();
12284                }
12285                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12286            }
12287        }
12288    }
12289
12290    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12291            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12292            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12293            String volumeUuid, PackageInstalledInfo res) {
12294        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12295                + ", old=" + deletedPackage);
12296        boolean disabledSystem = false;
12297        boolean updatedSettings = false;
12298        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12299        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12300                != 0) {
12301            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12302        }
12303        String packageName = deletedPackage.packageName;
12304        if (packageName == null) {
12305            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12306                    "Attempt to delete null packageName.");
12307            return;
12308        }
12309        PackageParser.Package oldPkg;
12310        PackageSetting oldPkgSetting;
12311        // reader
12312        synchronized (mPackages) {
12313            oldPkg = mPackages.get(packageName);
12314            oldPkgSetting = mSettings.mPackages.get(packageName);
12315            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12316                    (oldPkgSetting == null)) {
12317                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12318                        "Couldn't find package:" + packageName + " information");
12319                return;
12320            }
12321        }
12322
12323        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12324
12325        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12326        res.removedInfo.removedPackage = packageName;
12327        // Remove existing system package
12328        removePackageLI(oldPkgSetting, true);
12329        // writer
12330        synchronized (mPackages) {
12331            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12332            if (!disabledSystem && deletedPackage != null) {
12333                // We didn't need to disable the .apk as a current system package,
12334                // which means we are replacing another update that is already
12335                // installed.  We need to make sure to delete the older one's .apk.
12336                res.removedInfo.args = createInstallArgsForExisting(0,
12337                        deletedPackage.applicationInfo.getCodePath(),
12338                        deletedPackage.applicationInfo.getResourcePath(),
12339                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12340            } else {
12341                res.removedInfo.args = null;
12342            }
12343        }
12344
12345        // Successfully disabled the old package. Now proceed with re-installation
12346        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12347
12348        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12349        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12350
12351        PackageParser.Package newPackage = null;
12352        try {
12353            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12354            if (newPackage.mExtras != null) {
12355                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12356                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12357                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12358
12359                // is the update attempting to change shared user? that isn't going to work...
12360                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12361                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12362                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12363                            + " to " + newPkgSetting.sharedUser);
12364                    updatedSettings = true;
12365                }
12366            }
12367
12368            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12369                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12370                        perUserInstalled, res, user);
12371                updatedSettings = true;
12372            }
12373
12374        } catch (PackageManagerException e) {
12375            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12376        }
12377
12378        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12379            // Re installation failed. Restore old information
12380            // Remove new pkg information
12381            if (newPackage != null) {
12382                removeInstalledPackageLI(newPackage, true);
12383            }
12384            // Add back the old system package
12385            try {
12386                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12387            } catch (PackageManagerException e) {
12388                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12389            }
12390            // Restore the old system information in Settings
12391            synchronized (mPackages) {
12392                if (disabledSystem) {
12393                    mSettings.enableSystemPackageLPw(packageName);
12394                }
12395                if (updatedSettings) {
12396                    mSettings.setInstallerPackageName(packageName,
12397                            oldPkgSetting.installerPackageName);
12398                }
12399                mSettings.writeLPr();
12400            }
12401        }
12402    }
12403
12404    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12405        // Collect all used permissions in the UID
12406        ArraySet<String> usedPermissions = new ArraySet<>();
12407        final int packageCount = su.packages.size();
12408        for (int i = 0; i < packageCount; i++) {
12409            PackageSetting ps = su.packages.valueAt(i);
12410            if (ps.pkg == null) {
12411                continue;
12412            }
12413            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12414            for (int j = 0; j < requestedPermCount; j++) {
12415                String permission = ps.pkg.requestedPermissions.get(j);
12416                BasePermission bp = mSettings.mPermissions.get(permission);
12417                if (bp != null) {
12418                    usedPermissions.add(permission);
12419                }
12420            }
12421        }
12422
12423        PermissionsState permissionsState = su.getPermissionsState();
12424        // Prune install permissions
12425        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12426        final int installPermCount = installPermStates.size();
12427        for (int i = installPermCount - 1; i >= 0;  i--) {
12428            PermissionState permissionState = installPermStates.get(i);
12429            if (!usedPermissions.contains(permissionState.getName())) {
12430                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12431                if (bp != null) {
12432                    permissionsState.revokeInstallPermission(bp);
12433                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12434                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12435                }
12436            }
12437        }
12438
12439        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12440
12441        // Prune runtime permissions
12442        for (int userId : allUserIds) {
12443            List<PermissionState> runtimePermStates = permissionsState
12444                    .getRuntimePermissionStates(userId);
12445            final int runtimePermCount = runtimePermStates.size();
12446            for (int i = runtimePermCount - 1; i >= 0; i--) {
12447                PermissionState permissionState = runtimePermStates.get(i);
12448                if (!usedPermissions.contains(permissionState.getName())) {
12449                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12450                    if (bp != null) {
12451                        permissionsState.revokeRuntimePermission(bp, userId);
12452                        permissionsState.updatePermissionFlags(bp, userId,
12453                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12454                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12455                                runtimePermissionChangedUserIds, userId);
12456                    }
12457                }
12458            }
12459        }
12460
12461        return runtimePermissionChangedUserIds;
12462    }
12463
12464    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12465            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12466            UserHandle user) {
12467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12468
12469        String pkgName = newPackage.packageName;
12470        synchronized (mPackages) {
12471            //write settings. the installStatus will be incomplete at this stage.
12472            //note that the new package setting would have already been
12473            //added to mPackages. It hasn't been persisted yet.
12474            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12476            mSettings.writeLPr();
12477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12478        }
12479
12480        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12481        synchronized (mPackages) {
12482            updatePermissionsLPw(newPackage.packageName, newPackage,
12483                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12484                            ? UPDATE_PERMISSIONS_ALL : 0));
12485            // For system-bundled packages, we assume that installing an upgraded version
12486            // of the package implies that the user actually wants to run that new code,
12487            // so we enable the package.
12488            PackageSetting ps = mSettings.mPackages.get(pkgName);
12489            if (ps != null) {
12490                if (isSystemApp(newPackage)) {
12491                    // NB: implicit assumption that system package upgrades apply to all users
12492                    if (DEBUG_INSTALL) {
12493                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12494                    }
12495                    if (res.origUsers != null) {
12496                        for (int userHandle : res.origUsers) {
12497                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12498                                    userHandle, installerPackageName);
12499                        }
12500                    }
12501                    // Also convey the prior install/uninstall state
12502                    if (allUsers != null && perUserInstalled != null) {
12503                        for (int i = 0; i < allUsers.length; i++) {
12504                            if (DEBUG_INSTALL) {
12505                                Slog.d(TAG, "    user " + allUsers[i]
12506                                        + " => " + perUserInstalled[i]);
12507                            }
12508                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12509                        }
12510                        // these install state changes will be persisted in the
12511                        // upcoming call to mSettings.writeLPr().
12512                    }
12513                }
12514                // It's implied that when a user requests installation, they want the app to be
12515                // installed and enabled.
12516                int userId = user.getIdentifier();
12517                if (userId != UserHandle.USER_ALL) {
12518                    ps.setInstalled(true, userId);
12519                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12520                }
12521            }
12522            res.name = pkgName;
12523            res.uid = newPackage.applicationInfo.uid;
12524            res.pkg = newPackage;
12525            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12526            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12527            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12528            //to update install status
12529            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12530            mSettings.writeLPr();
12531            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12532        }
12533
12534        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12535    }
12536
12537    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12538        try {
12539            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12540            installPackageLI(args, res);
12541        } finally {
12542            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12543        }
12544    }
12545
12546    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12547        final int installFlags = args.installFlags;
12548        final String installerPackageName = args.installerPackageName;
12549        final String volumeUuid = args.volumeUuid;
12550        final File tmpPackageFile = new File(args.getCodePath());
12551        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12552        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12553                || (args.volumeUuid != null));
12554        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12555        boolean replace = false;
12556        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12557        if (args.move != null) {
12558            // moving a complete application; perfom an initial scan on the new install location
12559            scanFlags |= SCAN_INITIAL;
12560        }
12561        // Result object to be returned
12562        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12563
12564        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12565
12566        // Retrieve PackageSettings and parse package
12567        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12568                | PackageParser.PARSE_ENFORCE_CODE
12569                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12570                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12571                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12572        PackageParser pp = new PackageParser();
12573        pp.setSeparateProcesses(mSeparateProcesses);
12574        pp.setDisplayMetrics(mMetrics);
12575
12576        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12577        final PackageParser.Package pkg;
12578        try {
12579            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12580        } catch (PackageParserException e) {
12581            res.setError("Failed parse during installPackageLI", e);
12582            return;
12583        } finally {
12584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12585        }
12586
12587        // Mark that we have an install time CPU ABI override.
12588        pkg.cpuAbiOverride = args.abiOverride;
12589
12590        String pkgName = res.name = pkg.packageName;
12591        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12592            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12593                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12594                return;
12595            }
12596        }
12597
12598        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12599        try {
12600            pp.collectCertificates(pkg, parseFlags);
12601        } catch (PackageParserException e) {
12602            res.setError("Failed collect during installPackageLI", e);
12603            return;
12604        } finally {
12605            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12606        }
12607
12608        /* If the installer passed in a manifest digest, compare it now. */
12609        if (args.manifestDigest != null) {
12610            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12611            try {
12612                pp.collectManifestDigest(pkg);
12613            } catch (PackageParserException e) {
12614                res.setError("Failed collect during installPackageLI", e);
12615                return;
12616            } finally {
12617                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12618            }
12619
12620            if (DEBUG_INSTALL) {
12621                final String parsedManifest = pkg.manifestDigest == null ? "null"
12622                        : pkg.manifestDigest.toString();
12623                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12624                        + parsedManifest);
12625            }
12626
12627            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12628                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12629                return;
12630            }
12631        } else if (DEBUG_INSTALL) {
12632            final String parsedManifest = pkg.manifestDigest == null
12633                    ? "null" : pkg.manifestDigest.toString();
12634            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12635        }
12636
12637        // Get rid of all references to package scan path via parser.
12638        pp = null;
12639        String oldCodePath = null;
12640        boolean systemApp = false;
12641        synchronized (mPackages) {
12642            // Check if installing already existing package
12643            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12644                String oldName = mSettings.mRenamedPackages.get(pkgName);
12645                if (pkg.mOriginalPackages != null
12646                        && pkg.mOriginalPackages.contains(oldName)
12647                        && mPackages.containsKey(oldName)) {
12648                    // This package is derived from an original package,
12649                    // and this device has been updating from that original
12650                    // name.  We must continue using the original name, so
12651                    // rename the new package here.
12652                    pkg.setPackageName(oldName);
12653                    pkgName = pkg.packageName;
12654                    replace = true;
12655                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12656                            + oldName + " pkgName=" + pkgName);
12657                } else if (mPackages.containsKey(pkgName)) {
12658                    // This package, under its official name, already exists
12659                    // on the device; we should replace it.
12660                    replace = true;
12661                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12662                }
12663
12664                // Prevent apps opting out from runtime permissions
12665                if (replace) {
12666                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12667                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12668                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12669                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12670                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12671                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12672                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12673                                        + " doesn't support runtime permissions but the old"
12674                                        + " target SDK " + oldTargetSdk + " does.");
12675                        return;
12676                    }
12677                }
12678            }
12679
12680            PackageSetting ps = mSettings.mPackages.get(pkgName);
12681            if (ps != null) {
12682                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12683
12684                // Quick sanity check that we're signed correctly if updating;
12685                // we'll check this again later when scanning, but we want to
12686                // bail early here before tripping over redefined permissions.
12687                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12688                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12689                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12690                                + pkg.packageName + " upgrade keys do not match the "
12691                                + "previously installed version");
12692                        return;
12693                    }
12694                } else {
12695                    try {
12696                        verifySignaturesLP(ps, pkg);
12697                    } catch (PackageManagerException e) {
12698                        res.setError(e.error, e.getMessage());
12699                        return;
12700                    }
12701                }
12702
12703                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12704                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12705                    systemApp = (ps.pkg.applicationInfo.flags &
12706                            ApplicationInfo.FLAG_SYSTEM) != 0;
12707                }
12708                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12709            }
12710
12711            // Check whether the newly-scanned package wants to define an already-defined perm
12712            int N = pkg.permissions.size();
12713            for (int i = N-1; i >= 0; i--) {
12714                PackageParser.Permission perm = pkg.permissions.get(i);
12715                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12716                if (bp != null) {
12717                    // If the defining package is signed with our cert, it's okay.  This
12718                    // also includes the "updating the same package" case, of course.
12719                    // "updating same package" could also involve key-rotation.
12720                    final boolean sigsOk;
12721                    if (bp.sourcePackage.equals(pkg.packageName)
12722                            && (bp.packageSetting instanceof PackageSetting)
12723                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12724                                    scanFlags))) {
12725                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12726                    } else {
12727                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12728                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12729                    }
12730                    if (!sigsOk) {
12731                        // If the owning package is the system itself, we log but allow
12732                        // install to proceed; we fail the install on all other permission
12733                        // redefinitions.
12734                        if (!bp.sourcePackage.equals("android")) {
12735                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12736                                    + pkg.packageName + " attempting to redeclare permission "
12737                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12738                            res.origPermission = perm.info.name;
12739                            res.origPackage = bp.sourcePackage;
12740                            return;
12741                        } else {
12742                            Slog.w(TAG, "Package " + pkg.packageName
12743                                    + " attempting to redeclare system permission "
12744                                    + perm.info.name + "; ignoring new declaration");
12745                            pkg.permissions.remove(i);
12746                        }
12747                    }
12748                }
12749            }
12750
12751        }
12752
12753        if (systemApp && onExternal) {
12754            // Disable updates to system apps on sdcard
12755            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12756                    "Cannot install updates to system apps on sdcard");
12757            return;
12758        }
12759
12760        if (args.move != null) {
12761            // We did an in-place move, so dex is ready to roll
12762            scanFlags |= SCAN_NO_DEX;
12763            scanFlags |= SCAN_MOVE;
12764
12765            synchronized (mPackages) {
12766                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12767                if (ps == null) {
12768                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12769                            "Missing settings for moved package " + pkgName);
12770                }
12771
12772                // We moved the entire application as-is, so bring over the
12773                // previously derived ABI information.
12774                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12775                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12776            }
12777
12778        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12779            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12780            scanFlags |= SCAN_NO_DEX;
12781
12782            try {
12783                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12784                        true /* extract libs */);
12785            } catch (PackageManagerException pme) {
12786                Slog.e(TAG, "Error deriving application ABI", pme);
12787                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12788                return;
12789            }
12790        }
12791
12792        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12793            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12794            return;
12795        }
12796
12797        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12798
12799        if (replace) {
12800            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12801                    installerPackageName, volumeUuid, res);
12802        } else {
12803            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12804                    args.user, installerPackageName, volumeUuid, res);
12805        }
12806        synchronized (mPackages) {
12807            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12808            if (ps != null) {
12809                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12810            }
12811        }
12812    }
12813
12814    private void startIntentFilterVerifications(int userId, boolean replacing,
12815            PackageParser.Package pkg) {
12816        if (mIntentFilterVerifierComponent == null) {
12817            Slog.w(TAG, "No IntentFilter verification will not be done as "
12818                    + "there is no IntentFilterVerifier available!");
12819            return;
12820        }
12821
12822        final int verifierUid = getPackageUid(
12823                mIntentFilterVerifierComponent.getPackageName(),
12824                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12825
12826        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12827        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12828        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12829        mHandler.sendMessage(msg);
12830    }
12831
12832    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12833            PackageParser.Package pkg) {
12834        int size = pkg.activities.size();
12835        if (size == 0) {
12836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12837                    "No activity, so no need to verify any IntentFilter!");
12838            return;
12839        }
12840
12841        final boolean hasDomainURLs = hasDomainURLs(pkg);
12842        if (!hasDomainURLs) {
12843            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12844                    "No domain URLs, so no need to verify any IntentFilter!");
12845            return;
12846        }
12847
12848        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12849                + " if any IntentFilter from the " + size
12850                + " Activities needs verification ...");
12851
12852        int count = 0;
12853        final String packageName = pkg.packageName;
12854
12855        synchronized (mPackages) {
12856            // If this is a new install and we see that we've already run verification for this
12857            // package, we have nothing to do: it means the state was restored from backup.
12858            if (!replacing) {
12859                IntentFilterVerificationInfo ivi =
12860                        mSettings.getIntentFilterVerificationLPr(packageName);
12861                if (ivi != null) {
12862                    if (DEBUG_DOMAIN_VERIFICATION) {
12863                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12864                                + ivi.getStatusString());
12865                    }
12866                    return;
12867                }
12868            }
12869
12870            // If any filters need to be verified, then all need to be.
12871            boolean needToVerify = false;
12872            for (PackageParser.Activity a : pkg.activities) {
12873                for (ActivityIntentInfo filter : a.intents) {
12874                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12875                        if (DEBUG_DOMAIN_VERIFICATION) {
12876                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12877                        }
12878                        needToVerify = true;
12879                        break;
12880                    }
12881                }
12882            }
12883
12884            if (needToVerify) {
12885                final int verificationId = mIntentFilterVerificationToken++;
12886                for (PackageParser.Activity a : pkg.activities) {
12887                    for (ActivityIntentInfo filter : a.intents) {
12888                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12889                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12890                                    "Verification needed for IntentFilter:" + filter.toString());
12891                            mIntentFilterVerifier.addOneIntentFilterVerification(
12892                                    verifierUid, userId, verificationId, filter, packageName);
12893                            count++;
12894                        }
12895                    }
12896                }
12897            }
12898        }
12899
12900        if (count > 0) {
12901            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12902                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12903                    +  " for userId:" + userId);
12904            mIntentFilterVerifier.startVerifications(userId);
12905        } else {
12906            if (DEBUG_DOMAIN_VERIFICATION) {
12907                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12908            }
12909        }
12910    }
12911
12912    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12913        final ComponentName cn  = filter.activity.getComponentName();
12914        final String packageName = cn.getPackageName();
12915
12916        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12917                packageName);
12918        if (ivi == null) {
12919            return true;
12920        }
12921        int status = ivi.getStatus();
12922        switch (status) {
12923            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12924            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12925                return true;
12926
12927            default:
12928                // Nothing to do
12929                return false;
12930        }
12931    }
12932
12933    private static boolean isMultiArch(PackageSetting ps) {
12934        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12935    }
12936
12937    private static boolean isMultiArch(ApplicationInfo info) {
12938        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12939    }
12940
12941    private static boolean isExternal(PackageParser.Package pkg) {
12942        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12943    }
12944
12945    private static boolean isExternal(PackageSetting ps) {
12946        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12947    }
12948
12949    private static boolean isExternal(ApplicationInfo info) {
12950        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12951    }
12952
12953    private static boolean isSystemApp(PackageParser.Package pkg) {
12954        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12955    }
12956
12957    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12958        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12959    }
12960
12961    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12962        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12963    }
12964
12965    private static boolean isSystemApp(PackageSetting ps) {
12966        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12967    }
12968
12969    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12970        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12971    }
12972
12973    private int packageFlagsToInstallFlags(PackageSetting ps) {
12974        int installFlags = 0;
12975        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12976            // This existing package was an external ASEC install when we have
12977            // the external flag without a UUID
12978            installFlags |= PackageManager.INSTALL_EXTERNAL;
12979        }
12980        if (ps.isForwardLocked()) {
12981            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12982        }
12983        return installFlags;
12984    }
12985
12986    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12987        if (isExternal(pkg)) {
12988            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12989                return StorageManager.UUID_PRIMARY_PHYSICAL;
12990            } else {
12991                return pkg.volumeUuid;
12992            }
12993        } else {
12994            return StorageManager.UUID_PRIVATE_INTERNAL;
12995        }
12996    }
12997
12998    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12999        if (isExternal(pkg)) {
13000            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13001                return mSettings.getExternalVersion();
13002            } else {
13003                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13004            }
13005        } else {
13006            return mSettings.getInternalVersion();
13007        }
13008    }
13009
13010    private void deleteTempPackageFiles() {
13011        final FilenameFilter filter = new FilenameFilter() {
13012            public boolean accept(File dir, String name) {
13013                return name.startsWith("vmdl") && name.endsWith(".tmp");
13014            }
13015        };
13016        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13017            file.delete();
13018        }
13019    }
13020
13021    @Override
13022    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13023            int flags) {
13024        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13025                flags);
13026    }
13027
13028    @Override
13029    public void deletePackage(final String packageName,
13030            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13031        mContext.enforceCallingOrSelfPermission(
13032                android.Manifest.permission.DELETE_PACKAGES, null);
13033        Preconditions.checkNotNull(packageName);
13034        Preconditions.checkNotNull(observer);
13035        final int uid = Binder.getCallingUid();
13036        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13037        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13038        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13039            mContext.enforceCallingOrSelfPermission(
13040                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13041                    "deletePackage for user " + userId);
13042        }
13043
13044        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13045            try {
13046                observer.onPackageDeleted(packageName,
13047                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13048            } catch (RemoteException re) {
13049            }
13050            return;
13051        }
13052
13053        for (int currentUserId : users) {
13054            if (getBlockUninstallForUser(packageName, currentUserId)) {
13055                try {
13056                    observer.onPackageDeleted(packageName,
13057                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13058                } catch (RemoteException re) {
13059                }
13060                return;
13061            }
13062        }
13063
13064        if (DEBUG_REMOVE) {
13065            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13066        }
13067        // Queue up an async operation since the package deletion may take a little while.
13068        mHandler.post(new Runnable() {
13069            public void run() {
13070                mHandler.removeCallbacks(this);
13071                final int returnCode = deletePackageX(packageName, userId, flags);
13072                try {
13073                    observer.onPackageDeleted(packageName, returnCode, null);
13074                } catch (RemoteException e) {
13075                    Log.i(TAG, "Observer no longer exists.");
13076                } //end catch
13077            } //end run
13078        });
13079    }
13080
13081    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13082        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13083                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13084        try {
13085            if (dpm != null) {
13086                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13087                        /* callingUserOnly =*/ false);
13088                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13089                        : deviceOwnerComponentName.getPackageName();
13090                // Does the package contains the device owner?
13091                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13092                // this check is probably not needed, since DO should be registered as a device
13093                // admin on some user too. (Original bug for this: b/17657954)
13094                if (packageName.equals(deviceOwnerPackageName)) {
13095                    return true;
13096                }
13097                // Does it contain a device admin for any user?
13098                int[] users;
13099                if (userId == UserHandle.USER_ALL) {
13100                    users = sUserManager.getUserIds();
13101                } else {
13102                    users = new int[]{userId};
13103                }
13104                for (int i = 0; i < users.length; ++i) {
13105                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13106                        return true;
13107                    }
13108                }
13109            }
13110        } catch (RemoteException e) {
13111        }
13112        return false;
13113    }
13114
13115    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13116        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13117    }
13118
13119    /**
13120     *  This method is an internal method that could be get invoked either
13121     *  to delete an installed package or to clean up a failed installation.
13122     *  After deleting an installed package, a broadcast is sent to notify any
13123     *  listeners that the package has been installed. For cleaning up a failed
13124     *  installation, the broadcast is not necessary since the package's
13125     *  installation wouldn't have sent the initial broadcast either
13126     *  The key steps in deleting a package are
13127     *  deleting the package information in internal structures like mPackages,
13128     *  deleting the packages base directories through installd
13129     *  updating mSettings to reflect current status
13130     *  persisting settings for later use
13131     *  sending a broadcast if necessary
13132     */
13133    private int deletePackageX(String packageName, int userId, int flags) {
13134        final PackageRemovedInfo info = new PackageRemovedInfo();
13135        final boolean res;
13136
13137        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13138                ? UserHandle.ALL : new UserHandle(userId);
13139
13140        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13141            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13142            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13143        }
13144
13145        boolean removedForAllUsers = false;
13146        boolean systemUpdate = false;
13147
13148        // for the uninstall-updates case and restricted profiles, remember the per-
13149        // userhandle installed state
13150        int[] allUsers;
13151        boolean[] perUserInstalled;
13152        synchronized (mPackages) {
13153            PackageSetting ps = mSettings.mPackages.get(packageName);
13154            allUsers = sUserManager.getUserIds();
13155            perUserInstalled = new boolean[allUsers.length];
13156            for (int i = 0; i < allUsers.length; i++) {
13157                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13158            }
13159        }
13160
13161        synchronized (mInstallLock) {
13162            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13163            res = deletePackageLI(packageName, removeForUser,
13164                    true, allUsers, perUserInstalled,
13165                    flags | REMOVE_CHATTY, info, true);
13166            systemUpdate = info.isRemovedPackageSystemUpdate;
13167            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13168                removedForAllUsers = true;
13169            }
13170            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13171                    + " removedForAllUsers=" + removedForAllUsers);
13172        }
13173
13174        if (res) {
13175            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13176
13177            // If the removed package was a system update, the old system package
13178            // was re-enabled; we need to broadcast this information
13179            if (systemUpdate) {
13180                Bundle extras = new Bundle(1);
13181                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13182                        ? info.removedAppId : info.uid);
13183                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13184
13185                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13186                        extras, 0, null, null, null);
13187                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13188                        extras, 0, null, null, null);
13189                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13190                        null, 0, packageName, null, null);
13191            }
13192        }
13193        // Force a gc here.
13194        Runtime.getRuntime().gc();
13195        // Delete the resources here after sending the broadcast to let
13196        // other processes clean up before deleting resources.
13197        if (info.args != null) {
13198            synchronized (mInstallLock) {
13199                info.args.doPostDeleteLI(true);
13200            }
13201        }
13202
13203        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13204    }
13205
13206    class PackageRemovedInfo {
13207        String removedPackage;
13208        int uid = -1;
13209        int removedAppId = -1;
13210        int[] removedUsers = null;
13211        boolean isRemovedPackageSystemUpdate = false;
13212        // Clean up resources deleted packages.
13213        InstallArgs args = null;
13214
13215        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13216            Bundle extras = new Bundle(1);
13217            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13218            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13219            if (replacing) {
13220                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13221            }
13222            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13223            if (removedPackage != null) {
13224                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13225                        extras, 0, null, null, removedUsers);
13226                if (fullRemove && !replacing) {
13227                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13228                            extras, 0, null, null, removedUsers);
13229                }
13230            }
13231            if (removedAppId >= 0) {
13232                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13233                        removedUsers);
13234            }
13235        }
13236    }
13237
13238    /*
13239     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13240     * flag is not set, the data directory is removed as well.
13241     * make sure this flag is set for partially installed apps. If not its meaningless to
13242     * delete a partially installed application.
13243     */
13244    private void removePackageDataLI(PackageSetting ps,
13245            int[] allUserHandles, boolean[] perUserInstalled,
13246            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13247        String packageName = ps.name;
13248        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13249        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13250        // Retrieve object to delete permissions for shared user later on
13251        final PackageSetting deletedPs;
13252        // reader
13253        synchronized (mPackages) {
13254            deletedPs = mSettings.mPackages.get(packageName);
13255            if (outInfo != null) {
13256                outInfo.removedPackage = packageName;
13257                outInfo.removedUsers = deletedPs != null
13258                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13259                        : null;
13260            }
13261        }
13262        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13263            removeDataDirsLI(ps.volumeUuid, packageName);
13264            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13265        }
13266        // writer
13267        synchronized (mPackages) {
13268            if (deletedPs != null) {
13269                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13270                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13271                    clearDefaultBrowserIfNeeded(packageName);
13272                    if (outInfo != null) {
13273                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13274                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13275                    }
13276                    updatePermissionsLPw(deletedPs.name, null, 0);
13277                    if (deletedPs.sharedUser != null) {
13278                        // Remove permissions associated with package. Since runtime
13279                        // permissions are per user we have to kill the removed package
13280                        // or packages running under the shared user of the removed
13281                        // package if revoking the permissions requested only by the removed
13282                        // package is successful and this causes a change in gids.
13283                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13284                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13285                                    userId);
13286                            if (userIdToKill == UserHandle.USER_ALL
13287                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13288                                // If gids changed for this user, kill all affected packages.
13289                                mHandler.post(new Runnable() {
13290                                    @Override
13291                                    public void run() {
13292                                        // This has to happen with no lock held.
13293                                        killApplication(deletedPs.name, deletedPs.appId,
13294                                                KILL_APP_REASON_GIDS_CHANGED);
13295                                    }
13296                                });
13297                                break;
13298                            }
13299                        }
13300                    }
13301                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13302                }
13303                // make sure to preserve per-user disabled state if this removal was just
13304                // a downgrade of a system app to the factory package
13305                if (allUserHandles != null && perUserInstalled != null) {
13306                    if (DEBUG_REMOVE) {
13307                        Slog.d(TAG, "Propagating install state across downgrade");
13308                    }
13309                    for (int i = 0; i < allUserHandles.length; i++) {
13310                        if (DEBUG_REMOVE) {
13311                            Slog.d(TAG, "    user " + allUserHandles[i]
13312                                    + " => " + perUserInstalled[i]);
13313                        }
13314                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13315                    }
13316                }
13317            }
13318            // can downgrade to reader
13319            if (writeSettings) {
13320                // Save settings now
13321                mSettings.writeLPr();
13322            }
13323        }
13324        if (outInfo != null) {
13325            // A user ID was deleted here. Go through all users and remove it
13326            // from KeyStore.
13327            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13328        }
13329    }
13330
13331    static boolean locationIsPrivileged(File path) {
13332        try {
13333            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13334                    .getCanonicalPath();
13335            return path.getCanonicalPath().startsWith(privilegedAppDir);
13336        } catch (IOException e) {
13337            Slog.e(TAG, "Unable to access code path " + path);
13338        }
13339        return false;
13340    }
13341
13342    /*
13343     * Tries to delete system package.
13344     */
13345    private boolean deleteSystemPackageLI(PackageSetting newPs,
13346            int[] allUserHandles, boolean[] perUserInstalled,
13347            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13348        final boolean applyUserRestrictions
13349                = (allUserHandles != null) && (perUserInstalled != null);
13350        PackageSetting disabledPs = null;
13351        // Confirm if the system package has been updated
13352        // An updated system app can be deleted. This will also have to restore
13353        // the system pkg from system partition
13354        // reader
13355        synchronized (mPackages) {
13356            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13357        }
13358        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13359                + " disabledPs=" + disabledPs);
13360        if (disabledPs == null) {
13361            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13362            return false;
13363        } else if (DEBUG_REMOVE) {
13364            Slog.d(TAG, "Deleting system pkg from data partition");
13365        }
13366        if (DEBUG_REMOVE) {
13367            if (applyUserRestrictions) {
13368                Slog.d(TAG, "Remembering install states:");
13369                for (int i = 0; i < allUserHandles.length; i++) {
13370                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13371                }
13372            }
13373        }
13374        // Delete the updated package
13375        outInfo.isRemovedPackageSystemUpdate = true;
13376        if (disabledPs.versionCode < newPs.versionCode) {
13377            // Delete data for downgrades
13378            flags &= ~PackageManager.DELETE_KEEP_DATA;
13379        } else {
13380            // Preserve data by setting flag
13381            flags |= PackageManager.DELETE_KEEP_DATA;
13382        }
13383        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13384                allUserHandles, perUserInstalled, outInfo, writeSettings);
13385        if (!ret) {
13386            return false;
13387        }
13388        // writer
13389        synchronized (mPackages) {
13390            // Reinstate the old system package
13391            mSettings.enableSystemPackageLPw(newPs.name);
13392            // Remove any native libraries from the upgraded package.
13393            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13394        }
13395        // Install the system package
13396        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13397        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13398        if (locationIsPrivileged(disabledPs.codePath)) {
13399            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13400        }
13401
13402        final PackageParser.Package newPkg;
13403        try {
13404            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13405        } catch (PackageManagerException e) {
13406            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13407            return false;
13408        }
13409
13410        // writer
13411        synchronized (mPackages) {
13412            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13413
13414            // Propagate the permissions state as we do not want to drop on the floor
13415            // runtime permissions. The update permissions method below will take
13416            // care of removing obsolete permissions and grant install permissions.
13417            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13418            updatePermissionsLPw(newPkg.packageName, newPkg,
13419                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13420
13421            if (applyUserRestrictions) {
13422                if (DEBUG_REMOVE) {
13423                    Slog.d(TAG, "Propagating install state across reinstall");
13424                }
13425                for (int i = 0; i < allUserHandles.length; i++) {
13426                    if (DEBUG_REMOVE) {
13427                        Slog.d(TAG, "    user " + allUserHandles[i]
13428                                + " => " + perUserInstalled[i]);
13429                    }
13430                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13431
13432                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13433                }
13434                // Regardless of writeSettings we need to ensure that this restriction
13435                // state propagation is persisted
13436                mSettings.writeAllUsersPackageRestrictionsLPr();
13437            }
13438            // can downgrade to reader here
13439            if (writeSettings) {
13440                mSettings.writeLPr();
13441            }
13442        }
13443        return true;
13444    }
13445
13446    private boolean deleteInstalledPackageLI(PackageSetting ps,
13447            boolean deleteCodeAndResources, int flags,
13448            int[] allUserHandles, boolean[] perUserInstalled,
13449            PackageRemovedInfo outInfo, boolean writeSettings) {
13450        if (outInfo != null) {
13451            outInfo.uid = ps.appId;
13452        }
13453
13454        // Delete package data from internal structures and also remove data if flag is set
13455        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13456
13457        // Delete application code and resources
13458        if (deleteCodeAndResources && (outInfo != null)) {
13459            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13460                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13461            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13462        }
13463        return true;
13464    }
13465
13466    @Override
13467    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13468            int userId) {
13469        mContext.enforceCallingOrSelfPermission(
13470                android.Manifest.permission.DELETE_PACKAGES, null);
13471        synchronized (mPackages) {
13472            PackageSetting ps = mSettings.mPackages.get(packageName);
13473            if (ps == null) {
13474                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13475                return false;
13476            }
13477            if (!ps.getInstalled(userId)) {
13478                // Can't block uninstall for an app that is not installed or enabled.
13479                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13480                return false;
13481            }
13482            ps.setBlockUninstall(blockUninstall, userId);
13483            mSettings.writePackageRestrictionsLPr(userId);
13484        }
13485        return true;
13486    }
13487
13488    @Override
13489    public boolean getBlockUninstallForUser(String packageName, int userId) {
13490        synchronized (mPackages) {
13491            PackageSetting ps = mSettings.mPackages.get(packageName);
13492            if (ps == null) {
13493                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13494                return false;
13495            }
13496            return ps.getBlockUninstall(userId);
13497        }
13498    }
13499
13500    /*
13501     * This method handles package deletion in general
13502     */
13503    private boolean deletePackageLI(String packageName, UserHandle user,
13504            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13505            int flags, PackageRemovedInfo outInfo,
13506            boolean writeSettings) {
13507        if (packageName == null) {
13508            Slog.w(TAG, "Attempt to delete null packageName.");
13509            return false;
13510        }
13511        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13512        PackageSetting ps;
13513        boolean dataOnly = false;
13514        int removeUser = -1;
13515        int appId = -1;
13516        synchronized (mPackages) {
13517            ps = mSettings.mPackages.get(packageName);
13518            if (ps == null) {
13519                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13520                return false;
13521            }
13522            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13523                    && user.getIdentifier() != UserHandle.USER_ALL) {
13524                // The caller is asking that the package only be deleted for a single
13525                // user.  To do this, we just mark its uninstalled state and delete
13526                // its data.  If this is a system app, we only allow this to happen if
13527                // they have set the special DELETE_SYSTEM_APP which requests different
13528                // semantics than normal for uninstalling system apps.
13529                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13530                final int userId = user.getIdentifier();
13531                ps.setUserState(userId,
13532                        COMPONENT_ENABLED_STATE_DEFAULT,
13533                        false, //installed
13534                        true,  //stopped
13535                        true,  //notLaunched
13536                        false, //hidden
13537                        null, null, null,
13538                        false, // blockUninstall
13539                        ps.readUserState(userId).domainVerificationStatus, 0);
13540                if (!isSystemApp(ps)) {
13541                    // Do not uninstall the APK if an app should be cached
13542                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13543                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13544                        // Other user still have this package installed, so all
13545                        // we need to do is clear this user's data and save that
13546                        // it is uninstalled.
13547                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13548                        removeUser = user.getIdentifier();
13549                        appId = ps.appId;
13550                        scheduleWritePackageRestrictionsLocked(removeUser);
13551                    } else {
13552                        // We need to set it back to 'installed' so the uninstall
13553                        // broadcasts will be sent correctly.
13554                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13555                        ps.setInstalled(true, user.getIdentifier());
13556                    }
13557                } else {
13558                    // This is a system app, so we assume that the
13559                    // other users still have this package installed, so all
13560                    // we need to do is clear this user's data and save that
13561                    // it is uninstalled.
13562                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13563                    removeUser = user.getIdentifier();
13564                    appId = ps.appId;
13565                    scheduleWritePackageRestrictionsLocked(removeUser);
13566                }
13567            }
13568        }
13569
13570        if (removeUser >= 0) {
13571            // From above, we determined that we are deleting this only
13572            // for a single user.  Continue the work here.
13573            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13574            if (outInfo != null) {
13575                outInfo.removedPackage = packageName;
13576                outInfo.removedAppId = appId;
13577                outInfo.removedUsers = new int[] {removeUser};
13578            }
13579            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13580            removeKeystoreDataIfNeeded(removeUser, appId);
13581            schedulePackageCleaning(packageName, removeUser, false);
13582            synchronized (mPackages) {
13583                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13584                    scheduleWritePackageRestrictionsLocked(removeUser);
13585                }
13586                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13587            }
13588            return true;
13589        }
13590
13591        if (dataOnly) {
13592            // Delete application data first
13593            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13594            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13595            return true;
13596        }
13597
13598        boolean ret = false;
13599        if (isSystemApp(ps)) {
13600            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13601            // When an updated system application is deleted we delete the existing resources as well and
13602            // fall back to existing code in system partition
13603            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13604                    flags, outInfo, writeSettings);
13605        } else {
13606            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13607            // Kill application pre-emptively especially for apps on sd.
13608            killApplication(packageName, ps.appId, "uninstall pkg");
13609            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13610                    allUserHandles, perUserInstalled,
13611                    outInfo, writeSettings);
13612        }
13613
13614        return ret;
13615    }
13616
13617    private final class ClearStorageConnection implements ServiceConnection {
13618        IMediaContainerService mContainerService;
13619
13620        @Override
13621        public void onServiceConnected(ComponentName name, IBinder service) {
13622            synchronized (this) {
13623                mContainerService = IMediaContainerService.Stub.asInterface(service);
13624                notifyAll();
13625            }
13626        }
13627
13628        @Override
13629        public void onServiceDisconnected(ComponentName name) {
13630        }
13631    }
13632
13633    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13634        final boolean mounted;
13635        if (Environment.isExternalStorageEmulated()) {
13636            mounted = true;
13637        } else {
13638            final String status = Environment.getExternalStorageState();
13639
13640            mounted = status.equals(Environment.MEDIA_MOUNTED)
13641                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13642        }
13643
13644        if (!mounted) {
13645            return;
13646        }
13647
13648        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13649        int[] users;
13650        if (userId == UserHandle.USER_ALL) {
13651            users = sUserManager.getUserIds();
13652        } else {
13653            users = new int[] { userId };
13654        }
13655        final ClearStorageConnection conn = new ClearStorageConnection();
13656        if (mContext.bindServiceAsUser(
13657                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13658            try {
13659                for (int curUser : users) {
13660                    long timeout = SystemClock.uptimeMillis() + 5000;
13661                    synchronized (conn) {
13662                        long now = SystemClock.uptimeMillis();
13663                        while (conn.mContainerService == null && now < timeout) {
13664                            try {
13665                                conn.wait(timeout - now);
13666                            } catch (InterruptedException e) {
13667                            }
13668                        }
13669                    }
13670                    if (conn.mContainerService == null) {
13671                        return;
13672                    }
13673
13674                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13675                    clearDirectory(conn.mContainerService,
13676                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13677                    if (allData) {
13678                        clearDirectory(conn.mContainerService,
13679                                userEnv.buildExternalStorageAppDataDirs(packageName));
13680                        clearDirectory(conn.mContainerService,
13681                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13682                    }
13683                }
13684            } finally {
13685                mContext.unbindService(conn);
13686            }
13687        }
13688    }
13689
13690    @Override
13691    public void clearApplicationUserData(final String packageName,
13692            final IPackageDataObserver observer, final int userId) {
13693        mContext.enforceCallingOrSelfPermission(
13694                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13695        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13696        // Queue up an async operation since the package deletion may take a little while.
13697        mHandler.post(new Runnable() {
13698            public void run() {
13699                mHandler.removeCallbacks(this);
13700                final boolean succeeded;
13701                synchronized (mInstallLock) {
13702                    succeeded = clearApplicationUserDataLI(packageName, userId);
13703                }
13704                clearExternalStorageDataSync(packageName, userId, true);
13705                if (succeeded) {
13706                    // invoke DeviceStorageMonitor's update method to clear any notifications
13707                    DeviceStorageMonitorInternal
13708                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13709                    if (dsm != null) {
13710                        dsm.checkMemory();
13711                    }
13712                }
13713                if(observer != null) {
13714                    try {
13715                        observer.onRemoveCompleted(packageName, succeeded);
13716                    } catch (RemoteException e) {
13717                        Log.i(TAG, "Observer no longer exists.");
13718                    }
13719                } //end if observer
13720            } //end run
13721        });
13722    }
13723
13724    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13725        if (packageName == null) {
13726            Slog.w(TAG, "Attempt to delete null packageName.");
13727            return false;
13728        }
13729
13730        // Try finding details about the requested package
13731        PackageParser.Package pkg;
13732        synchronized (mPackages) {
13733            pkg = mPackages.get(packageName);
13734            if (pkg == null) {
13735                final PackageSetting ps = mSettings.mPackages.get(packageName);
13736                if (ps != null) {
13737                    pkg = ps.pkg;
13738                }
13739            }
13740
13741            if (pkg == null) {
13742                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13743                return false;
13744            }
13745
13746            PackageSetting ps = (PackageSetting) pkg.mExtras;
13747            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13748        }
13749
13750        // Always delete data directories for package, even if we found no other
13751        // record of app. This helps users recover from UID mismatches without
13752        // resorting to a full data wipe.
13753        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13754        if (retCode < 0) {
13755            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13756            return false;
13757        }
13758
13759        final int appId = pkg.applicationInfo.uid;
13760        removeKeystoreDataIfNeeded(userId, appId);
13761
13762        // Create a native library symlink only if we have native libraries
13763        // and if the native libraries are 32 bit libraries. We do not provide
13764        // this symlink for 64 bit libraries.
13765        if (pkg.applicationInfo.primaryCpuAbi != null &&
13766                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13767            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13768            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13769                    nativeLibPath, userId) < 0) {
13770                Slog.w(TAG, "Failed linking native library dir");
13771                return false;
13772            }
13773        }
13774
13775        return true;
13776    }
13777
13778    /**
13779     * Reverts user permission state changes (permissions and flags) in
13780     * all packages for a given user.
13781     *
13782     * @param userId The device user for which to do a reset.
13783     */
13784    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13785        final int packageCount = mPackages.size();
13786        for (int i = 0; i < packageCount; i++) {
13787            PackageParser.Package pkg = mPackages.valueAt(i);
13788            PackageSetting ps = (PackageSetting) pkg.mExtras;
13789            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13790        }
13791    }
13792
13793    /**
13794     * Reverts user permission state changes (permissions and flags).
13795     *
13796     * @param ps The package for which to reset.
13797     * @param userId The device user for which to do a reset.
13798     */
13799    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13800            final PackageSetting ps, final int userId) {
13801        if (ps.pkg == null) {
13802            return;
13803        }
13804
13805        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13806                | FLAG_PERMISSION_USER_FIXED
13807                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13808
13809        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13810                | FLAG_PERMISSION_POLICY_FIXED;
13811
13812        boolean writeInstallPermissions = false;
13813        boolean writeRuntimePermissions = false;
13814
13815        final int permissionCount = ps.pkg.requestedPermissions.size();
13816        for (int i = 0; i < permissionCount; i++) {
13817            String permission = ps.pkg.requestedPermissions.get(i);
13818
13819            BasePermission bp = mSettings.mPermissions.get(permission);
13820            if (bp == null) {
13821                continue;
13822            }
13823
13824            // If shared user we just reset the state to which only this app contributed.
13825            if (ps.sharedUser != null) {
13826                boolean used = false;
13827                final int packageCount = ps.sharedUser.packages.size();
13828                for (int j = 0; j < packageCount; j++) {
13829                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13830                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13831                            && pkg.pkg.requestedPermissions.contains(permission)) {
13832                        used = true;
13833                        break;
13834                    }
13835                }
13836                if (used) {
13837                    continue;
13838                }
13839            }
13840
13841            PermissionsState permissionsState = ps.getPermissionsState();
13842
13843            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13844
13845            // Always clear the user settable flags.
13846            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13847                    bp.name) != null;
13848            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13849                if (hasInstallState) {
13850                    writeInstallPermissions = true;
13851                } else {
13852                    writeRuntimePermissions = true;
13853                }
13854            }
13855
13856            // Below is only runtime permission handling.
13857            if (!bp.isRuntime()) {
13858                continue;
13859            }
13860
13861            // Never clobber system or policy.
13862            if ((oldFlags & policyOrSystemFlags) != 0) {
13863                continue;
13864            }
13865
13866            // If this permission was granted by default, make sure it is.
13867            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13868                if (permissionsState.grantRuntimePermission(bp, userId)
13869                        != PERMISSION_OPERATION_FAILURE) {
13870                    writeRuntimePermissions = true;
13871                }
13872            } else {
13873                // Otherwise, reset the permission.
13874                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13875                switch (revokeResult) {
13876                    case PERMISSION_OPERATION_SUCCESS: {
13877                        writeRuntimePermissions = true;
13878                    } break;
13879
13880                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13881                        writeRuntimePermissions = true;
13882                        final int appId = ps.appId;
13883                        mHandler.post(new Runnable() {
13884                            @Override
13885                            public void run() {
13886                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13887                            }
13888                        });
13889                    } break;
13890                }
13891            }
13892        }
13893
13894        // Synchronously write as we are taking permissions away.
13895        if (writeRuntimePermissions) {
13896            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13897        }
13898
13899        // Synchronously write as we are taking permissions away.
13900        if (writeInstallPermissions) {
13901            mSettings.writeLPr();
13902        }
13903    }
13904
13905    /**
13906     * Remove entries from the keystore daemon. Will only remove it if the
13907     * {@code appId} is valid.
13908     */
13909    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13910        if (appId < 0) {
13911            return;
13912        }
13913
13914        final KeyStore keyStore = KeyStore.getInstance();
13915        if (keyStore != null) {
13916            if (userId == UserHandle.USER_ALL) {
13917                for (final int individual : sUserManager.getUserIds()) {
13918                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13919                }
13920            } else {
13921                keyStore.clearUid(UserHandle.getUid(userId, appId));
13922            }
13923        } else {
13924            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13925        }
13926    }
13927
13928    @Override
13929    public void deleteApplicationCacheFiles(final String packageName,
13930            final IPackageDataObserver observer) {
13931        mContext.enforceCallingOrSelfPermission(
13932                android.Manifest.permission.DELETE_CACHE_FILES, null);
13933        // Queue up an async operation since the package deletion may take a little while.
13934        final int userId = UserHandle.getCallingUserId();
13935        mHandler.post(new Runnable() {
13936            public void run() {
13937                mHandler.removeCallbacks(this);
13938                final boolean succeded;
13939                synchronized (mInstallLock) {
13940                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13941                }
13942                clearExternalStorageDataSync(packageName, userId, false);
13943                if (observer != null) {
13944                    try {
13945                        observer.onRemoveCompleted(packageName, succeded);
13946                    } catch (RemoteException e) {
13947                        Log.i(TAG, "Observer no longer exists.");
13948                    }
13949                } //end if observer
13950            } //end run
13951        });
13952    }
13953
13954    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13955        if (packageName == null) {
13956            Slog.w(TAG, "Attempt to delete null packageName.");
13957            return false;
13958        }
13959        PackageParser.Package p;
13960        synchronized (mPackages) {
13961            p = mPackages.get(packageName);
13962        }
13963        if (p == null) {
13964            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13965            return false;
13966        }
13967        final ApplicationInfo applicationInfo = p.applicationInfo;
13968        if (applicationInfo == null) {
13969            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13970            return false;
13971        }
13972        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13973        if (retCode < 0) {
13974            Slog.w(TAG, "Couldn't remove cache files for package: "
13975                       + packageName + " u" + userId);
13976            return false;
13977        }
13978        return true;
13979    }
13980
13981    @Override
13982    public void getPackageSizeInfo(final String packageName, int userHandle,
13983            final IPackageStatsObserver observer) {
13984        mContext.enforceCallingOrSelfPermission(
13985                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13986        if (packageName == null) {
13987            throw new IllegalArgumentException("Attempt to get size of null packageName");
13988        }
13989
13990        PackageStats stats = new PackageStats(packageName, userHandle);
13991
13992        /*
13993         * Queue up an async operation since the package measurement may take a
13994         * little while.
13995         */
13996        Message msg = mHandler.obtainMessage(INIT_COPY);
13997        msg.obj = new MeasureParams(stats, observer);
13998        mHandler.sendMessage(msg);
13999    }
14000
14001    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14002            PackageStats pStats) {
14003        if (packageName == null) {
14004            Slog.w(TAG, "Attempt to get size of null packageName.");
14005            return false;
14006        }
14007        PackageParser.Package p;
14008        boolean dataOnly = false;
14009        String libDirRoot = null;
14010        String asecPath = null;
14011        PackageSetting ps = null;
14012        synchronized (mPackages) {
14013            p = mPackages.get(packageName);
14014            ps = mSettings.mPackages.get(packageName);
14015            if(p == null) {
14016                dataOnly = true;
14017                if((ps == null) || (ps.pkg == null)) {
14018                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14019                    return false;
14020                }
14021                p = ps.pkg;
14022            }
14023            if (ps != null) {
14024                libDirRoot = ps.legacyNativeLibraryPathString;
14025            }
14026            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14027                final long token = Binder.clearCallingIdentity();
14028                try {
14029                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14030                    if (secureContainerId != null) {
14031                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14032                    }
14033                } finally {
14034                    Binder.restoreCallingIdentity(token);
14035                }
14036            }
14037        }
14038        String publicSrcDir = null;
14039        if(!dataOnly) {
14040            final ApplicationInfo applicationInfo = p.applicationInfo;
14041            if (applicationInfo == null) {
14042                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14043                return false;
14044            }
14045            if (p.isForwardLocked()) {
14046                publicSrcDir = applicationInfo.getBaseResourcePath();
14047            }
14048        }
14049        // TODO: extend to measure size of split APKs
14050        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14051        // not just the first level.
14052        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14053        // just the primary.
14054        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14055
14056        String apkPath;
14057        File packageDir = new File(p.codePath);
14058
14059        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14060            apkPath = packageDir.getAbsolutePath();
14061            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14062            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14063                libDirRoot = null;
14064            }
14065        } else {
14066            apkPath = p.baseCodePath;
14067        }
14068
14069        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14070                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14071        if (res < 0) {
14072            return false;
14073        }
14074
14075        // Fix-up for forward-locked applications in ASEC containers.
14076        if (!isExternal(p)) {
14077            pStats.codeSize += pStats.externalCodeSize;
14078            pStats.externalCodeSize = 0L;
14079        }
14080
14081        return true;
14082    }
14083
14084
14085    @Override
14086    public void addPackageToPreferred(String packageName) {
14087        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14088    }
14089
14090    @Override
14091    public void removePackageFromPreferred(String packageName) {
14092        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14093    }
14094
14095    @Override
14096    public List<PackageInfo> getPreferredPackages(int flags) {
14097        return new ArrayList<PackageInfo>();
14098    }
14099
14100    private int getUidTargetSdkVersionLockedLPr(int uid) {
14101        Object obj = mSettings.getUserIdLPr(uid);
14102        if (obj instanceof SharedUserSetting) {
14103            final SharedUserSetting sus = (SharedUserSetting) obj;
14104            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14105            final Iterator<PackageSetting> it = sus.packages.iterator();
14106            while (it.hasNext()) {
14107                final PackageSetting ps = it.next();
14108                if (ps.pkg != null) {
14109                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14110                    if (v < vers) vers = v;
14111                }
14112            }
14113            return vers;
14114        } else if (obj instanceof PackageSetting) {
14115            final PackageSetting ps = (PackageSetting) obj;
14116            if (ps.pkg != null) {
14117                return ps.pkg.applicationInfo.targetSdkVersion;
14118            }
14119        }
14120        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14121    }
14122
14123    @Override
14124    public void addPreferredActivity(IntentFilter filter, int match,
14125            ComponentName[] set, ComponentName activity, int userId) {
14126        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14127                "Adding preferred");
14128    }
14129
14130    private void addPreferredActivityInternal(IntentFilter filter, int match,
14131            ComponentName[] set, ComponentName activity, boolean always, int userId,
14132            String opname) {
14133        // writer
14134        int callingUid = Binder.getCallingUid();
14135        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14136        if (filter.countActions() == 0) {
14137            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14138            return;
14139        }
14140        synchronized (mPackages) {
14141            if (mContext.checkCallingOrSelfPermission(
14142                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14143                    != PackageManager.PERMISSION_GRANTED) {
14144                if (getUidTargetSdkVersionLockedLPr(callingUid)
14145                        < Build.VERSION_CODES.FROYO) {
14146                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14147                            + callingUid);
14148                    return;
14149                }
14150                mContext.enforceCallingOrSelfPermission(
14151                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14152            }
14153
14154            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14155            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14156                    + userId + ":");
14157            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14158            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14159            scheduleWritePackageRestrictionsLocked(userId);
14160        }
14161    }
14162
14163    @Override
14164    public void replacePreferredActivity(IntentFilter filter, int match,
14165            ComponentName[] set, ComponentName activity, int userId) {
14166        if (filter.countActions() != 1) {
14167            throw new IllegalArgumentException(
14168                    "replacePreferredActivity expects filter to have only 1 action.");
14169        }
14170        if (filter.countDataAuthorities() != 0
14171                || filter.countDataPaths() != 0
14172                || filter.countDataSchemes() > 1
14173                || filter.countDataTypes() != 0) {
14174            throw new IllegalArgumentException(
14175                    "replacePreferredActivity expects filter to have no data authorities, " +
14176                    "paths, or types; and at most one scheme.");
14177        }
14178
14179        final int callingUid = Binder.getCallingUid();
14180        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14181        synchronized (mPackages) {
14182            if (mContext.checkCallingOrSelfPermission(
14183                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14184                    != PackageManager.PERMISSION_GRANTED) {
14185                if (getUidTargetSdkVersionLockedLPr(callingUid)
14186                        < Build.VERSION_CODES.FROYO) {
14187                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14188                            + Binder.getCallingUid());
14189                    return;
14190                }
14191                mContext.enforceCallingOrSelfPermission(
14192                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14193            }
14194
14195            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14196            if (pir != null) {
14197                // Get all of the existing entries that exactly match this filter.
14198                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14199                if (existing != null && existing.size() == 1) {
14200                    PreferredActivity cur = existing.get(0);
14201                    if (DEBUG_PREFERRED) {
14202                        Slog.i(TAG, "Checking replace of preferred:");
14203                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14204                        if (!cur.mPref.mAlways) {
14205                            Slog.i(TAG, "  -- CUR; not mAlways!");
14206                        } else {
14207                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14208                            Slog.i(TAG, "  -- CUR: mSet="
14209                                    + Arrays.toString(cur.mPref.mSetComponents));
14210                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14211                            Slog.i(TAG, "  -- NEW: mMatch="
14212                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14213                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14214                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14215                        }
14216                    }
14217                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14218                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14219                            && cur.mPref.sameSet(set)) {
14220                        // Setting the preferred activity to what it happens to be already
14221                        if (DEBUG_PREFERRED) {
14222                            Slog.i(TAG, "Replacing with same preferred activity "
14223                                    + cur.mPref.mShortComponent + " for user "
14224                                    + userId + ":");
14225                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14226                        }
14227                        return;
14228                    }
14229                }
14230
14231                if (existing != null) {
14232                    if (DEBUG_PREFERRED) {
14233                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14234                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14235                    }
14236                    for (int i = 0; i < existing.size(); i++) {
14237                        PreferredActivity pa = existing.get(i);
14238                        if (DEBUG_PREFERRED) {
14239                            Slog.i(TAG, "Removing existing preferred activity "
14240                                    + pa.mPref.mComponent + ":");
14241                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14242                        }
14243                        pir.removeFilter(pa);
14244                    }
14245                }
14246            }
14247            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14248                    "Replacing preferred");
14249        }
14250    }
14251
14252    @Override
14253    public void clearPackagePreferredActivities(String packageName) {
14254        final int uid = Binder.getCallingUid();
14255        // writer
14256        synchronized (mPackages) {
14257            PackageParser.Package pkg = mPackages.get(packageName);
14258            if (pkg == null || pkg.applicationInfo.uid != uid) {
14259                if (mContext.checkCallingOrSelfPermission(
14260                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14261                        != PackageManager.PERMISSION_GRANTED) {
14262                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14263                            < Build.VERSION_CODES.FROYO) {
14264                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14265                                + Binder.getCallingUid());
14266                        return;
14267                    }
14268                    mContext.enforceCallingOrSelfPermission(
14269                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14270                }
14271            }
14272
14273            int user = UserHandle.getCallingUserId();
14274            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14275                scheduleWritePackageRestrictionsLocked(user);
14276            }
14277        }
14278    }
14279
14280    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14281    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14282        ArrayList<PreferredActivity> removed = null;
14283        boolean changed = false;
14284        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14285            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14286            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14287            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14288                continue;
14289            }
14290            Iterator<PreferredActivity> it = pir.filterIterator();
14291            while (it.hasNext()) {
14292                PreferredActivity pa = it.next();
14293                // Mark entry for removal only if it matches the package name
14294                // and the entry is of type "always".
14295                if (packageName == null ||
14296                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14297                                && pa.mPref.mAlways)) {
14298                    if (removed == null) {
14299                        removed = new ArrayList<PreferredActivity>();
14300                    }
14301                    removed.add(pa);
14302                }
14303            }
14304            if (removed != null) {
14305                for (int j=0; j<removed.size(); j++) {
14306                    PreferredActivity pa = removed.get(j);
14307                    pir.removeFilter(pa);
14308                }
14309                changed = true;
14310            }
14311        }
14312        return changed;
14313    }
14314
14315    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14316    private void clearIntentFilterVerificationsLPw(int userId) {
14317        final int packageCount = mPackages.size();
14318        for (int i = 0; i < packageCount; i++) {
14319            PackageParser.Package pkg = mPackages.valueAt(i);
14320            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14321        }
14322    }
14323
14324    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14325    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14326        if (userId == UserHandle.USER_ALL) {
14327            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14328                    sUserManager.getUserIds())) {
14329                for (int oneUserId : sUserManager.getUserIds()) {
14330                    scheduleWritePackageRestrictionsLocked(oneUserId);
14331                }
14332            }
14333        } else {
14334            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14335                scheduleWritePackageRestrictionsLocked(userId);
14336            }
14337        }
14338    }
14339
14340    void clearDefaultBrowserIfNeeded(String packageName) {
14341        for (int oneUserId : sUserManager.getUserIds()) {
14342            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14343            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14344            if (packageName.equals(defaultBrowserPackageName)) {
14345                setDefaultBrowserPackageName(null, oneUserId);
14346            }
14347        }
14348    }
14349
14350    @Override
14351    public void resetApplicationPreferences(int userId) {
14352        mContext.enforceCallingOrSelfPermission(
14353                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14354        // writer
14355        synchronized (mPackages) {
14356            final long identity = Binder.clearCallingIdentity();
14357            try {
14358                clearPackagePreferredActivitiesLPw(null, userId);
14359                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14360                // TODO: We have to reset the default SMS and Phone. This requires
14361                // significant refactoring to keep all default apps in the package
14362                // manager (cleaner but more work) or have the services provide
14363                // callbacks to the package manager to request a default app reset.
14364                applyFactoryDefaultBrowserLPw(userId);
14365                clearIntentFilterVerificationsLPw(userId);
14366                primeDomainVerificationsLPw(userId);
14367                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14368                scheduleWritePackageRestrictionsLocked(userId);
14369            } finally {
14370                Binder.restoreCallingIdentity(identity);
14371            }
14372        }
14373    }
14374
14375    @Override
14376    public int getPreferredActivities(List<IntentFilter> outFilters,
14377            List<ComponentName> outActivities, String packageName) {
14378
14379        int num = 0;
14380        final int userId = UserHandle.getCallingUserId();
14381        // reader
14382        synchronized (mPackages) {
14383            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14384            if (pir != null) {
14385                final Iterator<PreferredActivity> it = pir.filterIterator();
14386                while (it.hasNext()) {
14387                    final PreferredActivity pa = it.next();
14388                    if (packageName == null
14389                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14390                                    && pa.mPref.mAlways)) {
14391                        if (outFilters != null) {
14392                            outFilters.add(new IntentFilter(pa));
14393                        }
14394                        if (outActivities != null) {
14395                            outActivities.add(pa.mPref.mComponent);
14396                        }
14397                    }
14398                }
14399            }
14400        }
14401
14402        return num;
14403    }
14404
14405    @Override
14406    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14407            int userId) {
14408        int callingUid = Binder.getCallingUid();
14409        if (callingUid != Process.SYSTEM_UID) {
14410            throw new SecurityException(
14411                    "addPersistentPreferredActivity can only be run by the system");
14412        }
14413        if (filter.countActions() == 0) {
14414            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14415            return;
14416        }
14417        synchronized (mPackages) {
14418            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14419                    " :");
14420            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14421            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14422                    new PersistentPreferredActivity(filter, activity));
14423            scheduleWritePackageRestrictionsLocked(userId);
14424        }
14425    }
14426
14427    @Override
14428    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14429        int callingUid = Binder.getCallingUid();
14430        if (callingUid != Process.SYSTEM_UID) {
14431            throw new SecurityException(
14432                    "clearPackagePersistentPreferredActivities can only be run by the system");
14433        }
14434        ArrayList<PersistentPreferredActivity> removed = null;
14435        boolean changed = false;
14436        synchronized (mPackages) {
14437            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14438                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14439                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14440                        .valueAt(i);
14441                if (userId != thisUserId) {
14442                    continue;
14443                }
14444                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14445                while (it.hasNext()) {
14446                    PersistentPreferredActivity ppa = it.next();
14447                    // Mark entry for removal only if it matches the package name.
14448                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14449                        if (removed == null) {
14450                            removed = new ArrayList<PersistentPreferredActivity>();
14451                        }
14452                        removed.add(ppa);
14453                    }
14454                }
14455                if (removed != null) {
14456                    for (int j=0; j<removed.size(); j++) {
14457                        PersistentPreferredActivity ppa = removed.get(j);
14458                        ppir.removeFilter(ppa);
14459                    }
14460                    changed = true;
14461                }
14462            }
14463
14464            if (changed) {
14465                scheduleWritePackageRestrictionsLocked(userId);
14466            }
14467        }
14468    }
14469
14470    /**
14471     * Common machinery for picking apart a restored XML blob and passing
14472     * it to a caller-supplied functor to be applied to the running system.
14473     */
14474    private void restoreFromXml(XmlPullParser parser, int userId,
14475            String expectedStartTag, BlobXmlRestorer functor)
14476            throws IOException, XmlPullParserException {
14477        int type;
14478        while ((type = parser.next()) != XmlPullParser.START_TAG
14479                && type != XmlPullParser.END_DOCUMENT) {
14480        }
14481        if (type != XmlPullParser.START_TAG) {
14482            // oops didn't find a start tag?!
14483            if (DEBUG_BACKUP) {
14484                Slog.e(TAG, "Didn't find start tag during restore");
14485            }
14486            return;
14487        }
14488
14489        // this is supposed to be TAG_PREFERRED_BACKUP
14490        if (!expectedStartTag.equals(parser.getName())) {
14491            if (DEBUG_BACKUP) {
14492                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14493            }
14494            return;
14495        }
14496
14497        // skip interfering stuff, then we're aligned with the backing implementation
14498        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14499        functor.apply(parser, userId);
14500    }
14501
14502    private interface BlobXmlRestorer {
14503        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14504    }
14505
14506    /**
14507     * Non-Binder method, support for the backup/restore mechanism: write the
14508     * full set of preferred activities in its canonical XML format.  Returns the
14509     * XML output as a byte array, or null if there is none.
14510     */
14511    @Override
14512    public byte[] getPreferredActivityBackup(int userId) {
14513        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14514            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14515        }
14516
14517        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14518        try {
14519            final XmlSerializer serializer = new FastXmlSerializer();
14520            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14521            serializer.startDocument(null, true);
14522            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14523
14524            synchronized (mPackages) {
14525                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14526            }
14527
14528            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14529            serializer.endDocument();
14530            serializer.flush();
14531        } catch (Exception e) {
14532            if (DEBUG_BACKUP) {
14533                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14534            }
14535            return null;
14536        }
14537
14538        return dataStream.toByteArray();
14539    }
14540
14541    @Override
14542    public void restorePreferredActivities(byte[] backup, int userId) {
14543        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14544            throw new SecurityException("Only the system may call restorePreferredActivities()");
14545        }
14546
14547        try {
14548            final XmlPullParser parser = Xml.newPullParser();
14549            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14550            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14551                    new BlobXmlRestorer() {
14552                        @Override
14553                        public void apply(XmlPullParser parser, int userId)
14554                                throws XmlPullParserException, IOException {
14555                            synchronized (mPackages) {
14556                                mSettings.readPreferredActivitiesLPw(parser, userId);
14557                            }
14558                        }
14559                    } );
14560        } catch (Exception e) {
14561            if (DEBUG_BACKUP) {
14562                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14563            }
14564        }
14565    }
14566
14567    /**
14568     * Non-Binder method, support for the backup/restore mechanism: write the
14569     * default browser (etc) settings in its canonical XML format.  Returns the default
14570     * browser XML representation as a byte array, or null if there is none.
14571     */
14572    @Override
14573    public byte[] getDefaultAppsBackup(int userId) {
14574        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14575            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14576        }
14577
14578        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14579        try {
14580            final XmlSerializer serializer = new FastXmlSerializer();
14581            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14582            serializer.startDocument(null, true);
14583            serializer.startTag(null, TAG_DEFAULT_APPS);
14584
14585            synchronized (mPackages) {
14586                mSettings.writeDefaultAppsLPr(serializer, userId);
14587            }
14588
14589            serializer.endTag(null, TAG_DEFAULT_APPS);
14590            serializer.endDocument();
14591            serializer.flush();
14592        } catch (Exception e) {
14593            if (DEBUG_BACKUP) {
14594                Slog.e(TAG, "Unable to write default apps for backup", e);
14595            }
14596            return null;
14597        }
14598
14599        return dataStream.toByteArray();
14600    }
14601
14602    @Override
14603    public void restoreDefaultApps(byte[] backup, int userId) {
14604        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14605            throw new SecurityException("Only the system may call restoreDefaultApps()");
14606        }
14607
14608        try {
14609            final XmlPullParser parser = Xml.newPullParser();
14610            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14611            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14612                    new BlobXmlRestorer() {
14613                        @Override
14614                        public void apply(XmlPullParser parser, int userId)
14615                                throws XmlPullParserException, IOException {
14616                            synchronized (mPackages) {
14617                                mSettings.readDefaultAppsLPw(parser, userId);
14618                            }
14619                        }
14620                    } );
14621        } catch (Exception e) {
14622            if (DEBUG_BACKUP) {
14623                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14624            }
14625        }
14626    }
14627
14628    @Override
14629    public byte[] getIntentFilterVerificationBackup(int userId) {
14630        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14631            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14632        }
14633
14634        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14635        try {
14636            final XmlSerializer serializer = new FastXmlSerializer();
14637            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14638            serializer.startDocument(null, true);
14639            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14640
14641            synchronized (mPackages) {
14642                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14643            }
14644
14645            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14646            serializer.endDocument();
14647            serializer.flush();
14648        } catch (Exception e) {
14649            if (DEBUG_BACKUP) {
14650                Slog.e(TAG, "Unable to write default apps for backup", e);
14651            }
14652            return null;
14653        }
14654
14655        return dataStream.toByteArray();
14656    }
14657
14658    @Override
14659    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14660        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14661            throw new SecurityException("Only the system may call restorePreferredActivities()");
14662        }
14663
14664        try {
14665            final XmlPullParser parser = Xml.newPullParser();
14666            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14667            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14668                    new BlobXmlRestorer() {
14669                        @Override
14670                        public void apply(XmlPullParser parser, int userId)
14671                                throws XmlPullParserException, IOException {
14672                            synchronized (mPackages) {
14673                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14674                                mSettings.writeLPr();
14675                            }
14676                        }
14677                    } );
14678        } catch (Exception e) {
14679            if (DEBUG_BACKUP) {
14680                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14681            }
14682        }
14683    }
14684
14685    @Override
14686    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14687            int sourceUserId, int targetUserId, int flags) {
14688        mContext.enforceCallingOrSelfPermission(
14689                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14690        int callingUid = Binder.getCallingUid();
14691        enforceOwnerRights(ownerPackage, callingUid);
14692        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14693        if (intentFilter.countActions() == 0) {
14694            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14695            return;
14696        }
14697        synchronized (mPackages) {
14698            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14699                    ownerPackage, targetUserId, flags);
14700            CrossProfileIntentResolver resolver =
14701                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14702            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14703            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14704            if (existing != null) {
14705                int size = existing.size();
14706                for (int i = 0; i < size; i++) {
14707                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14708                        return;
14709                    }
14710                }
14711            }
14712            resolver.addFilter(newFilter);
14713            scheduleWritePackageRestrictionsLocked(sourceUserId);
14714        }
14715    }
14716
14717    @Override
14718    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14719        mContext.enforceCallingOrSelfPermission(
14720                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14721        int callingUid = Binder.getCallingUid();
14722        enforceOwnerRights(ownerPackage, callingUid);
14723        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14724        synchronized (mPackages) {
14725            CrossProfileIntentResolver resolver =
14726                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14727            ArraySet<CrossProfileIntentFilter> set =
14728                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14729            for (CrossProfileIntentFilter filter : set) {
14730                if (filter.getOwnerPackage().equals(ownerPackage)) {
14731                    resolver.removeFilter(filter);
14732                }
14733            }
14734            scheduleWritePackageRestrictionsLocked(sourceUserId);
14735        }
14736    }
14737
14738    // Enforcing that callingUid is owning pkg on userId
14739    private void enforceOwnerRights(String pkg, int callingUid) {
14740        // The system owns everything.
14741        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14742            return;
14743        }
14744        int callingUserId = UserHandle.getUserId(callingUid);
14745        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14746        if (pi == null) {
14747            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14748                    + callingUserId);
14749        }
14750        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14751            throw new SecurityException("Calling uid " + callingUid
14752                    + " does not own package " + pkg);
14753        }
14754    }
14755
14756    @Override
14757    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14758        Intent intent = new Intent(Intent.ACTION_MAIN);
14759        intent.addCategory(Intent.CATEGORY_HOME);
14760
14761        final int callingUserId = UserHandle.getCallingUserId();
14762        List<ResolveInfo> list = queryIntentActivities(intent, null,
14763                PackageManager.GET_META_DATA, callingUserId);
14764        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14765                true, false, false, callingUserId);
14766
14767        allHomeCandidates.clear();
14768        if (list != null) {
14769            for (ResolveInfo ri : list) {
14770                allHomeCandidates.add(ri);
14771            }
14772        }
14773        return (preferred == null || preferred.activityInfo == null)
14774                ? null
14775                : new ComponentName(preferred.activityInfo.packageName,
14776                        preferred.activityInfo.name);
14777    }
14778
14779    @Override
14780    public void setApplicationEnabledSetting(String appPackageName,
14781            int newState, int flags, int userId, String callingPackage) {
14782        if (!sUserManager.exists(userId)) return;
14783        if (callingPackage == null) {
14784            callingPackage = Integer.toString(Binder.getCallingUid());
14785        }
14786        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14787    }
14788
14789    @Override
14790    public void setComponentEnabledSetting(ComponentName componentName,
14791            int newState, int flags, int userId) {
14792        if (!sUserManager.exists(userId)) return;
14793        setEnabledSetting(componentName.getPackageName(),
14794                componentName.getClassName(), newState, flags, userId, null);
14795    }
14796
14797    private void setEnabledSetting(final String packageName, String className, int newState,
14798            final int flags, int userId, String callingPackage) {
14799        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14800              || newState == COMPONENT_ENABLED_STATE_ENABLED
14801              || newState == COMPONENT_ENABLED_STATE_DISABLED
14802              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14803              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14804            throw new IllegalArgumentException("Invalid new component state: "
14805                    + newState);
14806        }
14807        PackageSetting pkgSetting;
14808        final int uid = Binder.getCallingUid();
14809        final int permission = mContext.checkCallingOrSelfPermission(
14810                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14811        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14812        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14813        boolean sendNow = false;
14814        boolean isApp = (className == null);
14815        String componentName = isApp ? packageName : className;
14816        int packageUid = -1;
14817        ArrayList<String> components;
14818
14819        // writer
14820        synchronized (mPackages) {
14821            pkgSetting = mSettings.mPackages.get(packageName);
14822            if (pkgSetting == null) {
14823                if (className == null) {
14824                    throw new IllegalArgumentException(
14825                            "Unknown package: " + packageName);
14826                }
14827                throw new IllegalArgumentException(
14828                        "Unknown component: " + packageName
14829                        + "/" + className);
14830            }
14831            // Allow root and verify that userId is not being specified by a different user
14832            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14833                throw new SecurityException(
14834                        "Permission Denial: attempt to change component state from pid="
14835                        + Binder.getCallingPid()
14836                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14837            }
14838            if (className == null) {
14839                // We're dealing with an application/package level state change
14840                if (pkgSetting.getEnabled(userId) == newState) {
14841                    // Nothing to do
14842                    return;
14843                }
14844                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14845                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14846                    // Don't care about who enables an app.
14847                    callingPackage = null;
14848                }
14849                pkgSetting.setEnabled(newState, userId, callingPackage);
14850                // pkgSetting.pkg.mSetEnabled = newState;
14851            } else {
14852                // We're dealing with a component level state change
14853                // First, verify that this is a valid class name.
14854                PackageParser.Package pkg = pkgSetting.pkg;
14855                if (pkg == null || !pkg.hasComponentClassName(className)) {
14856                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14857                        throw new IllegalArgumentException("Component class " + className
14858                                + " does not exist in " + packageName);
14859                    } else {
14860                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14861                                + className + " does not exist in " + packageName);
14862                    }
14863                }
14864                switch (newState) {
14865                case COMPONENT_ENABLED_STATE_ENABLED:
14866                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14867                        return;
14868                    }
14869                    break;
14870                case COMPONENT_ENABLED_STATE_DISABLED:
14871                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14872                        return;
14873                    }
14874                    break;
14875                case COMPONENT_ENABLED_STATE_DEFAULT:
14876                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14877                        return;
14878                    }
14879                    break;
14880                default:
14881                    Slog.e(TAG, "Invalid new component state: " + newState);
14882                    return;
14883                }
14884            }
14885            scheduleWritePackageRestrictionsLocked(userId);
14886            components = mPendingBroadcasts.get(userId, packageName);
14887            final boolean newPackage = components == null;
14888            if (newPackage) {
14889                components = new ArrayList<String>();
14890            }
14891            if (!components.contains(componentName)) {
14892                components.add(componentName);
14893            }
14894            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14895                sendNow = true;
14896                // Purge entry from pending broadcast list if another one exists already
14897                // since we are sending one right away.
14898                mPendingBroadcasts.remove(userId, packageName);
14899            } else {
14900                if (newPackage) {
14901                    mPendingBroadcasts.put(userId, packageName, components);
14902                }
14903                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14904                    // Schedule a message
14905                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14906                }
14907            }
14908        }
14909
14910        long callingId = Binder.clearCallingIdentity();
14911        try {
14912            if (sendNow) {
14913                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14914                sendPackageChangedBroadcast(packageName,
14915                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14916            }
14917        } finally {
14918            Binder.restoreCallingIdentity(callingId);
14919        }
14920    }
14921
14922    private void sendPackageChangedBroadcast(String packageName,
14923            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14924        if (DEBUG_INSTALL)
14925            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14926                    + componentNames);
14927        Bundle extras = new Bundle(4);
14928        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14929        String nameList[] = new String[componentNames.size()];
14930        componentNames.toArray(nameList);
14931        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14932        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14933        extras.putInt(Intent.EXTRA_UID, packageUid);
14934        // If this is not reporting a change of the overall package, then only send it
14935        // to registered receivers.  We don't want to launch a swath of apps for every
14936        // little component state change.
14937        final int flags = !componentNames.contains(packageName)
14938                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
14939        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
14940                new int[] {UserHandle.getUserId(packageUid)});
14941    }
14942
14943    @Override
14944    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14945        if (!sUserManager.exists(userId)) return;
14946        final int uid = Binder.getCallingUid();
14947        final int permission = mContext.checkCallingOrSelfPermission(
14948                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14949        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14950        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14951        // writer
14952        synchronized (mPackages) {
14953            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14954                    allowedByPermission, uid, userId)) {
14955                scheduleWritePackageRestrictionsLocked(userId);
14956            }
14957        }
14958    }
14959
14960    @Override
14961    public String getInstallerPackageName(String packageName) {
14962        // reader
14963        synchronized (mPackages) {
14964            return mSettings.getInstallerPackageNameLPr(packageName);
14965        }
14966    }
14967
14968    @Override
14969    public int getApplicationEnabledSetting(String packageName, int userId) {
14970        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14971        int uid = Binder.getCallingUid();
14972        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14973        // reader
14974        synchronized (mPackages) {
14975            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14976        }
14977    }
14978
14979    @Override
14980    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14981        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14982        int uid = Binder.getCallingUid();
14983        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14984        // reader
14985        synchronized (mPackages) {
14986            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14987        }
14988    }
14989
14990    @Override
14991    public void enterSafeMode() {
14992        enforceSystemOrRoot("Only the system can request entering safe mode");
14993
14994        if (!mSystemReady) {
14995            mSafeMode = true;
14996        }
14997    }
14998
14999    @Override
15000    public void systemReady() {
15001        mSystemReady = true;
15002
15003        // Read the compatibilty setting when the system is ready.
15004        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15005                mContext.getContentResolver(),
15006                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15007        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15008        if (DEBUG_SETTINGS) {
15009            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15010        }
15011
15012        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15013
15014        synchronized (mPackages) {
15015            // Verify that all of the preferred activity components actually
15016            // exist.  It is possible for applications to be updated and at
15017            // that point remove a previously declared activity component that
15018            // had been set as a preferred activity.  We try to clean this up
15019            // the next time we encounter that preferred activity, but it is
15020            // possible for the user flow to never be able to return to that
15021            // situation so here we do a sanity check to make sure we haven't
15022            // left any junk around.
15023            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15024            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15025                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15026                removed.clear();
15027                for (PreferredActivity pa : pir.filterSet()) {
15028                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15029                        removed.add(pa);
15030                    }
15031                }
15032                if (removed.size() > 0) {
15033                    for (int r=0; r<removed.size(); r++) {
15034                        PreferredActivity pa = removed.get(r);
15035                        Slog.w(TAG, "Removing dangling preferred activity: "
15036                                + pa.mPref.mComponent);
15037                        pir.removeFilter(pa);
15038                    }
15039                    mSettings.writePackageRestrictionsLPr(
15040                            mSettings.mPreferredActivities.keyAt(i));
15041                }
15042            }
15043
15044            for (int userId : UserManagerService.getInstance().getUserIds()) {
15045                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15046                    grantPermissionsUserIds = ArrayUtils.appendInt(
15047                            grantPermissionsUserIds, userId);
15048                }
15049            }
15050        }
15051        sUserManager.systemReady();
15052
15053        // If we upgraded grant all default permissions before kicking off.
15054        for (int userId : grantPermissionsUserIds) {
15055            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15056        }
15057
15058        // Kick off any messages waiting for system ready
15059        if (mPostSystemReadyMessages != null) {
15060            for (Message msg : mPostSystemReadyMessages) {
15061                msg.sendToTarget();
15062            }
15063            mPostSystemReadyMessages = null;
15064        }
15065
15066        // Watch for external volumes that come and go over time
15067        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15068        storage.registerListener(mStorageListener);
15069
15070        mInstallerService.systemReady();
15071        mPackageDexOptimizer.systemReady();
15072
15073        MountServiceInternal mountServiceInternal = LocalServices.getService(
15074                MountServiceInternal.class);
15075        mountServiceInternal.addExternalStoragePolicy(
15076                new MountServiceInternal.ExternalStorageMountPolicy() {
15077            @Override
15078            public int getMountMode(int uid, String packageName) {
15079                if (Process.isIsolated(uid)) {
15080                    return Zygote.MOUNT_EXTERNAL_NONE;
15081                }
15082                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15083                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15084                }
15085                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15086                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15087                }
15088                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15089                    return Zygote.MOUNT_EXTERNAL_READ;
15090                }
15091                return Zygote.MOUNT_EXTERNAL_WRITE;
15092            }
15093
15094            @Override
15095            public boolean hasExternalStorage(int uid, String packageName) {
15096                return true;
15097            }
15098        });
15099    }
15100
15101    @Override
15102    public boolean isSafeMode() {
15103        return mSafeMode;
15104    }
15105
15106    @Override
15107    public boolean hasSystemUidErrors() {
15108        return mHasSystemUidErrors;
15109    }
15110
15111    static String arrayToString(int[] array) {
15112        StringBuffer buf = new StringBuffer(128);
15113        buf.append('[');
15114        if (array != null) {
15115            for (int i=0; i<array.length; i++) {
15116                if (i > 0) buf.append(", ");
15117                buf.append(array[i]);
15118            }
15119        }
15120        buf.append(']');
15121        return buf.toString();
15122    }
15123
15124    static class DumpState {
15125        public static final int DUMP_LIBS = 1 << 0;
15126        public static final int DUMP_FEATURES = 1 << 1;
15127        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15128        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15129        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15130        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15131        public static final int DUMP_PERMISSIONS = 1 << 6;
15132        public static final int DUMP_PACKAGES = 1 << 7;
15133        public static final int DUMP_SHARED_USERS = 1 << 8;
15134        public static final int DUMP_MESSAGES = 1 << 9;
15135        public static final int DUMP_PROVIDERS = 1 << 10;
15136        public static final int DUMP_VERIFIERS = 1 << 11;
15137        public static final int DUMP_PREFERRED = 1 << 12;
15138        public static final int DUMP_PREFERRED_XML = 1 << 13;
15139        public static final int DUMP_KEYSETS = 1 << 14;
15140        public static final int DUMP_VERSION = 1 << 15;
15141        public static final int DUMP_INSTALLS = 1 << 16;
15142        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15143        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15144
15145        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15146
15147        private int mTypes;
15148
15149        private int mOptions;
15150
15151        private boolean mTitlePrinted;
15152
15153        private SharedUserSetting mSharedUser;
15154
15155        public boolean isDumping(int type) {
15156            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15157                return true;
15158            }
15159
15160            return (mTypes & type) != 0;
15161        }
15162
15163        public void setDump(int type) {
15164            mTypes |= type;
15165        }
15166
15167        public boolean isOptionEnabled(int option) {
15168            return (mOptions & option) != 0;
15169        }
15170
15171        public void setOptionEnabled(int option) {
15172            mOptions |= option;
15173        }
15174
15175        public boolean onTitlePrinted() {
15176            final boolean printed = mTitlePrinted;
15177            mTitlePrinted = true;
15178            return printed;
15179        }
15180
15181        public boolean getTitlePrinted() {
15182            return mTitlePrinted;
15183        }
15184
15185        public void setTitlePrinted(boolean enabled) {
15186            mTitlePrinted = enabled;
15187        }
15188
15189        public SharedUserSetting getSharedUser() {
15190            return mSharedUser;
15191        }
15192
15193        public void setSharedUser(SharedUserSetting user) {
15194            mSharedUser = user;
15195        }
15196    }
15197
15198    @Override
15199    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15200            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15201        (new PackageManagerShellCommand(this)).exec(
15202                this, in, out, err, args, resultReceiver);
15203    }
15204
15205    @Override
15206    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15207        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15208                != PackageManager.PERMISSION_GRANTED) {
15209            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15210                    + Binder.getCallingPid()
15211                    + ", uid=" + Binder.getCallingUid()
15212                    + " without permission "
15213                    + android.Manifest.permission.DUMP);
15214            return;
15215        }
15216
15217        DumpState dumpState = new DumpState();
15218        boolean fullPreferred = false;
15219        boolean checkin = false;
15220
15221        String packageName = null;
15222        ArraySet<String> permissionNames = null;
15223
15224        int opti = 0;
15225        while (opti < args.length) {
15226            String opt = args[opti];
15227            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15228                break;
15229            }
15230            opti++;
15231
15232            if ("-a".equals(opt)) {
15233                // Right now we only know how to print all.
15234            } else if ("-h".equals(opt)) {
15235                pw.println("Package manager dump options:");
15236                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15237                pw.println("    --checkin: dump for a checkin");
15238                pw.println("    -f: print details of intent filters");
15239                pw.println("    -h: print this help");
15240                pw.println("  cmd may be one of:");
15241                pw.println("    l[ibraries]: list known shared libraries");
15242                pw.println("    f[eatures]: list device features");
15243                pw.println("    k[eysets]: print known keysets");
15244                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15245                pw.println("    perm[issions]: dump permissions");
15246                pw.println("    permission [name ...]: dump declaration and use of given permission");
15247                pw.println("    pref[erred]: print preferred package settings");
15248                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15249                pw.println("    prov[iders]: dump content providers");
15250                pw.println("    p[ackages]: dump installed packages");
15251                pw.println("    s[hared-users]: dump shared user IDs");
15252                pw.println("    m[essages]: print collected runtime messages");
15253                pw.println("    v[erifiers]: print package verifier info");
15254                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15255                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15256                pw.println("    version: print database version info");
15257                pw.println("    write: write current settings now");
15258                pw.println("    installs: details about install sessions");
15259                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15260                pw.println("    <package.name>: info about given package");
15261                return;
15262            } else if ("--checkin".equals(opt)) {
15263                checkin = true;
15264            } else if ("-f".equals(opt)) {
15265                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15266            } else {
15267                pw.println("Unknown argument: " + opt + "; use -h for help");
15268            }
15269        }
15270
15271        // Is the caller requesting to dump a particular piece of data?
15272        if (opti < args.length) {
15273            String cmd = args[opti];
15274            opti++;
15275            // Is this a package name?
15276            if ("android".equals(cmd) || cmd.contains(".")) {
15277                packageName = cmd;
15278                // When dumping a single package, we always dump all of its
15279                // filter information since the amount of data will be reasonable.
15280                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15281            } else if ("check-permission".equals(cmd)) {
15282                if (opti >= args.length) {
15283                    pw.println("Error: check-permission missing permission argument");
15284                    return;
15285                }
15286                String perm = args[opti];
15287                opti++;
15288                if (opti >= args.length) {
15289                    pw.println("Error: check-permission missing package argument");
15290                    return;
15291                }
15292                String pkg = args[opti];
15293                opti++;
15294                int user = UserHandle.getUserId(Binder.getCallingUid());
15295                if (opti < args.length) {
15296                    try {
15297                        user = Integer.parseInt(args[opti]);
15298                    } catch (NumberFormatException e) {
15299                        pw.println("Error: check-permission user argument is not a number: "
15300                                + args[opti]);
15301                        return;
15302                    }
15303                }
15304                pw.println(checkPermission(perm, pkg, user));
15305                return;
15306            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15307                dumpState.setDump(DumpState.DUMP_LIBS);
15308            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15309                dumpState.setDump(DumpState.DUMP_FEATURES);
15310            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15311                if (opti >= args.length) {
15312                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15313                            | DumpState.DUMP_SERVICE_RESOLVERS
15314                            | DumpState.DUMP_RECEIVER_RESOLVERS
15315                            | DumpState.DUMP_CONTENT_RESOLVERS);
15316                } else {
15317                    while (opti < args.length) {
15318                        String name = args[opti];
15319                        if ("a".equals(name) || "activity".equals(name)) {
15320                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15321                        } else if ("s".equals(name) || "service".equals(name)) {
15322                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15323                        } else if ("r".equals(name) || "receiver".equals(name)) {
15324                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15325                        } else if ("c".equals(name) || "content".equals(name)) {
15326                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15327                        } else {
15328                            pw.println("Error: unknown resolver table type: " + name);
15329                            return;
15330                        }
15331                        opti++;
15332                    }
15333                }
15334            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15335                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15336            } else if ("permission".equals(cmd)) {
15337                if (opti >= args.length) {
15338                    pw.println("Error: permission requires permission name");
15339                    return;
15340                }
15341                permissionNames = new ArraySet<>();
15342                while (opti < args.length) {
15343                    permissionNames.add(args[opti]);
15344                    opti++;
15345                }
15346                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15347                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15348            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15349                dumpState.setDump(DumpState.DUMP_PREFERRED);
15350            } else if ("preferred-xml".equals(cmd)) {
15351                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15352                if (opti < args.length && "--full".equals(args[opti])) {
15353                    fullPreferred = true;
15354                    opti++;
15355                }
15356            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15357                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15358            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15359                dumpState.setDump(DumpState.DUMP_PACKAGES);
15360            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15361                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15362            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15363                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15364            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15365                dumpState.setDump(DumpState.DUMP_MESSAGES);
15366            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15367                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15368            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15369                    || "intent-filter-verifiers".equals(cmd)) {
15370                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15371            } else if ("version".equals(cmd)) {
15372                dumpState.setDump(DumpState.DUMP_VERSION);
15373            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15374                dumpState.setDump(DumpState.DUMP_KEYSETS);
15375            } else if ("installs".equals(cmd)) {
15376                dumpState.setDump(DumpState.DUMP_INSTALLS);
15377            } else if ("write".equals(cmd)) {
15378                synchronized (mPackages) {
15379                    mSettings.writeLPr();
15380                    pw.println("Settings written.");
15381                    return;
15382                }
15383            }
15384        }
15385
15386        if (checkin) {
15387            pw.println("vers,1");
15388        }
15389
15390        // reader
15391        synchronized (mPackages) {
15392            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15393                if (!checkin) {
15394                    if (dumpState.onTitlePrinted())
15395                        pw.println();
15396                    pw.println("Database versions:");
15397                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15398                }
15399            }
15400
15401            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15402                if (!checkin) {
15403                    if (dumpState.onTitlePrinted())
15404                        pw.println();
15405                    pw.println("Verifiers:");
15406                    pw.print("  Required: ");
15407                    pw.print(mRequiredVerifierPackage);
15408                    pw.print(" (uid=");
15409                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15410                    pw.println(")");
15411                } else if (mRequiredVerifierPackage != null) {
15412                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15413                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15414                }
15415            }
15416
15417            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15418                    packageName == null) {
15419                if (mIntentFilterVerifierComponent != null) {
15420                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15421                    if (!checkin) {
15422                        if (dumpState.onTitlePrinted())
15423                            pw.println();
15424                        pw.println("Intent Filter Verifier:");
15425                        pw.print("  Using: ");
15426                        pw.print(verifierPackageName);
15427                        pw.print(" (uid=");
15428                        pw.print(getPackageUid(verifierPackageName, 0));
15429                        pw.println(")");
15430                    } else if (verifierPackageName != null) {
15431                        pw.print("ifv,"); pw.print(verifierPackageName);
15432                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15433                    }
15434                } else {
15435                    pw.println();
15436                    pw.println("No Intent Filter Verifier available!");
15437                }
15438            }
15439
15440            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15441                boolean printedHeader = false;
15442                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15443                while (it.hasNext()) {
15444                    String name = it.next();
15445                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15446                    if (!checkin) {
15447                        if (!printedHeader) {
15448                            if (dumpState.onTitlePrinted())
15449                                pw.println();
15450                            pw.println("Libraries:");
15451                            printedHeader = true;
15452                        }
15453                        pw.print("  ");
15454                    } else {
15455                        pw.print("lib,");
15456                    }
15457                    pw.print(name);
15458                    if (!checkin) {
15459                        pw.print(" -> ");
15460                    }
15461                    if (ent.path != null) {
15462                        if (!checkin) {
15463                            pw.print("(jar) ");
15464                            pw.print(ent.path);
15465                        } else {
15466                            pw.print(",jar,");
15467                            pw.print(ent.path);
15468                        }
15469                    } else {
15470                        if (!checkin) {
15471                            pw.print("(apk) ");
15472                            pw.print(ent.apk);
15473                        } else {
15474                            pw.print(",apk,");
15475                            pw.print(ent.apk);
15476                        }
15477                    }
15478                    pw.println();
15479                }
15480            }
15481
15482            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15483                if (dumpState.onTitlePrinted())
15484                    pw.println();
15485                if (!checkin) {
15486                    pw.println("Features:");
15487                }
15488                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15489                while (it.hasNext()) {
15490                    String name = it.next();
15491                    if (!checkin) {
15492                        pw.print("  ");
15493                    } else {
15494                        pw.print("feat,");
15495                    }
15496                    pw.println(name);
15497                }
15498            }
15499
15500            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15501                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15502                        : "Activity Resolver Table:", "  ", packageName,
15503                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15504                    dumpState.setTitlePrinted(true);
15505                }
15506            }
15507            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15508                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15509                        : "Receiver Resolver Table:", "  ", packageName,
15510                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15511                    dumpState.setTitlePrinted(true);
15512                }
15513            }
15514            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15515                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15516                        : "Service Resolver Table:", "  ", packageName,
15517                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15518                    dumpState.setTitlePrinted(true);
15519                }
15520            }
15521            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15522                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15523                        : "Provider Resolver Table:", "  ", packageName,
15524                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15525                    dumpState.setTitlePrinted(true);
15526                }
15527            }
15528
15529            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15530                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15531                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15532                    int user = mSettings.mPreferredActivities.keyAt(i);
15533                    if (pir.dump(pw,
15534                            dumpState.getTitlePrinted()
15535                                ? "\nPreferred Activities User " + user + ":"
15536                                : "Preferred Activities User " + user + ":", "  ",
15537                            packageName, true, false)) {
15538                        dumpState.setTitlePrinted(true);
15539                    }
15540                }
15541            }
15542
15543            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15544                pw.flush();
15545                FileOutputStream fout = new FileOutputStream(fd);
15546                BufferedOutputStream str = new BufferedOutputStream(fout);
15547                XmlSerializer serializer = new FastXmlSerializer();
15548                try {
15549                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15550                    serializer.startDocument(null, true);
15551                    serializer.setFeature(
15552                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15553                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15554                    serializer.endDocument();
15555                    serializer.flush();
15556                } catch (IllegalArgumentException e) {
15557                    pw.println("Failed writing: " + e);
15558                } catch (IllegalStateException e) {
15559                    pw.println("Failed writing: " + e);
15560                } catch (IOException e) {
15561                    pw.println("Failed writing: " + e);
15562                }
15563            }
15564
15565            if (!checkin
15566                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15567                    && packageName == null) {
15568                pw.println();
15569                int count = mSettings.mPackages.size();
15570                if (count == 0) {
15571                    pw.println("No applications!");
15572                    pw.println();
15573                } else {
15574                    final String prefix = "  ";
15575                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15576                    if (allPackageSettings.size() == 0) {
15577                        pw.println("No domain preferred apps!");
15578                        pw.println();
15579                    } else {
15580                        pw.println("App verification status:");
15581                        pw.println();
15582                        count = 0;
15583                        for (PackageSetting ps : allPackageSettings) {
15584                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15585                            if (ivi == null || ivi.getPackageName() == null) continue;
15586                            pw.println(prefix + "Package: " + ivi.getPackageName());
15587                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15588                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15589                            pw.println();
15590                            count++;
15591                        }
15592                        if (count == 0) {
15593                            pw.println(prefix + "No app verification established.");
15594                            pw.println();
15595                        }
15596                        for (int userId : sUserManager.getUserIds()) {
15597                            pw.println("App linkages for user " + userId + ":");
15598                            pw.println();
15599                            count = 0;
15600                            for (PackageSetting ps : allPackageSettings) {
15601                                final long status = ps.getDomainVerificationStatusForUser(userId);
15602                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15603                                    continue;
15604                                }
15605                                pw.println(prefix + "Package: " + ps.name);
15606                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15607                                String statusStr = IntentFilterVerificationInfo.
15608                                        getStatusStringFromValue(status);
15609                                pw.println(prefix + "Status:  " + statusStr);
15610                                pw.println();
15611                                count++;
15612                            }
15613                            if (count == 0) {
15614                                pw.println(prefix + "No configured app linkages.");
15615                                pw.println();
15616                            }
15617                        }
15618                    }
15619                }
15620            }
15621
15622            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15623                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15624                if (packageName == null && permissionNames == null) {
15625                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15626                        if (iperm == 0) {
15627                            if (dumpState.onTitlePrinted())
15628                                pw.println();
15629                            pw.println("AppOp Permissions:");
15630                        }
15631                        pw.print("  AppOp Permission ");
15632                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15633                        pw.println(":");
15634                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15635                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15636                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15637                        }
15638                    }
15639                }
15640            }
15641
15642            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15643                boolean printedSomething = false;
15644                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15645                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15646                        continue;
15647                    }
15648                    if (!printedSomething) {
15649                        if (dumpState.onTitlePrinted())
15650                            pw.println();
15651                        pw.println("Registered ContentProviders:");
15652                        printedSomething = true;
15653                    }
15654                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15655                    pw.print("    "); pw.println(p.toString());
15656                }
15657                printedSomething = false;
15658                for (Map.Entry<String, PackageParser.Provider> entry :
15659                        mProvidersByAuthority.entrySet()) {
15660                    PackageParser.Provider p = entry.getValue();
15661                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15662                        continue;
15663                    }
15664                    if (!printedSomething) {
15665                        if (dumpState.onTitlePrinted())
15666                            pw.println();
15667                        pw.println("ContentProvider Authorities:");
15668                        printedSomething = true;
15669                    }
15670                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15671                    pw.print("    "); pw.println(p.toString());
15672                    if (p.info != null && p.info.applicationInfo != null) {
15673                        final String appInfo = p.info.applicationInfo.toString();
15674                        pw.print("      applicationInfo="); pw.println(appInfo);
15675                    }
15676                }
15677            }
15678
15679            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15680                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15681            }
15682
15683            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15684                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15685            }
15686
15687            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15688                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15689            }
15690
15691            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15692                // XXX should handle packageName != null by dumping only install data that
15693                // the given package is involved with.
15694                if (dumpState.onTitlePrinted()) pw.println();
15695                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15696            }
15697
15698            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15699                if (dumpState.onTitlePrinted()) pw.println();
15700                mSettings.dumpReadMessagesLPr(pw, dumpState);
15701
15702                pw.println();
15703                pw.println("Package warning messages:");
15704                BufferedReader in = null;
15705                String line = null;
15706                try {
15707                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15708                    while ((line = in.readLine()) != null) {
15709                        if (line.contains("ignored: updated version")) continue;
15710                        pw.println(line);
15711                    }
15712                } catch (IOException ignored) {
15713                } finally {
15714                    IoUtils.closeQuietly(in);
15715                }
15716            }
15717
15718            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15719                BufferedReader in = null;
15720                String line = null;
15721                try {
15722                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15723                    while ((line = in.readLine()) != null) {
15724                        if (line.contains("ignored: updated version")) continue;
15725                        pw.print("msg,");
15726                        pw.println(line);
15727                    }
15728                } catch (IOException ignored) {
15729                } finally {
15730                    IoUtils.closeQuietly(in);
15731                }
15732            }
15733        }
15734    }
15735
15736    private String dumpDomainString(String packageName) {
15737        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15738        List<IntentFilter> filters = getAllIntentFilters(packageName);
15739
15740        ArraySet<String> result = new ArraySet<>();
15741        if (iviList.size() > 0) {
15742            for (IntentFilterVerificationInfo ivi : iviList) {
15743                for (String host : ivi.getDomains()) {
15744                    result.add(host);
15745                }
15746            }
15747        }
15748        if (filters != null && filters.size() > 0) {
15749            for (IntentFilter filter : filters) {
15750                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15751                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15752                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15753                    result.addAll(filter.getHostsList());
15754                }
15755            }
15756        }
15757
15758        StringBuilder sb = new StringBuilder(result.size() * 16);
15759        for (String domain : result) {
15760            if (sb.length() > 0) sb.append(" ");
15761            sb.append(domain);
15762        }
15763        return sb.toString();
15764    }
15765
15766    // ------- apps on sdcard specific code -------
15767    static final boolean DEBUG_SD_INSTALL = false;
15768
15769    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15770
15771    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15772
15773    private boolean mMediaMounted = false;
15774
15775    static String getEncryptKey() {
15776        try {
15777            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15778                    SD_ENCRYPTION_KEYSTORE_NAME);
15779            if (sdEncKey == null) {
15780                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15781                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15782                if (sdEncKey == null) {
15783                    Slog.e(TAG, "Failed to create encryption keys");
15784                    return null;
15785                }
15786            }
15787            return sdEncKey;
15788        } catch (NoSuchAlgorithmException nsae) {
15789            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15790            return null;
15791        } catch (IOException ioe) {
15792            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15793            return null;
15794        }
15795    }
15796
15797    /*
15798     * Update media status on PackageManager.
15799     */
15800    @Override
15801    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15802        int callingUid = Binder.getCallingUid();
15803        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15804            throw new SecurityException("Media status can only be updated by the system");
15805        }
15806        // reader; this apparently protects mMediaMounted, but should probably
15807        // be a different lock in that case.
15808        synchronized (mPackages) {
15809            Log.i(TAG, "Updating external media status from "
15810                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15811                    + (mediaStatus ? "mounted" : "unmounted"));
15812            if (DEBUG_SD_INSTALL)
15813                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15814                        + ", mMediaMounted=" + mMediaMounted);
15815            if (mediaStatus == mMediaMounted) {
15816                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15817                        : 0, -1);
15818                mHandler.sendMessage(msg);
15819                return;
15820            }
15821            mMediaMounted = mediaStatus;
15822        }
15823        // Queue up an async operation since the package installation may take a
15824        // little while.
15825        mHandler.post(new Runnable() {
15826            public void run() {
15827                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15828            }
15829        });
15830    }
15831
15832    /**
15833     * Called by MountService when the initial ASECs to scan are available.
15834     * Should block until all the ASEC containers are finished being scanned.
15835     */
15836    public void scanAvailableAsecs() {
15837        updateExternalMediaStatusInner(true, false, false);
15838        if (mShouldRestoreconData) {
15839            SELinuxMMAC.setRestoreconDone();
15840            mShouldRestoreconData = false;
15841        }
15842    }
15843
15844    /*
15845     * Collect information of applications on external media, map them against
15846     * existing containers and update information based on current mount status.
15847     * Please note that we always have to report status if reportStatus has been
15848     * set to true especially when unloading packages.
15849     */
15850    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15851            boolean externalStorage) {
15852        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15853        int[] uidArr = EmptyArray.INT;
15854
15855        final String[] list = PackageHelper.getSecureContainerList();
15856        if (ArrayUtils.isEmpty(list)) {
15857            Log.i(TAG, "No secure containers found");
15858        } else {
15859            // Process list of secure containers and categorize them
15860            // as active or stale based on their package internal state.
15861
15862            // reader
15863            synchronized (mPackages) {
15864                for (String cid : list) {
15865                    // Leave stages untouched for now; installer service owns them
15866                    if (PackageInstallerService.isStageName(cid)) continue;
15867
15868                    if (DEBUG_SD_INSTALL)
15869                        Log.i(TAG, "Processing container " + cid);
15870                    String pkgName = getAsecPackageName(cid);
15871                    if (pkgName == null) {
15872                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15873                        continue;
15874                    }
15875                    if (DEBUG_SD_INSTALL)
15876                        Log.i(TAG, "Looking for pkg : " + pkgName);
15877
15878                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15879                    if (ps == null) {
15880                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15881                        continue;
15882                    }
15883
15884                    /*
15885                     * Skip packages that are not external if we're unmounting
15886                     * external storage.
15887                     */
15888                    if (externalStorage && !isMounted && !isExternal(ps)) {
15889                        continue;
15890                    }
15891
15892                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15893                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15894                    // The package status is changed only if the code path
15895                    // matches between settings and the container id.
15896                    if (ps.codePathString != null
15897                            && ps.codePathString.startsWith(args.getCodePath())) {
15898                        if (DEBUG_SD_INSTALL) {
15899                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15900                                    + " at code path: " + ps.codePathString);
15901                        }
15902
15903                        // We do have a valid package installed on sdcard
15904                        processCids.put(args, ps.codePathString);
15905                        final int uid = ps.appId;
15906                        if (uid != -1) {
15907                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15908                        }
15909                    } else {
15910                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15911                                + ps.codePathString);
15912                    }
15913                }
15914            }
15915
15916            Arrays.sort(uidArr);
15917        }
15918
15919        // Process packages with valid entries.
15920        if (isMounted) {
15921            if (DEBUG_SD_INSTALL)
15922                Log.i(TAG, "Loading packages");
15923            loadMediaPackages(processCids, uidArr, externalStorage);
15924            startCleaningPackages();
15925            mInstallerService.onSecureContainersAvailable();
15926        } else {
15927            if (DEBUG_SD_INSTALL)
15928                Log.i(TAG, "Unloading packages");
15929            unloadMediaPackages(processCids, uidArr, reportStatus);
15930        }
15931    }
15932
15933    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15934            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15935        final int size = infos.size();
15936        final String[] packageNames = new String[size];
15937        final int[] packageUids = new int[size];
15938        for (int i = 0; i < size; i++) {
15939            final ApplicationInfo info = infos.get(i);
15940            packageNames[i] = info.packageName;
15941            packageUids[i] = info.uid;
15942        }
15943        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15944                finishedReceiver);
15945    }
15946
15947    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15948            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15949        sendResourcesChangedBroadcast(mediaStatus, replacing,
15950                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15951    }
15952
15953    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15954            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15955        int size = pkgList.length;
15956        if (size > 0) {
15957            // Send broadcasts here
15958            Bundle extras = new Bundle();
15959            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15960            if (uidArr != null) {
15961                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15962            }
15963            if (replacing) {
15964                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15965            }
15966            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15967                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15968            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
15969        }
15970    }
15971
15972   /*
15973     * Look at potentially valid container ids from processCids If package
15974     * information doesn't match the one on record or package scanning fails,
15975     * the cid is added to list of removeCids. We currently don't delete stale
15976     * containers.
15977     */
15978    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15979            boolean externalStorage) {
15980        ArrayList<String> pkgList = new ArrayList<String>();
15981        Set<AsecInstallArgs> keys = processCids.keySet();
15982
15983        for (AsecInstallArgs args : keys) {
15984            String codePath = processCids.get(args);
15985            if (DEBUG_SD_INSTALL)
15986                Log.i(TAG, "Loading container : " + args.cid);
15987            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15988            try {
15989                // Make sure there are no container errors first.
15990                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15991                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15992                            + " when installing from sdcard");
15993                    continue;
15994                }
15995                // Check code path here.
15996                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15997                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15998                            + " does not match one in settings " + codePath);
15999                    continue;
16000                }
16001                // Parse package
16002                int parseFlags = mDefParseFlags;
16003                if (args.isExternalAsec()) {
16004                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16005                }
16006                if (args.isFwdLocked()) {
16007                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16008                }
16009
16010                synchronized (mInstallLock) {
16011                    PackageParser.Package pkg = null;
16012                    try {
16013                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16014                    } catch (PackageManagerException e) {
16015                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16016                    }
16017                    // Scan the package
16018                    if (pkg != null) {
16019                        /*
16020                         * TODO why is the lock being held? doPostInstall is
16021                         * called in other places without the lock. This needs
16022                         * to be straightened out.
16023                         */
16024                        // writer
16025                        synchronized (mPackages) {
16026                            retCode = PackageManager.INSTALL_SUCCEEDED;
16027                            pkgList.add(pkg.packageName);
16028                            // Post process args
16029                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16030                                    pkg.applicationInfo.uid);
16031                        }
16032                    } else {
16033                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16034                    }
16035                }
16036
16037            } finally {
16038                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16039                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16040                }
16041            }
16042        }
16043        // writer
16044        synchronized (mPackages) {
16045            // If the platform SDK has changed since the last time we booted,
16046            // we need to re-grant app permission to catch any new ones that
16047            // appear. This is really a hack, and means that apps can in some
16048            // cases get permissions that the user didn't initially explicitly
16049            // allow... it would be nice to have some better way to handle
16050            // this situation.
16051            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16052                    : mSettings.getInternalVersion();
16053            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16054                    : StorageManager.UUID_PRIVATE_INTERNAL;
16055
16056            int updateFlags = UPDATE_PERMISSIONS_ALL;
16057            if (ver.sdkVersion != mSdkVersion) {
16058                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16059                        + mSdkVersion + "; regranting permissions for external");
16060                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16061            }
16062            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16063
16064            // Yay, everything is now upgraded
16065            ver.forceCurrent();
16066
16067            // can downgrade to reader
16068            // Persist settings
16069            mSettings.writeLPr();
16070        }
16071        // Send a broadcast to let everyone know we are done processing
16072        if (pkgList.size() > 0) {
16073            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16074        }
16075    }
16076
16077   /*
16078     * Utility method to unload a list of specified containers
16079     */
16080    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16081        // Just unmount all valid containers.
16082        for (AsecInstallArgs arg : cidArgs) {
16083            synchronized (mInstallLock) {
16084                arg.doPostDeleteLI(false);
16085           }
16086       }
16087   }
16088
16089    /*
16090     * Unload packages mounted on external media. This involves deleting package
16091     * data from internal structures, sending broadcasts about diabled packages,
16092     * gc'ing to free up references, unmounting all secure containers
16093     * corresponding to packages on external media, and posting a
16094     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16095     * that we always have to post this message if status has been requested no
16096     * matter what.
16097     */
16098    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16099            final boolean reportStatus) {
16100        if (DEBUG_SD_INSTALL)
16101            Log.i(TAG, "unloading media packages");
16102        ArrayList<String> pkgList = new ArrayList<String>();
16103        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16104        final Set<AsecInstallArgs> keys = processCids.keySet();
16105        for (AsecInstallArgs args : keys) {
16106            String pkgName = args.getPackageName();
16107            if (DEBUG_SD_INSTALL)
16108                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16109            // Delete package internally
16110            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16111            synchronized (mInstallLock) {
16112                boolean res = deletePackageLI(pkgName, null, false, null, null,
16113                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16114                if (res) {
16115                    pkgList.add(pkgName);
16116                } else {
16117                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16118                    failedList.add(args);
16119                }
16120            }
16121        }
16122
16123        // reader
16124        synchronized (mPackages) {
16125            // We didn't update the settings after removing each package;
16126            // write them now for all packages.
16127            mSettings.writeLPr();
16128        }
16129
16130        // We have to absolutely send UPDATED_MEDIA_STATUS only
16131        // after confirming that all the receivers processed the ordered
16132        // broadcast when packages get disabled, force a gc to clean things up.
16133        // and unload all the containers.
16134        if (pkgList.size() > 0) {
16135            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16136                    new IIntentReceiver.Stub() {
16137                public void performReceive(Intent intent, int resultCode, String data,
16138                        Bundle extras, boolean ordered, boolean sticky,
16139                        int sendingUser) throws RemoteException {
16140                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16141                            reportStatus ? 1 : 0, 1, keys);
16142                    mHandler.sendMessage(msg);
16143                }
16144            });
16145        } else {
16146            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16147                    keys);
16148            mHandler.sendMessage(msg);
16149        }
16150    }
16151
16152    private void loadPrivatePackages(final VolumeInfo vol) {
16153        mHandler.post(new Runnable() {
16154            @Override
16155            public void run() {
16156                loadPrivatePackagesInner(vol);
16157            }
16158        });
16159    }
16160
16161    private void loadPrivatePackagesInner(VolumeInfo vol) {
16162        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16163        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16164
16165        final VersionInfo ver;
16166        final List<PackageSetting> packages;
16167        synchronized (mPackages) {
16168            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16169            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16170        }
16171
16172        for (PackageSetting ps : packages) {
16173            synchronized (mInstallLock) {
16174                final PackageParser.Package pkg;
16175                try {
16176                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16177                    loaded.add(pkg.applicationInfo);
16178                } catch (PackageManagerException e) {
16179                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16180                }
16181
16182                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16183                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16184                }
16185            }
16186        }
16187
16188        synchronized (mPackages) {
16189            int updateFlags = UPDATE_PERMISSIONS_ALL;
16190            if (ver.sdkVersion != mSdkVersion) {
16191                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16192                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16193                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16194            }
16195            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16196
16197            // Yay, everything is now upgraded
16198            ver.forceCurrent();
16199
16200            mSettings.writeLPr();
16201        }
16202
16203        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16204        sendResourcesChangedBroadcast(true, false, loaded, null);
16205    }
16206
16207    private void unloadPrivatePackages(final VolumeInfo vol) {
16208        mHandler.post(new Runnable() {
16209            @Override
16210            public void run() {
16211                unloadPrivatePackagesInner(vol);
16212            }
16213        });
16214    }
16215
16216    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16217        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16218        synchronized (mInstallLock) {
16219        synchronized (mPackages) {
16220            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16221            for (PackageSetting ps : packages) {
16222                if (ps.pkg == null) continue;
16223
16224                final ApplicationInfo info = ps.pkg.applicationInfo;
16225                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16226                if (deletePackageLI(ps.name, null, false, null, null,
16227                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16228                    unloaded.add(info);
16229                } else {
16230                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16231                }
16232            }
16233
16234            mSettings.writeLPr();
16235        }
16236        }
16237
16238        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16239        sendResourcesChangedBroadcast(false, false, unloaded, null);
16240    }
16241
16242    /**
16243     * Examine all users present on given mounted volume, and destroy data
16244     * belonging to users that are no longer valid, or whose user ID has been
16245     * recycled.
16246     */
16247    private void reconcileUsers(String volumeUuid) {
16248        final File[] files = FileUtils
16249                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16250        for (File file : files) {
16251            if (!file.isDirectory()) continue;
16252
16253            final int userId;
16254            final UserInfo info;
16255            try {
16256                userId = Integer.parseInt(file.getName());
16257                info = sUserManager.getUserInfo(userId);
16258            } catch (NumberFormatException e) {
16259                Slog.w(TAG, "Invalid user directory " + file);
16260                continue;
16261            }
16262
16263            boolean destroyUser = false;
16264            if (info == null) {
16265                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16266                        + " because no matching user was found");
16267                destroyUser = true;
16268            } else {
16269                try {
16270                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16271                } catch (IOException e) {
16272                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16273                            + " because we failed to enforce serial number: " + e);
16274                    destroyUser = true;
16275                }
16276            }
16277
16278            if (destroyUser) {
16279                synchronized (mInstallLock) {
16280                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16281                }
16282            }
16283        }
16284
16285        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16286        final UserManager um = mContext.getSystemService(UserManager.class);
16287        for (UserInfo user : um.getUsers()) {
16288            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16289            if (userDir.exists()) continue;
16290
16291            try {
16292                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
16293                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16294            } catch (IOException e) {
16295                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16296            }
16297        }
16298    }
16299
16300    /**
16301     * Examine all apps present on given mounted volume, and destroy apps that
16302     * aren't expected, either due to uninstallation or reinstallation on
16303     * another volume.
16304     */
16305    private void reconcileApps(String volumeUuid) {
16306        final File[] files = FileUtils
16307                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16308        for (File file : files) {
16309            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16310                    && !PackageInstallerService.isStageName(file.getName());
16311            if (!isPackage) {
16312                // Ignore entries which are not packages
16313                continue;
16314            }
16315
16316            boolean destroyApp = false;
16317            String packageName = null;
16318            try {
16319                final PackageLite pkg = PackageParser.parsePackageLite(file,
16320                        PackageParser.PARSE_MUST_BE_APK);
16321                packageName = pkg.packageName;
16322
16323                synchronized (mPackages) {
16324                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16325                    if (ps == null) {
16326                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16327                                + volumeUuid + " because we found no install record");
16328                        destroyApp = true;
16329                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16330                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16331                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16332                        destroyApp = true;
16333                    }
16334                }
16335
16336            } catch (PackageParserException e) {
16337                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16338                destroyApp = true;
16339            }
16340
16341            if (destroyApp) {
16342                synchronized (mInstallLock) {
16343                    if (packageName != null) {
16344                        removeDataDirsLI(volumeUuid, packageName);
16345                    }
16346                    if (file.isDirectory()) {
16347                        mInstaller.rmPackageDir(file.getAbsolutePath());
16348                    } else {
16349                        file.delete();
16350                    }
16351                }
16352            }
16353        }
16354    }
16355
16356    private void unfreezePackage(String packageName) {
16357        synchronized (mPackages) {
16358            final PackageSetting ps = mSettings.mPackages.get(packageName);
16359            if (ps != null) {
16360                ps.frozen = false;
16361            }
16362        }
16363    }
16364
16365    @Override
16366    public int movePackage(final String packageName, final String volumeUuid) {
16367        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16368
16369        final int moveId = mNextMoveId.getAndIncrement();
16370        mHandler.post(new Runnable() {
16371            @Override
16372            public void run() {
16373                try {
16374                    movePackageInternal(packageName, volumeUuid, moveId);
16375                } catch (PackageManagerException e) {
16376                    Slog.w(TAG, "Failed to move " + packageName, e);
16377                    mMoveCallbacks.notifyStatusChanged(moveId,
16378                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16379                }
16380            }
16381        });
16382        return moveId;
16383    }
16384
16385    private void movePackageInternal(final String packageName, final String volumeUuid,
16386            final int moveId) throws PackageManagerException {
16387        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16388        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16389        final PackageManager pm = mContext.getPackageManager();
16390
16391        final boolean currentAsec;
16392        final String currentVolumeUuid;
16393        final File codeFile;
16394        final String installerPackageName;
16395        final String packageAbiOverride;
16396        final int appId;
16397        final String seinfo;
16398        final String label;
16399
16400        // reader
16401        synchronized (mPackages) {
16402            final PackageParser.Package pkg = mPackages.get(packageName);
16403            final PackageSetting ps = mSettings.mPackages.get(packageName);
16404            if (pkg == null || ps == null) {
16405                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16406            }
16407
16408            if (pkg.applicationInfo.isSystemApp()) {
16409                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16410                        "Cannot move system application");
16411            }
16412
16413            if (pkg.applicationInfo.isExternalAsec()) {
16414                currentAsec = true;
16415                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16416            } else if (pkg.applicationInfo.isForwardLocked()) {
16417                currentAsec = true;
16418                currentVolumeUuid = "forward_locked";
16419            } else {
16420                currentAsec = false;
16421                currentVolumeUuid = ps.volumeUuid;
16422
16423                final File probe = new File(pkg.codePath);
16424                final File probeOat = new File(probe, "oat");
16425                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16426                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16427                            "Move only supported for modern cluster style installs");
16428                }
16429            }
16430
16431            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16432                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16433                        "Package already moved to " + volumeUuid);
16434            }
16435
16436            if (ps.frozen) {
16437                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16438                        "Failed to move already frozen package");
16439            }
16440            ps.frozen = true;
16441
16442            codeFile = new File(pkg.codePath);
16443            installerPackageName = ps.installerPackageName;
16444            packageAbiOverride = ps.cpuAbiOverrideString;
16445            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16446            seinfo = pkg.applicationInfo.seinfo;
16447            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16448        }
16449
16450        // Now that we're guarded by frozen state, kill app during move
16451        final long token = Binder.clearCallingIdentity();
16452        try {
16453            killApplication(packageName, appId, "move pkg");
16454        } finally {
16455            Binder.restoreCallingIdentity(token);
16456        }
16457
16458        final Bundle extras = new Bundle();
16459        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16460        extras.putString(Intent.EXTRA_TITLE, label);
16461        mMoveCallbacks.notifyCreated(moveId, extras);
16462
16463        int installFlags;
16464        final boolean moveCompleteApp;
16465        final File measurePath;
16466
16467        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16468            installFlags = INSTALL_INTERNAL;
16469            moveCompleteApp = !currentAsec;
16470            measurePath = Environment.getDataAppDirectory(volumeUuid);
16471        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16472            installFlags = INSTALL_EXTERNAL;
16473            moveCompleteApp = false;
16474            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16475        } else {
16476            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16477            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16478                    || !volume.isMountedWritable()) {
16479                unfreezePackage(packageName);
16480                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16481                        "Move location not mounted private volume");
16482            }
16483
16484            Preconditions.checkState(!currentAsec);
16485
16486            installFlags = INSTALL_INTERNAL;
16487            moveCompleteApp = true;
16488            measurePath = Environment.getDataAppDirectory(volumeUuid);
16489        }
16490
16491        final PackageStats stats = new PackageStats(null, -1);
16492        synchronized (mInstaller) {
16493            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16494                unfreezePackage(packageName);
16495                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16496                        "Failed to measure package size");
16497            }
16498        }
16499
16500        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16501                + stats.dataSize);
16502
16503        final long startFreeBytes = measurePath.getFreeSpace();
16504        final long sizeBytes;
16505        if (moveCompleteApp) {
16506            sizeBytes = stats.codeSize + stats.dataSize;
16507        } else {
16508            sizeBytes = stats.codeSize;
16509        }
16510
16511        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16512            unfreezePackage(packageName);
16513            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16514                    "Not enough free space to move");
16515        }
16516
16517        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16518
16519        final CountDownLatch installedLatch = new CountDownLatch(1);
16520        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16521            @Override
16522            public void onUserActionRequired(Intent intent) throws RemoteException {
16523                throw new IllegalStateException();
16524            }
16525
16526            @Override
16527            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16528                    Bundle extras) throws RemoteException {
16529                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16530                        + PackageManager.installStatusToString(returnCode, msg));
16531
16532                installedLatch.countDown();
16533
16534                // Regardless of success or failure of the move operation,
16535                // always unfreeze the package
16536                unfreezePackage(packageName);
16537
16538                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16539                switch (status) {
16540                    case PackageInstaller.STATUS_SUCCESS:
16541                        mMoveCallbacks.notifyStatusChanged(moveId,
16542                                PackageManager.MOVE_SUCCEEDED);
16543                        break;
16544                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16545                        mMoveCallbacks.notifyStatusChanged(moveId,
16546                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16547                        break;
16548                    default:
16549                        mMoveCallbacks.notifyStatusChanged(moveId,
16550                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16551                        break;
16552                }
16553            }
16554        };
16555
16556        final MoveInfo move;
16557        if (moveCompleteApp) {
16558            // Kick off a thread to report progress estimates
16559            new Thread() {
16560                @Override
16561                public void run() {
16562                    while (true) {
16563                        try {
16564                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16565                                break;
16566                            }
16567                        } catch (InterruptedException ignored) {
16568                        }
16569
16570                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16571                        final int progress = 10 + (int) MathUtils.constrain(
16572                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16573                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16574                    }
16575                }
16576            }.start();
16577
16578            final String dataAppName = codeFile.getName();
16579            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16580                    dataAppName, appId, seinfo);
16581        } else {
16582            move = null;
16583        }
16584
16585        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16586
16587        final Message msg = mHandler.obtainMessage(INIT_COPY);
16588        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16589        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16590                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16591        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16592        msg.obj = params;
16593
16594        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16595                System.identityHashCode(msg.obj));
16596        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16597                System.identityHashCode(msg.obj));
16598
16599        mHandler.sendMessage(msg);
16600    }
16601
16602    @Override
16603    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16604        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16605
16606        final int realMoveId = mNextMoveId.getAndIncrement();
16607        final Bundle extras = new Bundle();
16608        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16609        mMoveCallbacks.notifyCreated(realMoveId, extras);
16610
16611        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16612            @Override
16613            public void onCreated(int moveId, Bundle extras) {
16614                // Ignored
16615            }
16616
16617            @Override
16618            public void onStatusChanged(int moveId, int status, long estMillis) {
16619                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16620            }
16621        };
16622
16623        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16624        storage.setPrimaryStorageUuid(volumeUuid, callback);
16625        return realMoveId;
16626    }
16627
16628    @Override
16629    public int getMoveStatus(int moveId) {
16630        mContext.enforceCallingOrSelfPermission(
16631                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16632        return mMoveCallbacks.mLastStatus.get(moveId);
16633    }
16634
16635    @Override
16636    public void registerMoveCallback(IPackageMoveObserver callback) {
16637        mContext.enforceCallingOrSelfPermission(
16638                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16639        mMoveCallbacks.register(callback);
16640    }
16641
16642    @Override
16643    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16644        mContext.enforceCallingOrSelfPermission(
16645                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16646        mMoveCallbacks.unregister(callback);
16647    }
16648
16649    @Override
16650    public boolean setInstallLocation(int loc) {
16651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16652                null);
16653        if (getInstallLocation() == loc) {
16654            return true;
16655        }
16656        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16657                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16658            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16659                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16660            return true;
16661        }
16662        return false;
16663   }
16664
16665    @Override
16666    public int getInstallLocation() {
16667        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16668                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16669                PackageHelper.APP_INSTALL_AUTO);
16670    }
16671
16672    /** Called by UserManagerService */
16673    void cleanUpUser(UserManagerService userManager, int userHandle) {
16674        synchronized (mPackages) {
16675            mDirtyUsers.remove(userHandle);
16676            mUserNeedsBadging.delete(userHandle);
16677            mSettings.removeUserLPw(userHandle);
16678            mPendingBroadcasts.remove(userHandle);
16679        }
16680        synchronized (mInstallLock) {
16681            if (mInstaller != null) {
16682                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16683                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16684                    final String volumeUuid = vol.getFsUuid();
16685                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16686                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16687                }
16688            }
16689            synchronized (mPackages) {
16690                removeUnusedPackagesLILPw(userManager, userHandle);
16691            }
16692        }
16693    }
16694
16695    /**
16696     * We're removing userHandle and would like to remove any downloaded packages
16697     * that are no longer in use by any other user.
16698     * @param userHandle the user being removed
16699     */
16700    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16701        final boolean DEBUG_CLEAN_APKS = false;
16702        int [] users = userManager.getUserIds();
16703        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16704        while (psit.hasNext()) {
16705            PackageSetting ps = psit.next();
16706            if (ps.pkg == null) {
16707                continue;
16708            }
16709            final String packageName = ps.pkg.packageName;
16710            // Skip over if system app
16711            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16712                continue;
16713            }
16714            if (DEBUG_CLEAN_APKS) {
16715                Slog.i(TAG, "Checking package " + packageName);
16716            }
16717            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16718            if (keep) {
16719                if (DEBUG_CLEAN_APKS) {
16720                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16721                }
16722            } else {
16723                for (int i = 0; i < users.length; i++) {
16724                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16725                        keep = true;
16726                        if (DEBUG_CLEAN_APKS) {
16727                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16728                                    + users[i]);
16729                        }
16730                        break;
16731                    }
16732                }
16733            }
16734            if (!keep) {
16735                if (DEBUG_CLEAN_APKS) {
16736                    Slog.i(TAG, "  Removing package " + packageName);
16737                }
16738                mHandler.post(new Runnable() {
16739                    public void run() {
16740                        deletePackageX(packageName, userHandle, 0);
16741                    } //end run
16742                });
16743            }
16744        }
16745    }
16746
16747    /** Called by UserManagerService */
16748    void createNewUser(int userHandle) {
16749        if (mInstaller != null) {
16750            synchronized (mInstallLock) {
16751                synchronized (mPackages) {
16752                    mInstaller.createUserConfig(userHandle);
16753                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16754                }
16755            }
16756            synchronized (mPackages) {
16757                applyFactoryDefaultBrowserLPw(userHandle);
16758                primeDomainVerificationsLPw(userHandle);
16759            }
16760        }
16761    }
16762
16763    void newUserCreated(final int userHandle) {
16764        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16765    }
16766
16767    @Override
16768    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16769        mContext.enforceCallingOrSelfPermission(
16770                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16771                "Only package verification agents can read the verifier device identity");
16772
16773        synchronized (mPackages) {
16774            return mSettings.getVerifierDeviceIdentityLPw();
16775        }
16776    }
16777
16778    @Override
16779    public void setPermissionEnforced(String permission, boolean enforced) {
16780        // TODO: Now that we no longer change GID for storage, this should to away.
16781        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16782                "setPermissionEnforced");
16783        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16784            synchronized (mPackages) {
16785                if (mSettings.mReadExternalStorageEnforced == null
16786                        || mSettings.mReadExternalStorageEnforced != enforced) {
16787                    mSettings.mReadExternalStorageEnforced = enforced;
16788                    mSettings.writeLPr();
16789                }
16790            }
16791            // kill any non-foreground processes so we restart them and
16792            // grant/revoke the GID.
16793            final IActivityManager am = ActivityManagerNative.getDefault();
16794            if (am != null) {
16795                final long token = Binder.clearCallingIdentity();
16796                try {
16797                    am.killProcessesBelowForeground("setPermissionEnforcement");
16798                } catch (RemoteException e) {
16799                } finally {
16800                    Binder.restoreCallingIdentity(token);
16801                }
16802            }
16803        } else {
16804            throw new IllegalArgumentException("No selective enforcement for " + permission);
16805        }
16806    }
16807
16808    @Override
16809    @Deprecated
16810    public boolean isPermissionEnforced(String permission) {
16811        return true;
16812    }
16813
16814    @Override
16815    public boolean isStorageLow() {
16816        final long token = Binder.clearCallingIdentity();
16817        try {
16818            final DeviceStorageMonitorInternal
16819                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16820            if (dsm != null) {
16821                return dsm.isMemoryLow();
16822            } else {
16823                return false;
16824            }
16825        } finally {
16826            Binder.restoreCallingIdentity(token);
16827        }
16828    }
16829
16830    @Override
16831    public IPackageInstaller getPackageInstaller() {
16832        return mInstallerService;
16833    }
16834
16835    private boolean userNeedsBadging(int userId) {
16836        int index = mUserNeedsBadging.indexOfKey(userId);
16837        if (index < 0) {
16838            final UserInfo userInfo;
16839            final long token = Binder.clearCallingIdentity();
16840            try {
16841                userInfo = sUserManager.getUserInfo(userId);
16842            } finally {
16843                Binder.restoreCallingIdentity(token);
16844            }
16845            final boolean b;
16846            if (userInfo != null && userInfo.isManagedProfile()) {
16847                b = true;
16848            } else {
16849                b = false;
16850            }
16851            mUserNeedsBadging.put(userId, b);
16852            return b;
16853        }
16854        return mUserNeedsBadging.valueAt(index);
16855    }
16856
16857    @Override
16858    public KeySet getKeySetByAlias(String packageName, String alias) {
16859        if (packageName == null || alias == null) {
16860            return null;
16861        }
16862        synchronized(mPackages) {
16863            final PackageParser.Package pkg = mPackages.get(packageName);
16864            if (pkg == null) {
16865                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16866                throw new IllegalArgumentException("Unknown package: " + packageName);
16867            }
16868            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16869            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16870        }
16871    }
16872
16873    @Override
16874    public KeySet getSigningKeySet(String packageName) {
16875        if (packageName == null) {
16876            return null;
16877        }
16878        synchronized(mPackages) {
16879            final PackageParser.Package pkg = mPackages.get(packageName);
16880            if (pkg == null) {
16881                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16882                throw new IllegalArgumentException("Unknown package: " + packageName);
16883            }
16884            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16885                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16886                throw new SecurityException("May not access signing KeySet of other apps.");
16887            }
16888            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16889            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16890        }
16891    }
16892
16893    @Override
16894    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16895        if (packageName == null || ks == null) {
16896            return false;
16897        }
16898        synchronized(mPackages) {
16899            final PackageParser.Package pkg = mPackages.get(packageName);
16900            if (pkg == null) {
16901                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16902                throw new IllegalArgumentException("Unknown package: " + packageName);
16903            }
16904            IBinder ksh = ks.getToken();
16905            if (ksh instanceof KeySetHandle) {
16906                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16907                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16908            }
16909            return false;
16910        }
16911    }
16912
16913    @Override
16914    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16915        if (packageName == null || ks == null) {
16916            return false;
16917        }
16918        synchronized(mPackages) {
16919            final PackageParser.Package pkg = mPackages.get(packageName);
16920            if (pkg == null) {
16921                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16922                throw new IllegalArgumentException("Unknown package: " + packageName);
16923            }
16924            IBinder ksh = ks.getToken();
16925            if (ksh instanceof KeySetHandle) {
16926                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16927                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16928            }
16929            return false;
16930        }
16931    }
16932
16933    private void deletePackageIfUnusedLPr(final String packageName) {
16934        PackageSetting ps = mSettings.mPackages.get(packageName);
16935        if (ps == null) {
16936            return;
16937        }
16938        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
16939            // TODO Implement atomic delete if package is unused
16940            // It is currently possible that the package will be deleted even if it is installed
16941            // after this method returns.
16942            mHandler.post(new Runnable() {
16943                public void run() {
16944                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
16945                }
16946            });
16947        }
16948    }
16949
16950    /**
16951     * Check and throw if the given before/after packages would be considered a
16952     * downgrade.
16953     */
16954    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16955            throws PackageManagerException {
16956        if (after.versionCode < before.mVersionCode) {
16957            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16958                    "Update version code " + after.versionCode + " is older than current "
16959                    + before.mVersionCode);
16960        } else if (after.versionCode == before.mVersionCode) {
16961            if (after.baseRevisionCode < before.baseRevisionCode) {
16962                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16963                        "Update base revision code " + after.baseRevisionCode
16964                        + " is older than current " + before.baseRevisionCode);
16965            }
16966
16967            if (!ArrayUtils.isEmpty(after.splitNames)) {
16968                for (int i = 0; i < after.splitNames.length; i++) {
16969                    final String splitName = after.splitNames[i];
16970                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16971                    if (j != -1) {
16972                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16973                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16974                                    "Update split " + splitName + " revision code "
16975                                    + after.splitRevisionCodes[i] + " is older than current "
16976                                    + before.splitRevisionCodes[j]);
16977                        }
16978                    }
16979                }
16980            }
16981        }
16982    }
16983
16984    private static class MoveCallbacks extends Handler {
16985        private static final int MSG_CREATED = 1;
16986        private static final int MSG_STATUS_CHANGED = 2;
16987
16988        private final RemoteCallbackList<IPackageMoveObserver>
16989                mCallbacks = new RemoteCallbackList<>();
16990
16991        private final SparseIntArray mLastStatus = new SparseIntArray();
16992
16993        public MoveCallbacks(Looper looper) {
16994            super(looper);
16995        }
16996
16997        public void register(IPackageMoveObserver callback) {
16998            mCallbacks.register(callback);
16999        }
17000
17001        public void unregister(IPackageMoveObserver callback) {
17002            mCallbacks.unregister(callback);
17003        }
17004
17005        @Override
17006        public void handleMessage(Message msg) {
17007            final SomeArgs args = (SomeArgs) msg.obj;
17008            final int n = mCallbacks.beginBroadcast();
17009            for (int i = 0; i < n; i++) {
17010                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17011                try {
17012                    invokeCallback(callback, msg.what, args);
17013                } catch (RemoteException ignored) {
17014                }
17015            }
17016            mCallbacks.finishBroadcast();
17017            args.recycle();
17018        }
17019
17020        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17021                throws RemoteException {
17022            switch (what) {
17023                case MSG_CREATED: {
17024                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17025                    break;
17026                }
17027                case MSG_STATUS_CHANGED: {
17028                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17029                    break;
17030                }
17031            }
17032        }
17033
17034        private void notifyCreated(int moveId, Bundle extras) {
17035            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17036
17037            final SomeArgs args = SomeArgs.obtain();
17038            args.argi1 = moveId;
17039            args.arg2 = extras;
17040            obtainMessage(MSG_CREATED, args).sendToTarget();
17041        }
17042
17043        private void notifyStatusChanged(int moveId, int status) {
17044            notifyStatusChanged(moveId, status, -1);
17045        }
17046
17047        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17048            Slog.v(TAG, "Move " + moveId + " status " + status);
17049
17050            final SomeArgs args = SomeArgs.obtain();
17051            args.argi1 = moveId;
17052            args.argi2 = status;
17053            args.arg3 = estMillis;
17054            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17055
17056            synchronized (mLastStatus) {
17057                mLastStatus.put(moveId, status);
17058            }
17059        }
17060    }
17061
17062    private final class OnPermissionChangeListeners extends Handler {
17063        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17064
17065        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17066                new RemoteCallbackList<>();
17067
17068        public OnPermissionChangeListeners(Looper looper) {
17069            super(looper);
17070        }
17071
17072        @Override
17073        public void handleMessage(Message msg) {
17074            switch (msg.what) {
17075                case MSG_ON_PERMISSIONS_CHANGED: {
17076                    final int uid = msg.arg1;
17077                    handleOnPermissionsChanged(uid);
17078                } break;
17079            }
17080        }
17081
17082        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17083            mPermissionListeners.register(listener);
17084
17085        }
17086
17087        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17088            mPermissionListeners.unregister(listener);
17089        }
17090
17091        public void onPermissionsChanged(int uid) {
17092            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17093                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17094            }
17095        }
17096
17097        private void handleOnPermissionsChanged(int uid) {
17098            final int count = mPermissionListeners.beginBroadcast();
17099            try {
17100                for (int i = 0; i < count; i++) {
17101                    IOnPermissionsChangeListener callback = mPermissionListeners
17102                            .getBroadcastItem(i);
17103                    try {
17104                        callback.onPermissionsChanged(uid);
17105                    } catch (RemoteException e) {
17106                        Log.e(TAG, "Permission listener is dead", e);
17107                    }
17108                }
17109            } finally {
17110                mPermissionListeners.finishBroadcast();
17111            }
17112        }
17113    }
17114
17115    private class PackageManagerInternalImpl extends PackageManagerInternal {
17116        @Override
17117        public void setLocationPackagesProvider(PackagesProvider provider) {
17118            synchronized (mPackages) {
17119                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17120            }
17121        }
17122
17123        @Override
17124        public void setImePackagesProvider(PackagesProvider provider) {
17125            synchronized (mPackages) {
17126                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17127            }
17128        }
17129
17130        @Override
17131        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17132            synchronized (mPackages) {
17133                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17134            }
17135        }
17136
17137        @Override
17138        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17139            synchronized (mPackages) {
17140                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17141            }
17142        }
17143
17144        @Override
17145        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17146            synchronized (mPackages) {
17147                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17148            }
17149        }
17150
17151        @Override
17152        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17153            synchronized (mPackages) {
17154                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17155            }
17156        }
17157
17158        @Override
17159        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17160            synchronized (mPackages) {
17161                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17162            }
17163        }
17164
17165        @Override
17166        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17167            synchronized (mPackages) {
17168                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17169                        packageName, userId);
17170            }
17171        }
17172
17173        @Override
17174        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17175            synchronized (mPackages) {
17176                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17177                        packageName, userId);
17178            }
17179        }
17180        @Override
17181        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17182            synchronized (mPackages) {
17183                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17184                        packageName, userId);
17185            }
17186        }
17187
17188        @Override
17189        public void setKeepUninstalledPackages(final List<String> packageList) {
17190            Preconditions.checkNotNull(packageList);
17191            List<String> removedFromList = null;
17192            synchronized (mPackages) {
17193                if (mKeepUninstalledPackages != null) {
17194                    final int packagesCount = mKeepUninstalledPackages.size();
17195                    for (int i = 0; i < packagesCount; i++) {
17196                        String oldPackage = mKeepUninstalledPackages.get(i);
17197                        if (packageList != null && packageList.contains(oldPackage)) {
17198                            continue;
17199                        }
17200                        if (removedFromList == null) {
17201                            removedFromList = new ArrayList<>();
17202                        }
17203                        removedFromList.add(oldPackage);
17204                    }
17205                }
17206                mKeepUninstalledPackages = new ArrayList<>(packageList);
17207                if (removedFromList != null) {
17208                    final int removedCount = removedFromList.size();
17209                    for (int i = 0; i < removedCount; i++) {
17210                        deletePackageIfUnusedLPr(removedFromList.get(i));
17211                    }
17212                }
17213            }
17214        }
17215    }
17216
17217    @Override
17218    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17219        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17220        synchronized (mPackages) {
17221            final long identity = Binder.clearCallingIdentity();
17222            try {
17223                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17224                        packageNames, userId);
17225            } finally {
17226                Binder.restoreCallingIdentity(identity);
17227            }
17228        }
17229    }
17230
17231    private static void enforceSystemOrPhoneCaller(String tag) {
17232        int callingUid = Binder.getCallingUid();
17233        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17234            throw new SecurityException(
17235                    "Cannot call " + tag + " from UID " + callingUid);
17236        }
17237    }
17238}
17239