PackageManagerService.java revision fdf59bf82f35ccc870dbb7eb20b958997ea73b36
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.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.pm.Settings.VersionInfo;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277runtest -c android.content.pm.PackageManagerTests frameworks-core
278 *
279 * {@hide}
280 */
281public class PackageManagerService extends IPackageManager.Stub {
282    static final String TAG = "PackageManager";
283    static final boolean DEBUG_SETTINGS = false;
284    static final boolean DEBUG_PREFERRED = false;
285    static final boolean DEBUG_UPGRADE = false;
286    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
287    private static final boolean DEBUG_BACKUP = false;
288    private static final boolean DEBUG_INSTALL = false;
289    private static final boolean DEBUG_REMOVE = false;
290    private static final boolean DEBUG_BROADCASTS = false;
291    private static final boolean DEBUG_SHOW_INFO = false;
292    private static final boolean DEBUG_PACKAGE_INFO = false;
293    private static final boolean DEBUG_INTENT_MATCHING = false;
294    private static final boolean DEBUG_PACKAGE_SCANNING = false;
295    private static final boolean DEBUG_VERIFY = false;
296    private static final boolean DEBUG_DEXOPT = false;
297    private static final boolean DEBUG_ABI_SELECTION = false;
298
299    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
300
301    private static final int RADIO_UID = Process.PHONE_UID;
302    private static final int LOG_UID = Process.LOG_UID;
303    private static final int NFC_UID = Process.NFC_UID;
304    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
305    private static final int SHELL_UID = Process.SHELL_UID;
306
307    // Cap the size of permission trees that 3rd party apps can define
308    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
309
310    // Suffix used during package installation when copying/moving
311    // package apks to install directory.
312    private static final String INSTALL_PACKAGE_SUFFIX = "-";
313
314    static final int SCAN_NO_DEX = 1<<1;
315    static final int SCAN_FORCE_DEX = 1<<2;
316    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
317    static final int SCAN_NEW_INSTALL = 1<<4;
318    static final int SCAN_NO_PATHS = 1<<5;
319    static final int SCAN_UPDATE_TIME = 1<<6;
320    static final int SCAN_DEFER_DEX = 1<<7;
321    static final int SCAN_BOOTING = 1<<8;
322    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
323    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
324    static final int SCAN_REPLACING = 1<<11;
325    static final int SCAN_REQUIRE_KNOWN = 1<<12;
326    static final int SCAN_MOVE = 1<<13;
327    static final int SCAN_INITIAL = 1<<14;
328
329    static final int REMOVE_CHATTY = 1<<16;
330
331    private static final int[] EMPTY_INT_ARRAY = new int[0];
332
333    /**
334     * Timeout (in milliseconds) after which the watchdog should declare that
335     * our handler thread is wedged.  The usual default for such things is one
336     * minute but we sometimes do very lengthy I/O operations on this thread,
337     * such as installing multi-gigabyte applications, so ours needs to be longer.
338     */
339    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
340
341    /**
342     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
343     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
344     * settings entry if available, otherwise we use the hardcoded default.  If it's been
345     * more than this long since the last fstrim, we force one during the boot sequence.
346     *
347     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
348     * one gets run at the next available charging+idle time.  This final mandatory
349     * no-fstrim check kicks in only of the other scheduling criteria is never met.
350     */
351    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
352
353    /**
354     * Whether verification is enabled by default.
355     */
356    private static final boolean DEFAULT_VERIFY_ENABLE = true;
357
358    /**
359     * The default maximum time to wait for the verification agent to return in
360     * milliseconds.
361     */
362    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
363
364    /**
365     * The default response for package verification timeout.
366     *
367     * This can be either PackageManager.VERIFICATION_ALLOW or
368     * PackageManager.VERIFICATION_REJECT.
369     */
370    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
371
372    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
373
374    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
375            DEFAULT_CONTAINER_PACKAGE,
376            "com.android.defcontainer.DefaultContainerService");
377
378    private static final String KILL_APP_REASON_GIDS_CHANGED =
379            "permission grant or revoke changed gids";
380
381    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
382            "permissions revoked";
383
384    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
385
386    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
387
388    /** Permission grant: not grant the permission. */
389    private static final int GRANT_DENIED = 1;
390
391    /** Permission grant: grant the permission as an install permission. */
392    private static final int GRANT_INSTALL = 2;
393
394    /** Permission grant: grant the permission as an install permission for a legacy app. */
395    private static final int GRANT_INSTALL_LEGACY = 3;
396
397    /** Permission grant: grant the permission as a runtime one. */
398    private static final int GRANT_RUNTIME = 4;
399
400    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
401    private static final int GRANT_UPGRADE = 5;
402
403    /** Canonical intent used to identify what counts as a "web browser" app */
404    private static final Intent sBrowserIntent;
405    static {
406        sBrowserIntent = new Intent();
407        sBrowserIntent.setAction(Intent.ACTION_VIEW);
408        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
409        sBrowserIntent.setData(Uri.parse("http:"));
410    }
411
412    final ServiceThread mHandlerThread;
413
414    final PackageHandler mHandler;
415
416    /**
417     * Messages for {@link #mHandler} that need to wait for system ready before
418     * being dispatched.
419     */
420    private ArrayList<Message> mPostSystemReadyMessages;
421
422    final int mSdkVersion = Build.VERSION.SDK_INT;
423
424    final Context mContext;
425    final boolean mFactoryTest;
426    final boolean mOnlyCore;
427    final boolean mLazyDexOpt;
428    final long mDexOptLRUThresholdInMills;
429    final DisplayMetrics mMetrics;
430    final int mDefParseFlags;
431    final String[] mSeparateProcesses;
432    final boolean mIsUpgrade;
433
434    // This is where all application persistent data goes.
435    final File mAppDataDir;
436
437    // This is where all application persistent data goes for secondary users.
438    final File mUserAppDataDir;
439
440    /** The location for ASEC container files on internal storage. */
441    final String mAsecInternalPath;
442
443    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
444    // LOCK HELD.  Can be called with mInstallLock held.
445    @GuardedBy("mInstallLock")
446    final Installer mInstaller;
447
448    /** Directory where installed third-party apps stored */
449    final File mAppInstallDir;
450
451    /**
452     * Directory to which applications installed internally have their
453     * 32 bit native libraries copied.
454     */
455    private File mAppLib32InstallDir;
456
457    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
458    // apps.
459    final File mDrmAppPrivateInstallDir;
460
461    // ----------------------------------------------------------------
462
463    // Lock for state used when installing and doing other long running
464    // operations.  Methods that must be called with this lock held have
465    // the suffix "LI".
466    final Object mInstallLock = new Object();
467
468    // ----------------------------------------------------------------
469
470    // Keys are String (package name), values are Package.  This also serves
471    // as the lock for the global state.  Methods that must be called with
472    // this lock held have the prefix "LP".
473    @GuardedBy("mPackages")
474    final ArrayMap<String, PackageParser.Package> mPackages =
475            new ArrayMap<String, PackageParser.Package>();
476
477    // Tracks available target package names -> overlay package paths.
478    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
479        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
480
481    /**
482     * Tracks new system packages [receiving in an OTA] that we expect to
483     * find updated user-installed versions. Keys are package name, values
484     * are package location.
485     */
486    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
487
488    final Settings mSettings;
489    boolean mRestoredSettings;
490
491    // System configuration read by SystemConfig.
492    final int[] mGlobalGids;
493    final SparseArray<ArraySet<String>> mSystemPermissions;
494    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
495
496    // If mac_permissions.xml was found for seinfo labeling.
497    boolean mFoundPolicyFile;
498
499    // If a recursive restorecon of /data/data/<pkg> is needed.
500    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
501
502    public static final class SharedLibraryEntry {
503        public final String path;
504        public final String apk;
505
506        SharedLibraryEntry(String _path, String _apk) {
507            path = _path;
508            apk = _apk;
509        }
510    }
511
512    // Currently known shared libraries.
513    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
514            new ArrayMap<String, SharedLibraryEntry>();
515
516    // All available activities, for your resolving pleasure.
517    final ActivityIntentResolver mActivities =
518            new ActivityIntentResolver();
519
520    // All available receivers, for your resolving pleasure.
521    final ActivityIntentResolver mReceivers =
522            new ActivityIntentResolver();
523
524    // All available services, for your resolving pleasure.
525    final ServiceIntentResolver mServices = new ServiceIntentResolver();
526
527    // All available providers, for your resolving pleasure.
528    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
529
530    // Mapping from provider base names (first directory in content URI codePath)
531    // to the provider information.
532    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
533            new ArrayMap<String, PackageParser.Provider>();
534
535    // Mapping from instrumentation class names to info about them.
536    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
537            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
538
539    // Mapping from permission names to info about them.
540    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
541            new ArrayMap<String, PackageParser.PermissionGroup>();
542
543    // Packages whose data we have transfered into another package, thus
544    // should no longer exist.
545    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
546
547    // Broadcast actions that are only available to the system.
548    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
549
550    /** List of packages waiting for verification. */
551    final SparseArray<PackageVerificationState> mPendingVerification
552            = new SparseArray<PackageVerificationState>();
553
554    /** Set of packages associated with each app op permission. */
555    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
556
557    final PackageInstallerService mInstallerService;
558
559    private final PackageDexOptimizer mPackageDexOptimizer;
560
561    private AtomicInteger mNextMoveId = new AtomicInteger();
562    private final MoveCallbacks mMoveCallbacks;
563
564    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
565
566    // Cache of users who need badging.
567    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
568
569    /** Token for keys in mPendingVerification. */
570    private int mPendingVerificationToken = 0;
571
572    volatile boolean mSystemReady;
573    volatile boolean mSafeMode;
574    volatile boolean mHasSystemUidErrors;
575
576    ApplicationInfo mAndroidApplication;
577    final ActivityInfo mResolveActivity = new ActivityInfo();
578    final ResolveInfo mResolveInfo = new ResolveInfo();
579    ComponentName mResolveComponentName;
580    PackageParser.Package mPlatformPackage;
581    ComponentName mCustomResolverComponentName;
582
583    boolean mResolverReplaced = false;
584
585    private final ComponentName mIntentFilterVerifierComponent;
586    private int mIntentFilterVerificationToken = 0;
587
588    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
589            = new SparseArray<IntentFilterVerificationState>();
590
591    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
592            new DefaultPermissionGrantPolicy(this);
593
594    private static class IFVerificationParams {
595        PackageParser.Package pkg;
596        boolean replacing;
597        int userId;
598        int verifierUid;
599
600        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
601                int _userId, int _verifierUid) {
602            pkg = _pkg;
603            replacing = _replacing;
604            userId = _userId;
605            replacing = _replacing;
606            verifierUid = _verifierUid;
607        }
608    }
609
610    private interface IntentFilterVerifier<T extends IntentFilter> {
611        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
612                                               T filter, String packageName);
613        void startVerifications(int userId);
614        void receiveVerificationResponse(int verificationId);
615    }
616
617    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
618        private Context mContext;
619        private ComponentName mIntentFilterVerifierComponent;
620        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
621
622        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
623            mContext = context;
624            mIntentFilterVerifierComponent = verifierComponent;
625        }
626
627        private String getDefaultScheme() {
628            return IntentFilter.SCHEME_HTTPS;
629        }
630
631        @Override
632        public void startVerifications(int userId) {
633            // Launch verifications requests
634            int count = mCurrentIntentFilterVerifications.size();
635            for (int n=0; n<count; n++) {
636                int verificationId = mCurrentIntentFilterVerifications.get(n);
637                final IntentFilterVerificationState ivs =
638                        mIntentFilterVerificationStates.get(verificationId);
639
640                String packageName = ivs.getPackageName();
641
642                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
643                final int filterCount = filters.size();
644                ArraySet<String> domainsSet = new ArraySet<>();
645                for (int m=0; m<filterCount; m++) {
646                    PackageParser.ActivityIntentInfo filter = filters.get(m);
647                    domainsSet.addAll(filter.getHostsList());
648                }
649                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
650                synchronized (mPackages) {
651                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
652                            packageName, domainsList) != null) {
653                        scheduleWriteSettingsLocked();
654                    }
655                }
656                sendVerificationRequest(userId, verificationId, ivs);
657            }
658            mCurrentIntentFilterVerifications.clear();
659        }
660
661        private void sendVerificationRequest(int userId, int verificationId,
662                IntentFilterVerificationState ivs) {
663
664            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
665            verificationIntent.putExtra(
666                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
667                    verificationId);
668            verificationIntent.putExtra(
669                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
670                    getDefaultScheme());
671            verificationIntent.putExtra(
672                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
673                    ivs.getHostsString());
674            verificationIntent.putExtra(
675                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
676                    ivs.getPackageName());
677            verificationIntent.setComponent(mIntentFilterVerifierComponent);
678            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
679
680            UserHandle user = new UserHandle(userId);
681            mContext.sendBroadcastAsUser(verificationIntent, user);
682            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
683                    "Sending IntentFilter verification broadcast");
684        }
685
686        public void receiveVerificationResponse(int verificationId) {
687            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
688
689            final boolean verified = ivs.isVerified();
690
691            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
692            final int count = filters.size();
693            if (DEBUG_DOMAIN_VERIFICATION) {
694                Slog.i(TAG, "Received verification response " + verificationId
695                        + " for " + count + " filters, verified=" + verified);
696            }
697            for (int n=0; n<count; n++) {
698                PackageParser.ActivityIntentInfo filter = filters.get(n);
699                filter.setVerified(verified);
700
701                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
702                        + " verified with result:" + verified + " and hosts:"
703                        + ivs.getHostsString());
704            }
705
706            mIntentFilterVerificationStates.remove(verificationId);
707
708            final String packageName = ivs.getPackageName();
709            IntentFilterVerificationInfo ivi = null;
710
711            synchronized (mPackages) {
712                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
713            }
714            if (ivi == null) {
715                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
716                        + verificationId + " packageName:" + packageName);
717                return;
718            }
719            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
720                    "Updating IntentFilterVerificationInfo for package " + packageName
721                            +" verificationId:" + verificationId);
722
723            synchronized (mPackages) {
724                if (verified) {
725                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
726                } else {
727                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
728                }
729                scheduleWriteSettingsLocked();
730
731                final int userId = ivs.getUserId();
732                if (userId != UserHandle.USER_ALL) {
733                    final int userStatus =
734                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
735
736                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
737                    boolean needUpdate = false;
738
739                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
740                    // already been set by the User thru the Disambiguation dialog
741                    switch (userStatus) {
742                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
743                            if (verified) {
744                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
745                            } else {
746                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
747                            }
748                            needUpdate = true;
749                            break;
750
751                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
752                            if (verified) {
753                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
754                                needUpdate = true;
755                            }
756                            break;
757
758                        default:
759                            // Nothing to do
760                    }
761
762                    if (needUpdate) {
763                        mSettings.updateIntentFilterVerificationStatusLPw(
764                                packageName, updatedStatus, userId);
765                        scheduleWritePackageRestrictionsLocked(userId);
766                    }
767                }
768            }
769        }
770
771        @Override
772        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
773                    ActivityIntentInfo filter, String packageName) {
774            if (!hasValidDomains(filter)) {
775                return false;
776            }
777            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
778            if (ivs == null) {
779                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
780                        packageName);
781            }
782            if (DEBUG_DOMAIN_VERIFICATION) {
783                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
784            }
785            ivs.addFilter(filter);
786            return true;
787        }
788
789        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
790                int userId, int verificationId, String packageName) {
791            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
792                    verifierUid, userId, packageName);
793            ivs.setPendingState();
794            synchronized (mPackages) {
795                mIntentFilterVerificationStates.append(verificationId, ivs);
796                mCurrentIntentFilterVerifications.add(verificationId);
797            }
798            return ivs;
799        }
800    }
801
802    private static boolean hasValidDomains(ActivityIntentInfo filter) {
803        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
804                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
805                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
806    }
807
808    private IntentFilterVerifier mIntentFilterVerifier;
809
810    // Set of pending broadcasts for aggregating enable/disable of components.
811    static class PendingPackageBroadcasts {
812        // for each user id, a map of <package name -> components within that package>
813        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
814
815        public PendingPackageBroadcasts() {
816            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
817        }
818
819        public ArrayList<String> get(int userId, String packageName) {
820            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
821            return packages.get(packageName);
822        }
823
824        public void put(int userId, String packageName, ArrayList<String> components) {
825            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
826            packages.put(packageName, components);
827        }
828
829        public void remove(int userId, String packageName) {
830            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
831            if (packages != null) {
832                packages.remove(packageName);
833            }
834        }
835
836        public void remove(int userId) {
837            mUidMap.remove(userId);
838        }
839
840        public int userIdCount() {
841            return mUidMap.size();
842        }
843
844        public int userIdAt(int n) {
845            return mUidMap.keyAt(n);
846        }
847
848        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
849            return mUidMap.get(userId);
850        }
851
852        public int size() {
853            // total number of pending broadcast entries across all userIds
854            int num = 0;
855            for (int i = 0; i< mUidMap.size(); i++) {
856                num += mUidMap.valueAt(i).size();
857            }
858            return num;
859        }
860
861        public void clear() {
862            mUidMap.clear();
863        }
864
865        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
866            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
867            if (map == null) {
868                map = new ArrayMap<String, ArrayList<String>>();
869                mUidMap.put(userId, map);
870            }
871            return map;
872        }
873    }
874    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
875
876    // Service Connection to remote media container service to copy
877    // package uri's from external media onto secure containers
878    // or internal storage.
879    private IMediaContainerService mContainerService = null;
880
881    static final int SEND_PENDING_BROADCAST = 1;
882    static final int MCS_BOUND = 3;
883    static final int END_COPY = 4;
884    static final int INIT_COPY = 5;
885    static final int MCS_UNBIND = 6;
886    static final int START_CLEANING_PACKAGE = 7;
887    static final int FIND_INSTALL_LOC = 8;
888    static final int POST_INSTALL = 9;
889    static final int MCS_RECONNECT = 10;
890    static final int MCS_GIVE_UP = 11;
891    static final int UPDATED_MEDIA_STATUS = 12;
892    static final int WRITE_SETTINGS = 13;
893    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
894    static final int PACKAGE_VERIFIED = 15;
895    static final int CHECK_PENDING_VERIFICATION = 16;
896    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
897    static final int INTENT_FILTER_VERIFIED = 18;
898
899    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
900
901    // Delay time in millisecs
902    static final int BROADCAST_DELAY = 10 * 1000;
903
904    static UserManagerService sUserManager;
905
906    // Stores a list of users whose package restrictions file needs to be updated
907    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
908
909    final private DefaultContainerConnection mDefContainerConn =
910            new DefaultContainerConnection();
911    class DefaultContainerConnection implements ServiceConnection {
912        public void onServiceConnected(ComponentName name, IBinder service) {
913            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
914            IMediaContainerService imcs =
915                IMediaContainerService.Stub.asInterface(service);
916            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
917        }
918
919        public void onServiceDisconnected(ComponentName name) {
920            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
921        }
922    }
923
924    // Recordkeeping of restore-after-install operations that are currently in flight
925    // between the Package Manager and the Backup Manager
926    class PostInstallData {
927        public InstallArgs args;
928        public PackageInstalledInfo res;
929
930        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
931            args = _a;
932            res = _r;
933        }
934    }
935
936    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
937    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
938
939    // XML tags for backup/restore of various bits of state
940    private static final String TAG_PREFERRED_BACKUP = "pa";
941    private static final String TAG_DEFAULT_APPS = "da";
942    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
943
944    final String mRequiredVerifierPackage;
945    final String mRequiredInstallerPackage;
946
947    private final PackageUsage mPackageUsage = new PackageUsage();
948
949    private class PackageUsage {
950        private static final int WRITE_INTERVAL
951            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
952
953        private final Object mFileLock = new Object();
954        private final AtomicLong mLastWritten = new AtomicLong(0);
955        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
956
957        private boolean mIsHistoricalPackageUsageAvailable = true;
958
959        boolean isHistoricalPackageUsageAvailable() {
960            return mIsHistoricalPackageUsageAvailable;
961        }
962
963        void write(boolean force) {
964            if (force) {
965                writeInternal();
966                return;
967            }
968            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
969                && !DEBUG_DEXOPT) {
970                return;
971            }
972            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
973                new Thread("PackageUsage_DiskWriter") {
974                    @Override
975                    public void run() {
976                        try {
977                            writeInternal();
978                        } finally {
979                            mBackgroundWriteRunning.set(false);
980                        }
981                    }
982                }.start();
983            }
984        }
985
986        private void writeInternal() {
987            synchronized (mPackages) {
988                synchronized (mFileLock) {
989                    AtomicFile file = getFile();
990                    FileOutputStream f = null;
991                    try {
992                        f = file.startWrite();
993                        BufferedOutputStream out = new BufferedOutputStream(f);
994                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
995                        StringBuilder sb = new StringBuilder();
996                        for (PackageParser.Package pkg : mPackages.values()) {
997                            if (pkg.mLastPackageUsageTimeInMills == 0) {
998                                continue;
999                            }
1000                            sb.setLength(0);
1001                            sb.append(pkg.packageName);
1002                            sb.append(' ');
1003                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1004                            sb.append('\n');
1005                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1006                        }
1007                        out.flush();
1008                        file.finishWrite(f);
1009                    } catch (IOException e) {
1010                        if (f != null) {
1011                            file.failWrite(f);
1012                        }
1013                        Log.e(TAG, "Failed to write package usage times", e);
1014                    }
1015                }
1016            }
1017            mLastWritten.set(SystemClock.elapsedRealtime());
1018        }
1019
1020        void readLP() {
1021            synchronized (mFileLock) {
1022                AtomicFile file = getFile();
1023                BufferedInputStream in = null;
1024                try {
1025                    in = new BufferedInputStream(file.openRead());
1026                    StringBuffer sb = new StringBuffer();
1027                    while (true) {
1028                        String packageName = readToken(in, sb, ' ');
1029                        if (packageName == null) {
1030                            break;
1031                        }
1032                        String timeInMillisString = readToken(in, sb, '\n');
1033                        if (timeInMillisString == null) {
1034                            throw new IOException("Failed to find last usage time for package "
1035                                                  + packageName);
1036                        }
1037                        PackageParser.Package pkg = mPackages.get(packageName);
1038                        if (pkg == null) {
1039                            continue;
1040                        }
1041                        long timeInMillis;
1042                        try {
1043                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1044                        } catch (NumberFormatException e) {
1045                            throw new IOException("Failed to parse " + timeInMillisString
1046                                                  + " as a long.", e);
1047                        }
1048                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1049                    }
1050                } catch (FileNotFoundException expected) {
1051                    mIsHistoricalPackageUsageAvailable = false;
1052                } catch (IOException e) {
1053                    Log.w(TAG, "Failed to read package usage times", e);
1054                } finally {
1055                    IoUtils.closeQuietly(in);
1056                }
1057            }
1058            mLastWritten.set(SystemClock.elapsedRealtime());
1059        }
1060
1061        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1062                throws IOException {
1063            sb.setLength(0);
1064            while (true) {
1065                int ch = in.read();
1066                if (ch == -1) {
1067                    if (sb.length() == 0) {
1068                        return null;
1069                    }
1070                    throw new IOException("Unexpected EOF");
1071                }
1072                if (ch == endOfToken) {
1073                    return sb.toString();
1074                }
1075                sb.append((char)ch);
1076            }
1077        }
1078
1079        private AtomicFile getFile() {
1080            File dataDir = Environment.getDataDirectory();
1081            File systemDir = new File(dataDir, "system");
1082            File fname = new File(systemDir, "package-usage.list");
1083            return new AtomicFile(fname);
1084        }
1085    }
1086
1087    class PackageHandler extends Handler {
1088        private boolean mBound = false;
1089        final ArrayList<HandlerParams> mPendingInstalls =
1090            new ArrayList<HandlerParams>();
1091
1092        private boolean connectToService() {
1093            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1094                    " DefaultContainerService");
1095            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1096            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1097            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1098                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1099                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1100                mBound = true;
1101                return true;
1102            }
1103            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1104            return false;
1105        }
1106
1107        private void disconnectService() {
1108            mContainerService = null;
1109            mBound = false;
1110            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111            mContext.unbindService(mDefContainerConn);
1112            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113        }
1114
1115        PackageHandler(Looper looper) {
1116            super(looper);
1117        }
1118
1119        public void handleMessage(Message msg) {
1120            try {
1121                doHandleMessage(msg);
1122            } finally {
1123                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1124            }
1125        }
1126
1127        void doHandleMessage(Message msg) {
1128            switch (msg.what) {
1129                case INIT_COPY: {
1130                    HandlerParams params = (HandlerParams) msg.obj;
1131                    int idx = mPendingInstalls.size();
1132                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1133                    // If a bind was already initiated we dont really
1134                    // need to do anything. The pending install
1135                    // will be processed later on.
1136                    if (!mBound) {
1137                        // If this is the only one pending we might
1138                        // have to bind to the service again.
1139                        if (!connectToService()) {
1140                            Slog.e(TAG, "Failed to bind to media container service");
1141                            params.serviceError();
1142                            return;
1143                        } else {
1144                            // Once we bind to the service, the first
1145                            // pending request will be processed.
1146                            mPendingInstalls.add(idx, params);
1147                        }
1148                    } else {
1149                        mPendingInstalls.add(idx, params);
1150                        // Already bound to the service. Just make
1151                        // sure we trigger off processing the first request.
1152                        if (idx == 0) {
1153                            mHandler.sendEmptyMessage(MCS_BOUND);
1154                        }
1155                    }
1156                    break;
1157                }
1158                case MCS_BOUND: {
1159                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1160                    if (msg.obj != null) {
1161                        mContainerService = (IMediaContainerService) msg.obj;
1162                    }
1163                    if (mContainerService == null) {
1164                        if (!mBound) {
1165                            // Something seriously wrong since we are not bound and we are not
1166                            // waiting for connection. Bail out.
1167                            Slog.e(TAG, "Cannot bind to media container service");
1168                            for (HandlerParams params : mPendingInstalls) {
1169                                // Indicate service bind error
1170                                params.serviceError();
1171                            }
1172                            mPendingInstalls.clear();
1173                        } else {
1174                            Slog.w(TAG, "Waiting to connect to media container service");
1175                        }
1176                    } else if (mPendingInstalls.size() > 0) {
1177                        HandlerParams params = mPendingInstalls.get(0);
1178                        if (params != null) {
1179                            if (params.startCopy()) {
1180                                // We are done...  look for more work or to
1181                                // go idle.
1182                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1183                                        "Checking for more work or unbind...");
1184                                // Delete pending install
1185                                if (mPendingInstalls.size() > 0) {
1186                                    mPendingInstalls.remove(0);
1187                                }
1188                                if (mPendingInstalls.size() == 0) {
1189                                    if (mBound) {
1190                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1191                                                "Posting delayed MCS_UNBIND");
1192                                        removeMessages(MCS_UNBIND);
1193                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1194                                        // Unbind after a little delay, to avoid
1195                                        // continual thrashing.
1196                                        sendMessageDelayed(ubmsg, 10000);
1197                                    }
1198                                } else {
1199                                    // There are more pending requests in queue.
1200                                    // Just post MCS_BOUND message to trigger processing
1201                                    // of next pending install.
1202                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1203                                            "Posting MCS_BOUND for next work");
1204                                    mHandler.sendEmptyMessage(MCS_BOUND);
1205                                }
1206                            }
1207                        }
1208                    } else {
1209                        // Should never happen ideally.
1210                        Slog.w(TAG, "Empty queue");
1211                    }
1212                    break;
1213                }
1214                case MCS_RECONNECT: {
1215                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1216                    if (mPendingInstalls.size() > 0) {
1217                        if (mBound) {
1218                            disconnectService();
1219                        }
1220                        if (!connectToService()) {
1221                            Slog.e(TAG, "Failed to bind to media container service");
1222                            for (HandlerParams params : mPendingInstalls) {
1223                                // Indicate service bind error
1224                                params.serviceError();
1225                            }
1226                            mPendingInstalls.clear();
1227                        }
1228                    }
1229                    break;
1230                }
1231                case MCS_UNBIND: {
1232                    // If there is no actual work left, then time to unbind.
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1234
1235                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1236                        if (mBound) {
1237                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1238
1239                            disconnectService();
1240                        }
1241                    } else if (mPendingInstalls.size() > 0) {
1242                        // There are more pending requests in queue.
1243                        // Just post MCS_BOUND message to trigger processing
1244                        // of next pending install.
1245                        mHandler.sendEmptyMessage(MCS_BOUND);
1246                    }
1247
1248                    break;
1249                }
1250                case MCS_GIVE_UP: {
1251                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1252                    mPendingInstalls.remove(0);
1253                    break;
1254                }
1255                case SEND_PENDING_BROADCAST: {
1256                    String packages[];
1257                    ArrayList<String> components[];
1258                    int size = 0;
1259                    int uids[];
1260                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261                    synchronized (mPackages) {
1262                        if (mPendingBroadcasts == null) {
1263                            return;
1264                        }
1265                        size = mPendingBroadcasts.size();
1266                        if (size <= 0) {
1267                            // Nothing to be done. Just return
1268                            return;
1269                        }
1270                        packages = new String[size];
1271                        components = new ArrayList[size];
1272                        uids = new int[size];
1273                        int i = 0;  // filling out the above arrays
1274
1275                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1276                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1277                            Iterator<Map.Entry<String, ArrayList<String>>> it
1278                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1279                                            .entrySet().iterator();
1280                            while (it.hasNext() && i < size) {
1281                                Map.Entry<String, ArrayList<String>> ent = it.next();
1282                                packages[i] = ent.getKey();
1283                                components[i] = ent.getValue();
1284                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1285                                uids[i] = (ps != null)
1286                                        ? UserHandle.getUid(packageUserId, ps.appId)
1287                                        : -1;
1288                                i++;
1289                            }
1290                        }
1291                        size = i;
1292                        mPendingBroadcasts.clear();
1293                    }
1294                    // Send broadcasts
1295                    for (int i = 0; i < size; i++) {
1296                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1297                    }
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1299                    break;
1300                }
1301                case START_CLEANING_PACKAGE: {
1302                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1303                    final String packageName = (String)msg.obj;
1304                    final int userId = msg.arg1;
1305                    final boolean andCode = msg.arg2 != 0;
1306                    synchronized (mPackages) {
1307                        if (userId == UserHandle.USER_ALL) {
1308                            int[] users = sUserManager.getUserIds();
1309                            for (int user : users) {
1310                                mSettings.addPackageToCleanLPw(
1311                                        new PackageCleanItem(user, packageName, andCode));
1312                            }
1313                        } else {
1314                            mSettings.addPackageToCleanLPw(
1315                                    new PackageCleanItem(userId, packageName, andCode));
1316                        }
1317                    }
1318                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1319                    startCleaningPackages();
1320                } break;
1321                case POST_INSTALL: {
1322                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1323                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1324                    mRunningInstalls.delete(msg.arg1);
1325                    boolean deleteOld = false;
1326
1327                    if (data != null) {
1328                        InstallArgs args = data.args;
1329                        PackageInstalledInfo res = data.res;
1330
1331                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1332                            final String packageName = res.pkg.applicationInfo.packageName;
1333                            res.removedInfo.sendBroadcast(false, true, false);
1334                            Bundle extras = new Bundle(1);
1335                            extras.putInt(Intent.EXTRA_UID, res.uid);
1336
1337                            // Now that we successfully installed the package, grant runtime
1338                            // permissions if requested before broadcasting the install.
1339                            if ((args.installFlags
1340                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1341                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1342                                        args.installGrantPermissions);
1343                            }
1344
1345                            // Determine the set of users who are adding this
1346                            // package for the first time vs. those who are seeing
1347                            // an update.
1348                            int[] firstUsers;
1349                            int[] updateUsers = new int[0];
1350                            if (res.origUsers == null || res.origUsers.length == 0) {
1351                                firstUsers = res.newUsers;
1352                            } else {
1353                                firstUsers = new int[0];
1354                                for (int i=0; i<res.newUsers.length; i++) {
1355                                    int user = res.newUsers[i];
1356                                    boolean isNew = true;
1357                                    for (int j=0; j<res.origUsers.length; j++) {
1358                                        if (res.origUsers[j] == user) {
1359                                            isNew = false;
1360                                            break;
1361                                        }
1362                                    }
1363                                    if (isNew) {
1364                                        int[] newFirst = new int[firstUsers.length+1];
1365                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1366                                                firstUsers.length);
1367                                        newFirst[firstUsers.length] = user;
1368                                        firstUsers = newFirst;
1369                                    } else {
1370                                        int[] newUpdate = new int[updateUsers.length+1];
1371                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1372                                                updateUsers.length);
1373                                        newUpdate[updateUsers.length] = user;
1374                                        updateUsers = newUpdate;
1375                                    }
1376                                }
1377                            }
1378                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1379                                    packageName, extras, null, null, firstUsers);
1380                            final boolean update = res.removedInfo.removedPackage != null;
1381                            if (update) {
1382                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1383                            }
1384                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1385                                    packageName, extras, null, null, updateUsers);
1386                            if (update) {
1387                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1388                                        packageName, extras, null, null, updateUsers);
1389                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1390                                        null, null, packageName, null, updateUsers);
1391
1392                                // treat asec-hosted packages like removable media on upgrade
1393                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1394                                    if (DEBUG_INSTALL) {
1395                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1396                                                + " is ASEC-hosted -> AVAILABLE");
1397                                    }
1398                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1399                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1400                                    pkgList.add(packageName);
1401                                    sendResourcesChangedBroadcast(true, true,
1402                                            pkgList,uidArray, null);
1403                                }
1404                            }
1405                            if (res.removedInfo.args != null) {
1406                                // Remove the replaced package's older resources safely now
1407                                deleteOld = true;
1408                            }
1409
1410                            // If this app is a browser and it's newly-installed for some
1411                            // users, clear any default-browser state in those users
1412                            if (firstUsers.length > 0) {
1413                                // the app's nature doesn't depend on the user, so we can just
1414                                // check its browser nature in any user and generalize.
1415                                if (packageIsBrowser(packageName, firstUsers[0])) {
1416                                    synchronized (mPackages) {
1417                                        for (int userId : firstUsers) {
1418                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1419                                        }
1420                                    }
1421                                }
1422                            }
1423                            // Log current value of "unknown sources" setting
1424                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1425                                getUnknownSourcesSettings());
1426                        }
1427                        // Force a gc to clear up things
1428                        Runtime.getRuntime().gc();
1429                        // We delete after a gc for applications  on sdcard.
1430                        if (deleteOld) {
1431                            synchronized (mInstallLock) {
1432                                res.removedInfo.args.doPostDeleteLI(true);
1433                            }
1434                        }
1435                        if (args.observer != null) {
1436                            try {
1437                                Bundle extras = extrasForInstallResult(res);
1438                                args.observer.onPackageInstalled(res.name, res.returnCode,
1439                                        res.returnMsg, extras);
1440                            } catch (RemoteException e) {
1441                                Slog.i(TAG, "Observer no longer exists.");
1442                            }
1443                        }
1444                    } else {
1445                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1446                    }
1447                } break;
1448                case UPDATED_MEDIA_STATUS: {
1449                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1450                    boolean reportStatus = msg.arg1 == 1;
1451                    boolean doGc = msg.arg2 == 1;
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1453                    if (doGc) {
1454                        // Force a gc to clear up stale containers.
1455                        Runtime.getRuntime().gc();
1456                    }
1457                    if (msg.obj != null) {
1458                        @SuppressWarnings("unchecked")
1459                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1460                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1461                        // Unload containers
1462                        unloadAllContainers(args);
1463                    }
1464                    if (reportStatus) {
1465                        try {
1466                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1467                            PackageHelper.getMountService().finishMediaUpdate();
1468                        } catch (RemoteException e) {
1469                            Log.e(TAG, "MountService not running?");
1470                        }
1471                    }
1472                } break;
1473                case WRITE_SETTINGS: {
1474                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1475                    synchronized (mPackages) {
1476                        removeMessages(WRITE_SETTINGS);
1477                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1478                        mSettings.writeLPr();
1479                        mDirtyUsers.clear();
1480                    }
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1482                } break;
1483                case WRITE_PACKAGE_RESTRICTIONS: {
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1485                    synchronized (mPackages) {
1486                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1487                        for (int userId : mDirtyUsers) {
1488                            mSettings.writePackageRestrictionsLPr(userId);
1489                        }
1490                        mDirtyUsers.clear();
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                } break;
1494                case CHECK_PENDING_VERIFICATION: {
1495                    final int verificationId = msg.arg1;
1496                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1497
1498                    if ((state != null) && !state.timeoutExtended()) {
1499                        final InstallArgs args = state.getInstallArgs();
1500                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1501
1502                        Slog.i(TAG, "Verification timed out for " + originUri);
1503                        mPendingVerification.remove(verificationId);
1504
1505                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1506
1507                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1508                            Slog.i(TAG, "Continuing with installation of " + originUri);
1509                            state.setVerifierResponse(Binder.getCallingUid(),
1510                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1511                            broadcastPackageVerified(verificationId, originUri,
1512                                    PackageManager.VERIFICATION_ALLOW,
1513                                    state.getInstallArgs().getUser());
1514                            try {
1515                                ret = args.copyApk(mContainerService, true);
1516                            } catch (RemoteException e) {
1517                                Slog.e(TAG, "Could not contact the ContainerService");
1518                            }
1519                        } else {
1520                            broadcastPackageVerified(verificationId, originUri,
1521                                    PackageManager.VERIFICATION_REJECT,
1522                                    state.getInstallArgs().getUser());
1523                        }
1524
1525                        processPendingInstall(args, ret);
1526                        mHandler.sendEmptyMessage(MCS_UNBIND);
1527                    }
1528                    break;
1529                }
1530                case PACKAGE_VERIFIED: {
1531                    final int verificationId = msg.arg1;
1532
1533                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1534                    if (state == null) {
1535                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1536                        break;
1537                    }
1538
1539                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1540
1541                    state.setVerifierResponse(response.callerUid, response.code);
1542
1543                    if (state.isVerificationComplete()) {
1544                        mPendingVerification.remove(verificationId);
1545
1546                        final InstallArgs args = state.getInstallArgs();
1547                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1548
1549                        int ret;
1550                        if (state.isInstallAllowed()) {
1551                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1552                            broadcastPackageVerified(verificationId, originUri,
1553                                    response.code, state.getInstallArgs().getUser());
1554                            try {
1555                                ret = args.copyApk(mContainerService, true);
1556                            } catch (RemoteException e) {
1557                                Slog.e(TAG, "Could not contact the ContainerService");
1558                            }
1559                        } else {
1560                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1561                        }
1562
1563                        processPendingInstall(args, ret);
1564
1565                        mHandler.sendEmptyMessage(MCS_UNBIND);
1566                    }
1567
1568                    break;
1569                }
1570                case START_INTENT_FILTER_VERIFICATIONS: {
1571                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1572                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1573                            params.replacing, params.pkg);
1574                    break;
1575                }
1576                case INTENT_FILTER_VERIFIED: {
1577                    final int verificationId = msg.arg1;
1578
1579                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1580                            verificationId);
1581                    if (state == null) {
1582                        Slog.w(TAG, "Invalid IntentFilter verification token "
1583                                + verificationId + " received");
1584                        break;
1585                    }
1586
1587                    final int userId = state.getUserId();
1588
1589                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1590                            "Processing IntentFilter verification with token:"
1591                            + verificationId + " and userId:" + userId);
1592
1593                    final IntentFilterVerificationResponse response =
1594                            (IntentFilterVerificationResponse) msg.obj;
1595
1596                    state.setVerifierResponse(response.callerUid, response.code);
1597
1598                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1599                            "IntentFilter verification with token:" + verificationId
1600                            + " and userId:" + userId
1601                            + " is settings verifier response with response code:"
1602                            + response.code);
1603
1604                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1605                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1606                                + response.getFailedDomainsString());
1607                    }
1608
1609                    if (state.isVerificationComplete()) {
1610                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1611                    } else {
1612                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1613                                "IntentFilter verification with token:" + verificationId
1614                                + " was not said to be complete");
1615                    }
1616
1617                    break;
1618                }
1619            }
1620        }
1621    }
1622
1623    private StorageEventListener mStorageListener = new StorageEventListener() {
1624        @Override
1625        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1626            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1627                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1628                    final String volumeUuid = vol.getFsUuid();
1629
1630                    // Clean up any users or apps that were removed or recreated
1631                    // while this volume was missing
1632                    reconcileUsers(volumeUuid);
1633                    reconcileApps(volumeUuid);
1634
1635                    // Clean up any install sessions that expired or were
1636                    // cancelled while this volume was missing
1637                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1638
1639                    loadPrivatePackages(vol);
1640
1641                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1642                    unloadPrivatePackages(vol);
1643                }
1644            }
1645
1646            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1647                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1648                    updateExternalMediaStatus(true, false);
1649                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1650                    updateExternalMediaStatus(false, false);
1651                }
1652            }
1653        }
1654
1655        @Override
1656        public void onVolumeForgotten(String fsUuid) {
1657            if (TextUtils.isEmpty(fsUuid)) {
1658                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1659                return;
1660            }
1661
1662            // Remove any apps installed on the forgotten volume
1663            synchronized (mPackages) {
1664                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1665                for (PackageSetting ps : packages) {
1666                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1667                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1668                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1669                }
1670
1671                mSettings.onVolumeForgotten(fsUuid);
1672                mSettings.writeLPr();
1673            }
1674        }
1675    };
1676
1677    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1678            String[] grantedPermissions) {
1679        if (userId >= UserHandle.USER_OWNER) {
1680            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1681        } else if (userId == UserHandle.USER_ALL) {
1682            final int[] userIds;
1683            synchronized (mPackages) {
1684                userIds = UserManagerService.getInstance().getUserIds();
1685            }
1686            for (int someUserId : userIds) {
1687                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1688            }
1689        }
1690
1691        // We could have touched GID membership, so flush out packages.list
1692        synchronized (mPackages) {
1693            mSettings.writePackageListLPr();
1694        }
1695    }
1696
1697    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1698            String[] grantedPermissions) {
1699        SettingBase sb = (SettingBase) pkg.mExtras;
1700        if (sb == null) {
1701            return;
1702        }
1703
1704        PermissionsState permissionsState = sb.getPermissionsState();
1705
1706        for (String permission : pkg.requestedPermissions) {
1707            BasePermission bp = mSettings.mPermissions.get(permission);
1708            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1709                    || ArrayUtils.contains(grantedPermissions, permission))) {
1710                permissionsState.grantRuntimePermission(bp, userId);
1711            }
1712        }
1713    }
1714
1715    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1716        Bundle extras = null;
1717        switch (res.returnCode) {
1718            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1719                extras = new Bundle();
1720                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1721                        res.origPermission);
1722                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1723                        res.origPackage);
1724                break;
1725            }
1726            case PackageManager.INSTALL_SUCCEEDED: {
1727                extras = new Bundle();
1728                extras.putBoolean(Intent.EXTRA_REPLACING,
1729                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1730                break;
1731            }
1732        }
1733        return extras;
1734    }
1735
1736    void scheduleWriteSettingsLocked() {
1737        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1738            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1739        }
1740    }
1741
1742    void scheduleWritePackageRestrictionsLocked(int userId) {
1743        if (!sUserManager.exists(userId)) return;
1744        mDirtyUsers.add(userId);
1745        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1746            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1747        }
1748    }
1749
1750    public static PackageManagerService main(Context context, Installer installer,
1751            boolean factoryTest, boolean onlyCore) {
1752        PackageManagerService m = new PackageManagerService(context, installer,
1753                factoryTest, onlyCore);
1754        ServiceManager.addService("package", m);
1755        return m;
1756    }
1757
1758    static String[] splitString(String str, char sep) {
1759        int count = 1;
1760        int i = 0;
1761        while ((i=str.indexOf(sep, i)) >= 0) {
1762            count++;
1763            i++;
1764        }
1765
1766        String[] res = new String[count];
1767        i=0;
1768        count = 0;
1769        int lastI=0;
1770        while ((i=str.indexOf(sep, i)) >= 0) {
1771            res[count] = str.substring(lastI, i);
1772            count++;
1773            i++;
1774            lastI = i;
1775        }
1776        res[count] = str.substring(lastI, str.length());
1777        return res;
1778    }
1779
1780    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1781        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1782                Context.DISPLAY_SERVICE);
1783        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1784    }
1785
1786    public PackageManagerService(Context context, Installer installer,
1787            boolean factoryTest, boolean onlyCore) {
1788        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1789                SystemClock.uptimeMillis());
1790
1791        if (mSdkVersion <= 0) {
1792            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1793        }
1794
1795        mContext = context;
1796        mFactoryTest = factoryTest;
1797        mOnlyCore = onlyCore;
1798        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1799        mMetrics = new DisplayMetrics();
1800        mSettings = new Settings(mPackages);
1801        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1802                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1803        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1804                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1805        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1806                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1807        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1808                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1809        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1810                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1811        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1812                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1813
1814        // TODO: add a property to control this?
1815        long dexOptLRUThresholdInMinutes;
1816        if (mLazyDexOpt) {
1817            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1818        } else {
1819            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1820        }
1821        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1822
1823        String separateProcesses = SystemProperties.get("debug.separate_processes");
1824        if (separateProcesses != null && separateProcesses.length() > 0) {
1825            if ("*".equals(separateProcesses)) {
1826                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1827                mSeparateProcesses = null;
1828                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1829            } else {
1830                mDefParseFlags = 0;
1831                mSeparateProcesses = separateProcesses.split(",");
1832                Slog.w(TAG, "Running with debug.separate_processes: "
1833                        + separateProcesses);
1834            }
1835        } else {
1836            mDefParseFlags = 0;
1837            mSeparateProcesses = null;
1838        }
1839
1840        mInstaller = installer;
1841        mPackageDexOptimizer = new PackageDexOptimizer(this);
1842        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1843
1844        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1845                FgThread.get().getLooper());
1846
1847        getDefaultDisplayMetrics(context, mMetrics);
1848
1849        SystemConfig systemConfig = SystemConfig.getInstance();
1850        mGlobalGids = systemConfig.getGlobalGids();
1851        mSystemPermissions = systemConfig.getSystemPermissions();
1852        mAvailableFeatures = systemConfig.getAvailableFeatures();
1853
1854        synchronized (mInstallLock) {
1855        // writer
1856        synchronized (mPackages) {
1857            mHandlerThread = new ServiceThread(TAG,
1858                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1859            mHandlerThread.start();
1860            mHandler = new PackageHandler(mHandlerThread.getLooper());
1861            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1862
1863            File dataDir = Environment.getDataDirectory();
1864            mAppDataDir = new File(dataDir, "data");
1865            mAppInstallDir = new File(dataDir, "app");
1866            mAppLib32InstallDir = new File(dataDir, "app-lib");
1867            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1868            mUserAppDataDir = new File(dataDir, "user");
1869            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1870
1871            sUserManager = new UserManagerService(context, this,
1872                    mInstallLock, mPackages);
1873
1874            // Propagate permission configuration in to package manager.
1875            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1876                    = systemConfig.getPermissions();
1877            for (int i=0; i<permConfig.size(); i++) {
1878                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1879                BasePermission bp = mSettings.mPermissions.get(perm.name);
1880                if (bp == null) {
1881                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1882                    mSettings.mPermissions.put(perm.name, bp);
1883                }
1884                if (perm.gids != null) {
1885                    bp.setGids(perm.gids, perm.perUser);
1886                }
1887            }
1888
1889            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1890            for (int i=0; i<libConfig.size(); i++) {
1891                mSharedLibraries.put(libConfig.keyAt(i),
1892                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1893            }
1894
1895            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1896
1897            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1898                    mSdkVersion, mOnlyCore);
1899
1900            String customResolverActivity = Resources.getSystem().getString(
1901                    R.string.config_customResolverActivity);
1902            if (TextUtils.isEmpty(customResolverActivity)) {
1903                customResolverActivity = null;
1904            } else {
1905                mCustomResolverComponentName = ComponentName.unflattenFromString(
1906                        customResolverActivity);
1907            }
1908
1909            long startTime = SystemClock.uptimeMillis();
1910
1911            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1912                    startTime);
1913
1914            // Set flag to monitor and not change apk file paths when
1915            // scanning install directories.
1916            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1917
1918            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1919
1920            /**
1921             * Add everything in the in the boot class path to the
1922             * list of process files because dexopt will have been run
1923             * if necessary during zygote startup.
1924             */
1925            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1926            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1927
1928            if (bootClassPath != null) {
1929                String[] bootClassPathElements = splitString(bootClassPath, ':');
1930                for (String element : bootClassPathElements) {
1931                    alreadyDexOpted.add(element);
1932                }
1933            } else {
1934                Slog.w(TAG, "No BOOTCLASSPATH found!");
1935            }
1936
1937            if (systemServerClassPath != null) {
1938                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1939                for (String element : systemServerClassPathElements) {
1940                    alreadyDexOpted.add(element);
1941                }
1942            } else {
1943                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1944            }
1945
1946            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1947            final String[] dexCodeInstructionSets =
1948                    getDexCodeInstructionSets(
1949                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1950
1951            /**
1952             * Ensure all external libraries have had dexopt run on them.
1953             */
1954            if (mSharedLibraries.size() > 0) {
1955                // NOTE: For now, we're compiling these system "shared libraries"
1956                // (and framework jars) into all available architectures. It's possible
1957                // to compile them only when we come across an app that uses them (there's
1958                // already logic for that in scanPackageLI) but that adds some complexity.
1959                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1960                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1961                        final String lib = libEntry.path;
1962                        if (lib == null) {
1963                            continue;
1964                        }
1965
1966                        try {
1967                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1968                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1969                                alreadyDexOpted.add(lib);
1970                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1971                            }
1972                        } catch (FileNotFoundException e) {
1973                            Slog.w(TAG, "Library not found: " + lib);
1974                        } catch (IOException e) {
1975                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1976                                    + e.getMessage());
1977                        }
1978                    }
1979                }
1980            }
1981
1982            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1983
1984            // Gross hack for now: we know this file doesn't contain any
1985            // code, so don't dexopt it to avoid the resulting log spew.
1986            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1987
1988            // Gross hack for now: we know this file is only part of
1989            // the boot class path for art, so don't dexopt it to
1990            // avoid the resulting log spew.
1991            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1992
1993            /**
1994             * There are a number of commands implemented in Java, which
1995             * we currently need to do the dexopt on so that they can be
1996             * run from a non-root shell.
1997             */
1998            String[] frameworkFiles = frameworkDir.list();
1999            if (frameworkFiles != null) {
2000                // TODO: We could compile these only for the most preferred ABI. We should
2001                // first double check that the dex files for these commands are not referenced
2002                // by other system apps.
2003                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2004                    for (int i=0; i<frameworkFiles.length; i++) {
2005                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2006                        String path = libPath.getPath();
2007                        // Skip the file if we already did it.
2008                        if (alreadyDexOpted.contains(path)) {
2009                            continue;
2010                        }
2011                        // Skip the file if it is not a type we want to dexopt.
2012                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2013                            continue;
2014                        }
2015                        try {
2016                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2017                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2018                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2019                            }
2020                        } catch (FileNotFoundException e) {
2021                            Slog.w(TAG, "Jar not found: " + path);
2022                        } catch (IOException e) {
2023                            Slog.w(TAG, "Exception reading jar: " + path, e);
2024                        }
2025                    }
2026                }
2027            }
2028
2029            // Collect vendor overlay packages.
2030            // (Do this before scanning any apps.)
2031            // For security and version matching reason, only consider
2032            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2033            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2034            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2035                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2036
2037            // Find base frameworks (resource packages without code).
2038            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2039                    | PackageParser.PARSE_IS_SYSTEM_DIR
2040                    | PackageParser.PARSE_IS_PRIVILEGED,
2041                    scanFlags | SCAN_NO_DEX, 0);
2042
2043            // Collected privileged system packages.
2044            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2045            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2046                    | PackageParser.PARSE_IS_SYSTEM_DIR
2047                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2048
2049            // Collect ordinary system packages.
2050            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2051            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2052                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2053
2054            // Collect all vendor packages.
2055            File vendorAppDir = new File("/vendor/app");
2056            try {
2057                vendorAppDir = vendorAppDir.getCanonicalFile();
2058            } catch (IOException e) {
2059                // failed to look up canonical path, continue with original one
2060            }
2061            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2062                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2063
2064            // Collect all OEM packages.
2065            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2066            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2067                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2068
2069            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2070            mInstaller.moveFiles();
2071
2072            // Prune any system packages that no longer exist.
2073            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2074            if (!mOnlyCore) {
2075                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2076                while (psit.hasNext()) {
2077                    PackageSetting ps = psit.next();
2078
2079                    /*
2080                     * If this is not a system app, it can't be a
2081                     * disable system app.
2082                     */
2083                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2084                        continue;
2085                    }
2086
2087                    /*
2088                     * If the package is scanned, it's not erased.
2089                     */
2090                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2091                    if (scannedPkg != null) {
2092                        /*
2093                         * If the system app is both scanned and in the
2094                         * disabled packages list, then it must have been
2095                         * added via OTA. Remove it from the currently
2096                         * scanned package so the previously user-installed
2097                         * application can be scanned.
2098                         */
2099                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2100                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2101                                    + ps.name + "; removing system app.  Last known codePath="
2102                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2103                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2104                                    + scannedPkg.mVersionCode);
2105                            removePackageLI(ps, true);
2106                            mExpectingBetter.put(ps.name, ps.codePath);
2107                        }
2108
2109                        continue;
2110                    }
2111
2112                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2113                        psit.remove();
2114                        logCriticalInfo(Log.WARN, "System package " + ps.name
2115                                + " no longer exists; wiping its data");
2116                        removeDataDirsLI(null, ps.name);
2117                    } else {
2118                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2119                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2120                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2121                        }
2122                    }
2123                }
2124            }
2125
2126            //look for any incomplete package installations
2127            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2128            //clean up list
2129            for(int i = 0; i < deletePkgsList.size(); i++) {
2130                //clean up here
2131                cleanupInstallFailedPackage(deletePkgsList.get(i));
2132            }
2133            //delete tmp files
2134            deleteTempPackageFiles();
2135
2136            // Remove any shared userIDs that have no associated packages
2137            mSettings.pruneSharedUsersLPw();
2138
2139            if (!mOnlyCore) {
2140                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2141                        SystemClock.uptimeMillis());
2142                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2143
2144                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2145                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2146
2147                /**
2148                 * Remove disable package settings for any updated system
2149                 * apps that were removed via an OTA. If they're not a
2150                 * previously-updated app, remove them completely.
2151                 * Otherwise, just revoke their system-level permissions.
2152                 */
2153                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2154                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2155                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2156
2157                    String msg;
2158                    if (deletedPkg == null) {
2159                        msg = "Updated system package " + deletedAppName
2160                                + " no longer exists; wiping its data";
2161                        removeDataDirsLI(null, deletedAppName);
2162                    } else {
2163                        msg = "Updated system app + " + deletedAppName
2164                                + " no longer present; removing system privileges for "
2165                                + deletedAppName;
2166
2167                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2168
2169                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2170                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2171                    }
2172                    logCriticalInfo(Log.WARN, msg);
2173                }
2174
2175                /**
2176                 * Make sure all system apps that we expected to appear on
2177                 * the userdata partition actually showed up. If they never
2178                 * appeared, crawl back and revive the system version.
2179                 */
2180                for (int i = 0; i < mExpectingBetter.size(); i++) {
2181                    final String packageName = mExpectingBetter.keyAt(i);
2182                    if (!mPackages.containsKey(packageName)) {
2183                        final File scanFile = mExpectingBetter.valueAt(i);
2184
2185                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2186                                + " but never showed up; reverting to system");
2187
2188                        final int reparseFlags;
2189                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2190                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2191                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2192                                    | PackageParser.PARSE_IS_PRIVILEGED;
2193                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2194                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2195                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2196                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2197                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2198                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2199                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2200                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2201                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2202                        } else {
2203                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2204                            continue;
2205                        }
2206
2207                        mSettings.enableSystemPackageLPw(packageName);
2208
2209                        try {
2210                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2211                        } catch (PackageManagerException e) {
2212                            Slog.e(TAG, "Failed to parse original system package: "
2213                                    + e.getMessage());
2214                        }
2215                    }
2216                }
2217            }
2218            mExpectingBetter.clear();
2219
2220            // Now that we know all of the shared libraries, update all clients to have
2221            // the correct library paths.
2222            updateAllSharedLibrariesLPw();
2223
2224            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2225                // NOTE: We ignore potential failures here during a system scan (like
2226                // the rest of the commands above) because there's precious little we
2227                // can do about it. A settings error is reported, though.
2228                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2229                        false /* force dexopt */, false /* defer dexopt */);
2230            }
2231
2232            // Now that we know all the packages we are keeping,
2233            // read and update their last usage times.
2234            mPackageUsage.readLP();
2235
2236            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2237                    SystemClock.uptimeMillis());
2238            Slog.i(TAG, "Time to scan packages: "
2239                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2240                    + " seconds");
2241
2242            // If the platform SDK has changed since the last time we booted,
2243            // we need to re-grant app permission to catch any new ones that
2244            // appear.  This is really a hack, and means that apps can in some
2245            // cases get permissions that the user didn't initially explicitly
2246            // allow...  it would be nice to have some better way to handle
2247            // this situation.
2248            final VersionInfo ver = mSettings.getInternalVersion();
2249
2250            int updateFlags = UPDATE_PERMISSIONS_ALL;
2251            if (ver.sdkVersion != mSdkVersion) {
2252                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2253                        + mSdkVersion + "; regranting permissions for internal storage");
2254                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2255            }
2256            updatePermissionsLPw(null, null, updateFlags);
2257            ver.sdkVersion = mSdkVersion;
2258
2259            // If this is the first boot, and it is a normal boot, then
2260            // we need to initialize the default preferred apps.
2261            if (!mRestoredSettings && !onlyCore) {
2262                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2263                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2264                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2265            }
2266
2267            // If this is first boot after an OTA, and a normal boot, then
2268            // we need to clear code cache directories.
2269            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2270            if (mIsUpgrade && !onlyCore) {
2271                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2272                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2273                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2274                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2275                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2276                    }
2277                }
2278                ver.fingerprint = Build.FINGERPRINT;
2279            }
2280
2281            checkDefaultBrowser();
2282
2283            // All the changes are done during package scanning.
2284            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2285
2286            // can downgrade to reader
2287            mSettings.writeLPr();
2288
2289            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2290                    SystemClock.uptimeMillis());
2291
2292            mRequiredVerifierPackage = getRequiredVerifierLPr();
2293            mRequiredInstallerPackage = getRequiredInstallerLPr();
2294
2295            mInstallerService = new PackageInstallerService(context, this);
2296
2297            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2298            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2299                    mIntentFilterVerifierComponent);
2300
2301        } // synchronized (mPackages)
2302        } // synchronized (mInstallLock)
2303
2304        // Now after opening every single application zip, make sure they
2305        // are all flushed.  Not really needed, but keeps things nice and
2306        // tidy.
2307        Runtime.getRuntime().gc();
2308
2309        // Expose private service for system components to use.
2310        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2311    }
2312
2313    @Override
2314    public boolean isFirstBoot() {
2315        return !mRestoredSettings;
2316    }
2317
2318    @Override
2319    public boolean isOnlyCoreApps() {
2320        return mOnlyCore;
2321    }
2322
2323    @Override
2324    public boolean isUpgrade() {
2325        return mIsUpgrade;
2326    }
2327
2328    private String getRequiredVerifierLPr() {
2329        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2330        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2331                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2332
2333        String requiredVerifier = null;
2334
2335        final int N = receivers.size();
2336        for (int i = 0; i < N; i++) {
2337            final ResolveInfo info = receivers.get(i);
2338
2339            if (info.activityInfo == null) {
2340                continue;
2341            }
2342
2343            final String packageName = info.activityInfo.packageName;
2344
2345            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2346                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2347                continue;
2348            }
2349
2350            if (requiredVerifier != null) {
2351                throw new RuntimeException("There can be only one required verifier");
2352            }
2353
2354            requiredVerifier = packageName;
2355        }
2356
2357        return requiredVerifier;
2358    }
2359
2360    private String getRequiredInstallerLPr() {
2361        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2362        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2363        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2364
2365        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2366                PACKAGE_MIME_TYPE, 0, 0);
2367
2368        String requiredInstaller = null;
2369
2370        final int N = installers.size();
2371        for (int i = 0; i < N; i++) {
2372            final ResolveInfo info = installers.get(i);
2373            final String packageName = info.activityInfo.packageName;
2374
2375            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2376                continue;
2377            }
2378
2379            if (requiredInstaller != null) {
2380                throw new RuntimeException("There must be one required installer");
2381            }
2382
2383            requiredInstaller = packageName;
2384        }
2385
2386        if (requiredInstaller == null) {
2387            throw new RuntimeException("There must be one required installer");
2388        }
2389
2390        return requiredInstaller;
2391    }
2392
2393    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2394        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2395        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2396                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2397
2398        ComponentName verifierComponentName = null;
2399
2400        int priority = -1000;
2401        final int N = receivers.size();
2402        for (int i = 0; i < N; i++) {
2403            final ResolveInfo info = receivers.get(i);
2404
2405            if (info.activityInfo == null) {
2406                continue;
2407            }
2408
2409            final String packageName = info.activityInfo.packageName;
2410
2411            final PackageSetting ps = mSettings.mPackages.get(packageName);
2412            if (ps == null) {
2413                continue;
2414            }
2415
2416            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2417                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2418                continue;
2419            }
2420
2421            // Select the IntentFilterVerifier with the highest priority
2422            if (priority < info.priority) {
2423                priority = info.priority;
2424                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2425                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2426                        + verifierComponentName + " with priority: " + info.priority);
2427            }
2428        }
2429
2430        return verifierComponentName;
2431    }
2432
2433    private void primeDomainVerificationsLPw(int userId) {
2434        if (DEBUG_DOMAIN_VERIFICATION) {
2435            Slog.d(TAG, "Priming domain verifications in user " + userId);
2436        }
2437
2438        SystemConfig systemConfig = SystemConfig.getInstance();
2439        ArraySet<String> packages = systemConfig.getLinkedApps();
2440        ArraySet<String> domains = new ArraySet<String>();
2441
2442        for (String packageName : packages) {
2443            PackageParser.Package pkg = mPackages.get(packageName);
2444            if (pkg != null) {
2445                if (!pkg.isSystemApp()) {
2446                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2447                    continue;
2448                }
2449
2450                domains.clear();
2451                for (PackageParser.Activity a : pkg.activities) {
2452                    for (ActivityIntentInfo filter : a.intents) {
2453                        if (hasValidDomains(filter)) {
2454                            domains.addAll(filter.getHostsList());
2455                        }
2456                    }
2457                }
2458
2459                if (domains.size() > 0) {
2460                    if (DEBUG_DOMAIN_VERIFICATION) {
2461                        Slog.v(TAG, "      + " + packageName);
2462                    }
2463                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2464                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2465                    // and then 'always' in the per-user state actually used for intent resolution.
2466                    final IntentFilterVerificationInfo ivi;
2467                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2468                            new ArrayList<String>(domains));
2469                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2470                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2471                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2472                } else {
2473                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2474                            + "' does not handle web links");
2475                }
2476            } else {
2477                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2478            }
2479        }
2480
2481        scheduleWritePackageRestrictionsLocked(userId);
2482        scheduleWriteSettingsLocked();
2483    }
2484
2485    private void applyFactoryDefaultBrowserLPw(int userId) {
2486        // The default browser app's package name is stored in a string resource,
2487        // with a product-specific overlay used for vendor customization.
2488        String browserPkg = mContext.getResources().getString(
2489                com.android.internal.R.string.default_browser);
2490        if (!TextUtils.isEmpty(browserPkg)) {
2491            // non-empty string => required to be a known package
2492            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2493            if (ps == null) {
2494                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2495                browserPkg = null;
2496            } else {
2497                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2498            }
2499        }
2500
2501        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2502        // default.  If there's more than one, just leave everything alone.
2503        if (browserPkg == null) {
2504            calculateDefaultBrowserLPw(userId);
2505        }
2506    }
2507
2508    private void calculateDefaultBrowserLPw(int userId) {
2509        List<String> allBrowsers = resolveAllBrowserApps(userId);
2510        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2511        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2512    }
2513
2514    private List<String> resolveAllBrowserApps(int userId) {
2515        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2516        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2517                PackageManager.MATCH_ALL, userId);
2518
2519        final int count = list.size();
2520        List<String> result = new ArrayList<String>(count);
2521        for (int i=0; i<count; i++) {
2522            ResolveInfo info = list.get(i);
2523            if (info.activityInfo == null
2524                    || !info.handleAllWebDataURI
2525                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2526                    || result.contains(info.activityInfo.packageName)) {
2527                continue;
2528            }
2529            result.add(info.activityInfo.packageName);
2530        }
2531
2532        return result;
2533    }
2534
2535    private boolean packageIsBrowser(String packageName, int userId) {
2536        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2537                PackageManager.MATCH_ALL, userId);
2538        final int N = list.size();
2539        for (int i = 0; i < N; i++) {
2540            ResolveInfo info = list.get(i);
2541            if (packageName.equals(info.activityInfo.packageName)) {
2542                return true;
2543            }
2544        }
2545        return false;
2546    }
2547
2548    private void checkDefaultBrowser() {
2549        final int myUserId = UserHandle.myUserId();
2550        final String packageName = getDefaultBrowserPackageName(myUserId);
2551        if (packageName != null) {
2552            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2553            if (info == null) {
2554                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2555                synchronized (mPackages) {
2556                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2557                }
2558            }
2559        }
2560    }
2561
2562    @Override
2563    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2564            throws RemoteException {
2565        try {
2566            return super.onTransact(code, data, reply, flags);
2567        } catch (RuntimeException e) {
2568            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2569                Slog.wtf(TAG, "Package Manager Crash", e);
2570            }
2571            throw e;
2572        }
2573    }
2574
2575    void cleanupInstallFailedPackage(PackageSetting ps) {
2576        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2577
2578        removeDataDirsLI(ps.volumeUuid, ps.name);
2579        if (ps.codePath != null) {
2580            if (ps.codePath.isDirectory()) {
2581                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2582            } else {
2583                ps.codePath.delete();
2584            }
2585        }
2586        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2587            if (ps.resourcePath.isDirectory()) {
2588                FileUtils.deleteContents(ps.resourcePath);
2589            }
2590            ps.resourcePath.delete();
2591        }
2592        mSettings.removePackageLPw(ps.name);
2593    }
2594
2595    static int[] appendInts(int[] cur, int[] add) {
2596        if (add == null) return cur;
2597        if (cur == null) return add;
2598        final int N = add.length;
2599        for (int i=0; i<N; i++) {
2600            cur = appendInt(cur, add[i]);
2601        }
2602        return cur;
2603    }
2604
2605    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2606        if (!sUserManager.exists(userId)) return null;
2607        final PackageSetting ps = (PackageSetting) p.mExtras;
2608        if (ps == null) {
2609            return null;
2610        }
2611
2612        final PermissionsState permissionsState = ps.getPermissionsState();
2613
2614        final int[] gids = permissionsState.computeGids(userId);
2615        final Set<String> permissions = permissionsState.getPermissions(userId);
2616        final PackageUserState state = ps.readUserState(userId);
2617
2618        return PackageParser.generatePackageInfo(p, gids, flags,
2619                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2620    }
2621
2622    @Override
2623    public boolean isPackageFrozen(String packageName) {
2624        synchronized (mPackages) {
2625            final PackageSetting ps = mSettings.mPackages.get(packageName);
2626            if (ps != null) {
2627                return ps.frozen;
2628            }
2629        }
2630        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2631        return true;
2632    }
2633
2634    @Override
2635    public boolean isPackageAvailable(String packageName, int userId) {
2636        if (!sUserManager.exists(userId)) return false;
2637        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2638        synchronized (mPackages) {
2639            PackageParser.Package p = mPackages.get(packageName);
2640            if (p != null) {
2641                final PackageSetting ps = (PackageSetting) p.mExtras;
2642                if (ps != null) {
2643                    final PackageUserState state = ps.readUserState(userId);
2644                    if (state != null) {
2645                        return PackageParser.isAvailable(state);
2646                    }
2647                }
2648            }
2649        }
2650        return false;
2651    }
2652
2653    @Override
2654    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2655        if (!sUserManager.exists(userId)) return null;
2656        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2657        // reader
2658        synchronized (mPackages) {
2659            PackageParser.Package p = mPackages.get(packageName);
2660            if (DEBUG_PACKAGE_INFO)
2661                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2662            if (p != null) {
2663                return generatePackageInfo(p, flags, userId);
2664            }
2665            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2666                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2667            }
2668        }
2669        return null;
2670    }
2671
2672    @Override
2673    public String[] currentToCanonicalPackageNames(String[] names) {
2674        String[] out = new String[names.length];
2675        // reader
2676        synchronized (mPackages) {
2677            for (int i=names.length-1; i>=0; i--) {
2678                PackageSetting ps = mSettings.mPackages.get(names[i]);
2679                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2680            }
2681        }
2682        return out;
2683    }
2684
2685    @Override
2686    public String[] canonicalToCurrentPackageNames(String[] names) {
2687        String[] out = new String[names.length];
2688        // reader
2689        synchronized (mPackages) {
2690            for (int i=names.length-1; i>=0; i--) {
2691                String cur = mSettings.mRenamedPackages.get(names[i]);
2692                out[i] = cur != null ? cur : names[i];
2693            }
2694        }
2695        return out;
2696    }
2697
2698    @Override
2699    public int getPackageUid(String packageName, int userId) {
2700        if (!sUserManager.exists(userId)) return -1;
2701        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2702
2703        // reader
2704        synchronized (mPackages) {
2705            PackageParser.Package p = mPackages.get(packageName);
2706            if(p != null) {
2707                return UserHandle.getUid(userId, p.applicationInfo.uid);
2708            }
2709            PackageSetting ps = mSettings.mPackages.get(packageName);
2710            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2711                return -1;
2712            }
2713            p = ps.pkg;
2714            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2715        }
2716    }
2717
2718    @Override
2719    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2720        if (!sUserManager.exists(userId)) {
2721            return null;
2722        }
2723
2724        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2725                "getPackageGids");
2726
2727        // reader
2728        synchronized (mPackages) {
2729            PackageParser.Package p = mPackages.get(packageName);
2730            if (DEBUG_PACKAGE_INFO) {
2731                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2732            }
2733            if (p != null) {
2734                PackageSetting ps = (PackageSetting) p.mExtras;
2735                return ps.getPermissionsState().computeGids(userId);
2736            }
2737        }
2738
2739        return null;
2740    }
2741
2742    static PermissionInfo generatePermissionInfo(
2743            BasePermission bp, int flags) {
2744        if (bp.perm != null) {
2745            return PackageParser.generatePermissionInfo(bp.perm, flags);
2746        }
2747        PermissionInfo pi = new PermissionInfo();
2748        pi.name = bp.name;
2749        pi.packageName = bp.sourcePackage;
2750        pi.nonLocalizedLabel = bp.name;
2751        pi.protectionLevel = bp.protectionLevel;
2752        return pi;
2753    }
2754
2755    @Override
2756    public PermissionInfo getPermissionInfo(String name, int flags) {
2757        // reader
2758        synchronized (mPackages) {
2759            final BasePermission p = mSettings.mPermissions.get(name);
2760            if (p != null) {
2761                return generatePermissionInfo(p, flags);
2762            }
2763            return null;
2764        }
2765    }
2766
2767    @Override
2768    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2769        // reader
2770        synchronized (mPackages) {
2771            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2772            for (BasePermission p : mSettings.mPermissions.values()) {
2773                if (group == null) {
2774                    if (p.perm == null || p.perm.info.group == null) {
2775                        out.add(generatePermissionInfo(p, flags));
2776                    }
2777                } else {
2778                    if (p.perm != null && group.equals(p.perm.info.group)) {
2779                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2780                    }
2781                }
2782            }
2783
2784            if (out.size() > 0) {
2785                return out;
2786            }
2787            return mPermissionGroups.containsKey(group) ? out : null;
2788        }
2789    }
2790
2791    @Override
2792    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2793        // reader
2794        synchronized (mPackages) {
2795            return PackageParser.generatePermissionGroupInfo(
2796                    mPermissionGroups.get(name), flags);
2797        }
2798    }
2799
2800    @Override
2801    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2802        // reader
2803        synchronized (mPackages) {
2804            final int N = mPermissionGroups.size();
2805            ArrayList<PermissionGroupInfo> out
2806                    = new ArrayList<PermissionGroupInfo>(N);
2807            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2808                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2809            }
2810            return out;
2811        }
2812    }
2813
2814    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2815            int userId) {
2816        if (!sUserManager.exists(userId)) return null;
2817        PackageSetting ps = mSettings.mPackages.get(packageName);
2818        if (ps != null) {
2819            if (ps.pkg == null) {
2820                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2821                        flags, userId);
2822                if (pInfo != null) {
2823                    return pInfo.applicationInfo;
2824                }
2825                return null;
2826            }
2827            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2828                    ps.readUserState(userId), userId);
2829        }
2830        return null;
2831    }
2832
2833    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2834            int userId) {
2835        if (!sUserManager.exists(userId)) return null;
2836        PackageSetting ps = mSettings.mPackages.get(packageName);
2837        if (ps != null) {
2838            PackageParser.Package pkg = ps.pkg;
2839            if (pkg == null) {
2840                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2841                    return null;
2842                }
2843                // Only data remains, so we aren't worried about code paths
2844                pkg = new PackageParser.Package(packageName);
2845                pkg.applicationInfo.packageName = packageName;
2846                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2847                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2848                pkg.applicationInfo.dataDir = Environment
2849                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2850                        .getAbsolutePath();
2851                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2852                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2853            }
2854            return generatePackageInfo(pkg, flags, userId);
2855        }
2856        return null;
2857    }
2858
2859    @Override
2860    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2861        if (!sUserManager.exists(userId)) return null;
2862        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2863        // writer
2864        synchronized (mPackages) {
2865            PackageParser.Package p = mPackages.get(packageName);
2866            if (DEBUG_PACKAGE_INFO) Log.v(
2867                    TAG, "getApplicationInfo " + packageName
2868                    + ": " + p);
2869            if (p != null) {
2870                PackageSetting ps = mSettings.mPackages.get(packageName);
2871                if (ps == null) return null;
2872                // Note: isEnabledLP() does not apply here - always return info
2873                return PackageParser.generateApplicationInfo(
2874                        p, flags, ps.readUserState(userId), userId);
2875            }
2876            if ("android".equals(packageName)||"system".equals(packageName)) {
2877                return mAndroidApplication;
2878            }
2879            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2880                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2881            }
2882        }
2883        return null;
2884    }
2885
2886    @Override
2887    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2888            final IPackageDataObserver observer) {
2889        mContext.enforceCallingOrSelfPermission(
2890                android.Manifest.permission.CLEAR_APP_CACHE, null);
2891        // Queue up an async operation since clearing cache may take a little while.
2892        mHandler.post(new Runnable() {
2893            public void run() {
2894                mHandler.removeCallbacks(this);
2895                int retCode = -1;
2896                synchronized (mInstallLock) {
2897                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2898                    if (retCode < 0) {
2899                        Slog.w(TAG, "Couldn't clear application caches");
2900                    }
2901                }
2902                if (observer != null) {
2903                    try {
2904                        observer.onRemoveCompleted(null, (retCode >= 0));
2905                    } catch (RemoteException e) {
2906                        Slog.w(TAG, "RemoveException when invoking call back");
2907                    }
2908                }
2909            }
2910        });
2911    }
2912
2913    @Override
2914    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2915            final IntentSender pi) {
2916        mContext.enforceCallingOrSelfPermission(
2917                android.Manifest.permission.CLEAR_APP_CACHE, null);
2918        // Queue up an async operation since clearing cache may take a little while.
2919        mHandler.post(new Runnable() {
2920            public void run() {
2921                mHandler.removeCallbacks(this);
2922                int retCode = -1;
2923                synchronized (mInstallLock) {
2924                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2925                    if (retCode < 0) {
2926                        Slog.w(TAG, "Couldn't clear application caches");
2927                    }
2928                }
2929                if(pi != null) {
2930                    try {
2931                        // Callback via pending intent
2932                        int code = (retCode >= 0) ? 1 : 0;
2933                        pi.sendIntent(null, code, null,
2934                                null, null);
2935                    } catch (SendIntentException e1) {
2936                        Slog.i(TAG, "Failed to send pending intent");
2937                    }
2938                }
2939            }
2940        });
2941    }
2942
2943    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2944        synchronized (mInstallLock) {
2945            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2946                throw new IOException("Failed to free enough space");
2947            }
2948        }
2949    }
2950
2951    @Override
2952    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2953        if (!sUserManager.exists(userId)) return null;
2954        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2955        synchronized (mPackages) {
2956            PackageParser.Activity a = mActivities.mActivities.get(component);
2957
2958            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2959            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2960                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2961                if (ps == null) return null;
2962                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2963                        userId);
2964            }
2965            if (mResolveComponentName.equals(component)) {
2966                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2967                        new PackageUserState(), userId);
2968            }
2969        }
2970        return null;
2971    }
2972
2973    @Override
2974    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2975            String resolvedType) {
2976        synchronized (mPackages) {
2977            if (component.equals(mResolveComponentName)) {
2978                // The resolver supports EVERYTHING!
2979                return true;
2980            }
2981            PackageParser.Activity a = mActivities.mActivities.get(component);
2982            if (a == null) {
2983                return false;
2984            }
2985            for (int i=0; i<a.intents.size(); i++) {
2986                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2987                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2988                    return true;
2989                }
2990            }
2991            return false;
2992        }
2993    }
2994
2995    @Override
2996    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2997        if (!sUserManager.exists(userId)) return null;
2998        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2999        synchronized (mPackages) {
3000            PackageParser.Activity a = mReceivers.mActivities.get(component);
3001            if (DEBUG_PACKAGE_INFO) Log.v(
3002                TAG, "getReceiverInfo " + component + ": " + a);
3003            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3004                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3005                if (ps == null) return null;
3006                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3007                        userId);
3008            }
3009        }
3010        return null;
3011    }
3012
3013    @Override
3014    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3017        synchronized (mPackages) {
3018            PackageParser.Service s = mServices.mServices.get(component);
3019            if (DEBUG_PACKAGE_INFO) Log.v(
3020                TAG, "getServiceInfo " + component + ": " + s);
3021            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3023                if (ps == null) return null;
3024                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3025                        userId);
3026            }
3027        }
3028        return null;
3029    }
3030
3031    @Override
3032    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3033        if (!sUserManager.exists(userId)) return null;
3034        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3035        synchronized (mPackages) {
3036            PackageParser.Provider p = mProviders.mProviders.get(component);
3037            if (DEBUG_PACKAGE_INFO) Log.v(
3038                TAG, "getProviderInfo " + component + ": " + p);
3039            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3040                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3041                if (ps == null) return null;
3042                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3043                        userId);
3044            }
3045        }
3046        return null;
3047    }
3048
3049    @Override
3050    public String[] getSystemSharedLibraryNames() {
3051        Set<String> libSet;
3052        synchronized (mPackages) {
3053            libSet = mSharedLibraries.keySet();
3054            int size = libSet.size();
3055            if (size > 0) {
3056                String[] libs = new String[size];
3057                libSet.toArray(libs);
3058                return libs;
3059            }
3060        }
3061        return null;
3062    }
3063
3064    /**
3065     * @hide
3066     */
3067    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3068        synchronized (mPackages) {
3069            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3070            if (lib != null && lib.apk != null) {
3071                return mPackages.get(lib.apk);
3072            }
3073        }
3074        return null;
3075    }
3076
3077    @Override
3078    public FeatureInfo[] getSystemAvailableFeatures() {
3079        Collection<FeatureInfo> featSet;
3080        synchronized (mPackages) {
3081            featSet = mAvailableFeatures.values();
3082            int size = featSet.size();
3083            if (size > 0) {
3084                FeatureInfo[] features = new FeatureInfo[size+1];
3085                featSet.toArray(features);
3086                FeatureInfo fi = new FeatureInfo();
3087                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3088                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3089                features[size] = fi;
3090                return features;
3091            }
3092        }
3093        return null;
3094    }
3095
3096    @Override
3097    public boolean hasSystemFeature(String name) {
3098        synchronized (mPackages) {
3099            return mAvailableFeatures.containsKey(name);
3100        }
3101    }
3102
3103    private void checkValidCaller(int uid, int userId) {
3104        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3105            return;
3106
3107        throw new SecurityException("Caller uid=" + uid
3108                + " is not privileged to communicate with user=" + userId);
3109    }
3110
3111    @Override
3112    public int checkPermission(String permName, String pkgName, int userId) {
3113        if (!sUserManager.exists(userId)) {
3114            return PackageManager.PERMISSION_DENIED;
3115        }
3116
3117        synchronized (mPackages) {
3118            final PackageParser.Package p = mPackages.get(pkgName);
3119            if (p != null && p.mExtras != null) {
3120                final PackageSetting ps = (PackageSetting) p.mExtras;
3121                final PermissionsState permissionsState = ps.getPermissionsState();
3122                if (permissionsState.hasPermission(permName, userId)) {
3123                    return PackageManager.PERMISSION_GRANTED;
3124                }
3125                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3126                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3127                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3128                    return PackageManager.PERMISSION_GRANTED;
3129                }
3130            }
3131        }
3132
3133        return PackageManager.PERMISSION_DENIED;
3134    }
3135
3136    @Override
3137    public int checkUidPermission(String permName, int uid) {
3138        final int userId = UserHandle.getUserId(uid);
3139
3140        if (!sUserManager.exists(userId)) {
3141            return PackageManager.PERMISSION_DENIED;
3142        }
3143
3144        synchronized (mPackages) {
3145            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3146            if (obj != null) {
3147                final SettingBase ps = (SettingBase) obj;
3148                final PermissionsState permissionsState = ps.getPermissionsState();
3149                if (permissionsState.hasPermission(permName, userId)) {
3150                    return PackageManager.PERMISSION_GRANTED;
3151                }
3152                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3153                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3154                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3155                    return PackageManager.PERMISSION_GRANTED;
3156                }
3157            } else {
3158                ArraySet<String> perms = mSystemPermissions.get(uid);
3159                if (perms != null) {
3160                    if (perms.contains(permName)) {
3161                        return PackageManager.PERMISSION_GRANTED;
3162                    }
3163                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3164                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3165                        return PackageManager.PERMISSION_GRANTED;
3166                    }
3167                }
3168            }
3169        }
3170
3171        return PackageManager.PERMISSION_DENIED;
3172    }
3173
3174    @Override
3175    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3176        if (UserHandle.getCallingUserId() != userId) {
3177            mContext.enforceCallingPermission(
3178                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3179                    "isPermissionRevokedByPolicy for user " + userId);
3180        }
3181
3182        if (checkPermission(permission, packageName, userId)
3183                == PackageManager.PERMISSION_GRANTED) {
3184            return false;
3185        }
3186
3187        final long identity = Binder.clearCallingIdentity();
3188        try {
3189            final int flags = getPermissionFlags(permission, packageName, userId);
3190            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3191        } finally {
3192            Binder.restoreCallingIdentity(identity);
3193        }
3194    }
3195
3196    @Override
3197    public String getPermissionControllerPackageName() {
3198        synchronized (mPackages) {
3199            return mRequiredInstallerPackage;
3200        }
3201    }
3202
3203    /**
3204     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3205     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3206     * @param checkShell TODO(yamasani):
3207     * @param message the message to log on security exception
3208     */
3209    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3210            boolean checkShell, String message) {
3211        if (userId < 0) {
3212            throw new IllegalArgumentException("Invalid userId " + userId);
3213        }
3214        if (checkShell) {
3215            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3216        }
3217        if (userId == UserHandle.getUserId(callingUid)) return;
3218        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3219            if (requireFullPermission) {
3220                mContext.enforceCallingOrSelfPermission(
3221                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3222            } else {
3223                try {
3224                    mContext.enforceCallingOrSelfPermission(
3225                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3226                } catch (SecurityException se) {
3227                    mContext.enforceCallingOrSelfPermission(
3228                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3229                }
3230            }
3231        }
3232    }
3233
3234    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3235        if (callingUid == Process.SHELL_UID) {
3236            if (userHandle >= 0
3237                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3238                throw new SecurityException("Shell does not have permission to access user "
3239                        + userHandle);
3240            } else if (userHandle < 0) {
3241                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3242                        + Debug.getCallers(3));
3243            }
3244        }
3245    }
3246
3247    private BasePermission findPermissionTreeLP(String permName) {
3248        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3249            if (permName.startsWith(bp.name) &&
3250                    permName.length() > bp.name.length() &&
3251                    permName.charAt(bp.name.length()) == '.') {
3252                return bp;
3253            }
3254        }
3255        return null;
3256    }
3257
3258    private BasePermission checkPermissionTreeLP(String permName) {
3259        if (permName != null) {
3260            BasePermission bp = findPermissionTreeLP(permName);
3261            if (bp != null) {
3262                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3263                    return bp;
3264                }
3265                throw new SecurityException("Calling uid "
3266                        + Binder.getCallingUid()
3267                        + " is not allowed to add to permission tree "
3268                        + bp.name + " owned by uid " + bp.uid);
3269            }
3270        }
3271        throw new SecurityException("No permission tree found for " + permName);
3272    }
3273
3274    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3275        if (s1 == null) {
3276            return s2 == null;
3277        }
3278        if (s2 == null) {
3279            return false;
3280        }
3281        if (s1.getClass() != s2.getClass()) {
3282            return false;
3283        }
3284        return s1.equals(s2);
3285    }
3286
3287    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3288        if (pi1.icon != pi2.icon) return false;
3289        if (pi1.logo != pi2.logo) return false;
3290        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3291        if (!compareStrings(pi1.name, pi2.name)) return false;
3292        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3293        // We'll take care of setting this one.
3294        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3295        // These are not currently stored in settings.
3296        //if (!compareStrings(pi1.group, pi2.group)) return false;
3297        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3298        //if (pi1.labelRes != pi2.labelRes) return false;
3299        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3300        return true;
3301    }
3302
3303    int permissionInfoFootprint(PermissionInfo info) {
3304        int size = info.name.length();
3305        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3306        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3307        return size;
3308    }
3309
3310    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3311        int size = 0;
3312        for (BasePermission perm : mSettings.mPermissions.values()) {
3313            if (perm.uid == tree.uid) {
3314                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3315            }
3316        }
3317        return size;
3318    }
3319
3320    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3321        // We calculate the max size of permissions defined by this uid and throw
3322        // if that plus the size of 'info' would exceed our stated maximum.
3323        if (tree.uid != Process.SYSTEM_UID) {
3324            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3325            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3326                throw new SecurityException("Permission tree size cap exceeded");
3327            }
3328        }
3329    }
3330
3331    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3332        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3333            throw new SecurityException("Label must be specified in permission");
3334        }
3335        BasePermission tree = checkPermissionTreeLP(info.name);
3336        BasePermission bp = mSettings.mPermissions.get(info.name);
3337        boolean added = bp == null;
3338        boolean changed = true;
3339        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3340        if (added) {
3341            enforcePermissionCapLocked(info, tree);
3342            bp = new BasePermission(info.name, tree.sourcePackage,
3343                    BasePermission.TYPE_DYNAMIC);
3344        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3345            throw new SecurityException(
3346                    "Not allowed to modify non-dynamic permission "
3347                    + info.name);
3348        } else {
3349            if (bp.protectionLevel == fixedLevel
3350                    && bp.perm.owner.equals(tree.perm.owner)
3351                    && bp.uid == tree.uid
3352                    && comparePermissionInfos(bp.perm.info, info)) {
3353                changed = false;
3354            }
3355        }
3356        bp.protectionLevel = fixedLevel;
3357        info = new PermissionInfo(info);
3358        info.protectionLevel = fixedLevel;
3359        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3360        bp.perm.info.packageName = tree.perm.info.packageName;
3361        bp.uid = tree.uid;
3362        if (added) {
3363            mSettings.mPermissions.put(info.name, bp);
3364        }
3365        if (changed) {
3366            if (!async) {
3367                mSettings.writeLPr();
3368            } else {
3369                scheduleWriteSettingsLocked();
3370            }
3371        }
3372        return added;
3373    }
3374
3375    @Override
3376    public boolean addPermission(PermissionInfo info) {
3377        synchronized (mPackages) {
3378            return addPermissionLocked(info, false);
3379        }
3380    }
3381
3382    @Override
3383    public boolean addPermissionAsync(PermissionInfo info) {
3384        synchronized (mPackages) {
3385            return addPermissionLocked(info, true);
3386        }
3387    }
3388
3389    @Override
3390    public void removePermission(String name) {
3391        synchronized (mPackages) {
3392            checkPermissionTreeLP(name);
3393            BasePermission bp = mSettings.mPermissions.get(name);
3394            if (bp != null) {
3395                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3396                    throw new SecurityException(
3397                            "Not allowed to modify non-dynamic permission "
3398                            + name);
3399                }
3400                mSettings.mPermissions.remove(name);
3401                mSettings.writeLPr();
3402            }
3403        }
3404    }
3405
3406    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3407            BasePermission bp) {
3408        int index = pkg.requestedPermissions.indexOf(bp.name);
3409        if (index == -1) {
3410            throw new SecurityException("Package " + pkg.packageName
3411                    + " has not requested permission " + bp.name);
3412        }
3413        if (!bp.isRuntime()) {
3414            throw new SecurityException("Permission " + bp.name
3415                    + " is not a changeable permission type");
3416        }
3417    }
3418
3419    @Override
3420    public void grantRuntimePermission(String packageName, String name, final int userId) {
3421        if (!sUserManager.exists(userId)) {
3422            Log.e(TAG, "No such user:" + userId);
3423            return;
3424        }
3425
3426        mContext.enforceCallingOrSelfPermission(
3427                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3428                "grantRuntimePermission");
3429
3430        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3431                "grantRuntimePermission");
3432
3433        final int uid;
3434        final SettingBase sb;
3435
3436        synchronized (mPackages) {
3437            final PackageParser.Package pkg = mPackages.get(packageName);
3438            if (pkg == null) {
3439                throw new IllegalArgumentException("Unknown package: " + packageName);
3440            }
3441
3442            final BasePermission bp = mSettings.mPermissions.get(name);
3443            if (bp == null) {
3444                throw new IllegalArgumentException("Unknown permission: " + name);
3445            }
3446
3447            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3448
3449            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3450            sb = (SettingBase) pkg.mExtras;
3451            if (sb == null) {
3452                throw new IllegalArgumentException("Unknown package: " + packageName);
3453            }
3454
3455            final PermissionsState permissionsState = sb.getPermissionsState();
3456
3457            final int flags = permissionsState.getPermissionFlags(name, userId);
3458            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3459                throw new SecurityException("Cannot grant system fixed permission: "
3460                        + name + " for package: " + packageName);
3461            }
3462
3463            final int result = permissionsState.grantRuntimePermission(bp, userId);
3464            switch (result) {
3465                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3466                    return;
3467                }
3468
3469                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3470                    mHandler.post(new Runnable() {
3471                        @Override
3472                        public void run() {
3473                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3474                        }
3475                    });
3476                } break;
3477            }
3478
3479            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3480
3481            // Not critical if that is lost - app has to request again.
3482            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3483        }
3484
3485        // Only need to do this if user is initialized. Otherwise it's a new user
3486        // and there are no processes running as the user yet and there's no need
3487        // to make an expensive call to remount processes for the changed permissions.
3488        if (READ_EXTERNAL_STORAGE.equals(name)
3489                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3490            final long token = Binder.clearCallingIdentity();
3491            try {
3492                if (sUserManager.isInitialized(userId)) {
3493                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3494                            MountServiceInternal.class);
3495                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3496                }
3497            } finally {
3498                Binder.restoreCallingIdentity(token);
3499            }
3500        }
3501    }
3502
3503    @Override
3504    public void revokeRuntimePermission(String packageName, String name, int userId) {
3505        if (!sUserManager.exists(userId)) {
3506            Log.e(TAG, "No such user:" + userId);
3507            return;
3508        }
3509
3510        mContext.enforceCallingOrSelfPermission(
3511                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3512                "revokeRuntimePermission");
3513
3514        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3515                "revokeRuntimePermission");
3516
3517        final SettingBase sb;
3518
3519        synchronized (mPackages) {
3520            final PackageParser.Package pkg = mPackages.get(packageName);
3521            if (pkg == null) {
3522                throw new IllegalArgumentException("Unknown package: " + packageName);
3523            }
3524
3525            final BasePermission bp = mSettings.mPermissions.get(name);
3526            if (bp == null) {
3527                throw new IllegalArgumentException("Unknown permission: " + name);
3528            }
3529
3530            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3531
3532            sb = (SettingBase) pkg.mExtras;
3533            if (sb == null) {
3534                throw new IllegalArgumentException("Unknown package: " + packageName);
3535            }
3536
3537            final PermissionsState permissionsState = sb.getPermissionsState();
3538
3539            final int flags = permissionsState.getPermissionFlags(name, userId);
3540            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3541                throw new SecurityException("Cannot revoke system fixed permission: "
3542                        + name + " for package: " + packageName);
3543            }
3544
3545            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3546                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3547                return;
3548            }
3549
3550            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3551
3552            // Critical, after this call app should never have the permission.
3553            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3554        }
3555
3556        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3557    }
3558
3559    @Override
3560    public void resetRuntimePermissions() {
3561        mContext.enforceCallingOrSelfPermission(
3562                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3563                "revokeRuntimePermission");
3564
3565        int callingUid = Binder.getCallingUid();
3566        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3567            mContext.enforceCallingOrSelfPermission(
3568                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3569                    "resetRuntimePermissions");
3570        }
3571
3572        synchronized (mPackages) {
3573            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3574            for (int userId : UserManagerService.getInstance().getUserIds()) {
3575                final int packageCount = mPackages.size();
3576                for (int i = 0; i < packageCount; i++) {
3577                    PackageParser.Package pkg = mPackages.valueAt(i);
3578                    if (!(pkg.mExtras instanceof PackageSetting)) {
3579                        continue;
3580                    }
3581                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3582                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3583                }
3584            }
3585        }
3586    }
3587
3588    @Override
3589    public int getPermissionFlags(String name, String packageName, int userId) {
3590        if (!sUserManager.exists(userId)) {
3591            return 0;
3592        }
3593
3594        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3595
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3597                "getPermissionFlags");
3598
3599        synchronized (mPackages) {
3600            final PackageParser.Package pkg = mPackages.get(packageName);
3601            if (pkg == null) {
3602                throw new IllegalArgumentException("Unknown package: " + packageName);
3603            }
3604
3605            final BasePermission bp = mSettings.mPermissions.get(name);
3606            if (bp == null) {
3607                throw new IllegalArgumentException("Unknown permission: " + name);
3608            }
3609
3610            SettingBase sb = (SettingBase) pkg.mExtras;
3611            if (sb == null) {
3612                throw new IllegalArgumentException("Unknown package: " + packageName);
3613            }
3614
3615            PermissionsState permissionsState = sb.getPermissionsState();
3616            return permissionsState.getPermissionFlags(name, userId);
3617        }
3618    }
3619
3620    @Override
3621    public void updatePermissionFlags(String name, String packageName, int flagMask,
3622            int flagValues, int userId) {
3623        if (!sUserManager.exists(userId)) {
3624            return;
3625        }
3626
3627        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3628
3629        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3630                "updatePermissionFlags");
3631
3632        // Only the system can change these flags and nothing else.
3633        if (getCallingUid() != Process.SYSTEM_UID) {
3634            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3635            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3636            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3637            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3638        }
3639
3640        synchronized (mPackages) {
3641            final PackageParser.Package pkg = mPackages.get(packageName);
3642            if (pkg == null) {
3643                throw new IllegalArgumentException("Unknown package: " + packageName);
3644            }
3645
3646            final BasePermission bp = mSettings.mPermissions.get(name);
3647            if (bp == null) {
3648                throw new IllegalArgumentException("Unknown permission: " + name);
3649            }
3650
3651            SettingBase sb = (SettingBase) pkg.mExtras;
3652            if (sb == null) {
3653                throw new IllegalArgumentException("Unknown package: " + packageName);
3654            }
3655
3656            PermissionsState permissionsState = sb.getPermissionsState();
3657
3658            // Only the package manager can change flags for system component permissions.
3659            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3660            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3661                return;
3662            }
3663
3664            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3665
3666            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3667                // Install and runtime permissions are stored in different places,
3668                // so figure out what permission changed and persist the change.
3669                if (permissionsState.getInstallPermissionState(name) != null) {
3670                    scheduleWriteSettingsLocked();
3671                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3672                        || hadState) {
3673                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3674                }
3675            }
3676        }
3677    }
3678
3679    /**
3680     * Update the permission flags for all packages and runtime permissions of a user in order
3681     * to allow device or profile owner to remove POLICY_FIXED.
3682     */
3683    @Override
3684    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3685        if (!sUserManager.exists(userId)) {
3686            return;
3687        }
3688
3689        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3690
3691        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3692                "updatePermissionFlagsForAllApps");
3693
3694        // Only the system can change system fixed flags.
3695        if (getCallingUid() != Process.SYSTEM_UID) {
3696            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3697            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3698        }
3699
3700        synchronized (mPackages) {
3701            boolean changed = false;
3702            final int packageCount = mPackages.size();
3703            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3704                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3705                SettingBase sb = (SettingBase) pkg.mExtras;
3706                if (sb == null) {
3707                    continue;
3708                }
3709                PermissionsState permissionsState = sb.getPermissionsState();
3710                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3711                        userId, flagMask, flagValues);
3712            }
3713            if (changed) {
3714                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3715            }
3716        }
3717    }
3718
3719    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3720        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3721                != PackageManager.PERMISSION_GRANTED
3722            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3723                != PackageManager.PERMISSION_GRANTED) {
3724            throw new SecurityException(message + " requires "
3725                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3726                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3727        }
3728    }
3729
3730    @Override
3731    public boolean shouldShowRequestPermissionRationale(String permissionName,
3732            String packageName, int userId) {
3733        if (UserHandle.getCallingUserId() != userId) {
3734            mContext.enforceCallingPermission(
3735                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3736                    "canShowRequestPermissionRationale for user " + userId);
3737        }
3738
3739        final int uid = getPackageUid(packageName, userId);
3740        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3741            return false;
3742        }
3743
3744        if (checkPermission(permissionName, packageName, userId)
3745                == PackageManager.PERMISSION_GRANTED) {
3746            return false;
3747        }
3748
3749        final int flags;
3750
3751        final long identity = Binder.clearCallingIdentity();
3752        try {
3753            flags = getPermissionFlags(permissionName,
3754                    packageName, userId);
3755        } finally {
3756            Binder.restoreCallingIdentity(identity);
3757        }
3758
3759        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3760                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3761                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3762
3763        if ((flags & fixedFlags) != 0) {
3764            return false;
3765        }
3766
3767        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3768    }
3769
3770    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3771        BasePermission bp = mSettings.mPermissions.get(permission);
3772        if (bp == null) {
3773            throw new SecurityException("Missing " + permission + " permission");
3774        }
3775
3776        SettingBase sb = (SettingBase) pkg.mExtras;
3777        PermissionsState permissionsState = sb.getPermissionsState();
3778
3779        if (permissionsState.grantInstallPermission(bp) !=
3780                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3781            scheduleWriteSettingsLocked();
3782        }
3783    }
3784
3785    @Override
3786    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3787        mContext.enforceCallingOrSelfPermission(
3788                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3789                "addOnPermissionsChangeListener");
3790
3791        synchronized (mPackages) {
3792            mOnPermissionChangeListeners.addListenerLocked(listener);
3793        }
3794    }
3795
3796    @Override
3797    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3798        synchronized (mPackages) {
3799            mOnPermissionChangeListeners.removeListenerLocked(listener);
3800        }
3801    }
3802
3803    @Override
3804    public boolean isProtectedBroadcast(String actionName) {
3805        synchronized (mPackages) {
3806            return mProtectedBroadcasts.contains(actionName);
3807        }
3808    }
3809
3810    @Override
3811    public int checkSignatures(String pkg1, String pkg2) {
3812        synchronized (mPackages) {
3813            final PackageParser.Package p1 = mPackages.get(pkg1);
3814            final PackageParser.Package p2 = mPackages.get(pkg2);
3815            if (p1 == null || p1.mExtras == null
3816                    || p2 == null || p2.mExtras == null) {
3817                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3818            }
3819            return compareSignatures(p1.mSignatures, p2.mSignatures);
3820        }
3821    }
3822
3823    @Override
3824    public int checkUidSignatures(int uid1, int uid2) {
3825        // Map to base uids.
3826        uid1 = UserHandle.getAppId(uid1);
3827        uid2 = UserHandle.getAppId(uid2);
3828        // reader
3829        synchronized (mPackages) {
3830            Signature[] s1;
3831            Signature[] s2;
3832            Object obj = mSettings.getUserIdLPr(uid1);
3833            if (obj != null) {
3834                if (obj instanceof SharedUserSetting) {
3835                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3836                } else if (obj instanceof PackageSetting) {
3837                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3838                } else {
3839                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3840                }
3841            } else {
3842                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3843            }
3844            obj = mSettings.getUserIdLPr(uid2);
3845            if (obj != null) {
3846                if (obj instanceof SharedUserSetting) {
3847                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3848                } else if (obj instanceof PackageSetting) {
3849                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3850                } else {
3851                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3852                }
3853            } else {
3854                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3855            }
3856            return compareSignatures(s1, s2);
3857        }
3858    }
3859
3860    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3861        final long identity = Binder.clearCallingIdentity();
3862        try {
3863            if (sb instanceof SharedUserSetting) {
3864                SharedUserSetting sus = (SharedUserSetting) sb;
3865                final int packageCount = sus.packages.size();
3866                for (int i = 0; i < packageCount; i++) {
3867                    PackageSetting susPs = sus.packages.valueAt(i);
3868                    if (userId == UserHandle.USER_ALL) {
3869                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3870                    } else {
3871                        final int uid = UserHandle.getUid(userId, susPs.appId);
3872                        killUid(uid, reason);
3873                    }
3874                }
3875            } else if (sb instanceof PackageSetting) {
3876                PackageSetting ps = (PackageSetting) sb;
3877                if (userId == UserHandle.USER_ALL) {
3878                    killApplication(ps.pkg.packageName, ps.appId, reason);
3879                } else {
3880                    final int uid = UserHandle.getUid(userId, ps.appId);
3881                    killUid(uid, reason);
3882                }
3883            }
3884        } finally {
3885            Binder.restoreCallingIdentity(identity);
3886        }
3887    }
3888
3889    private static void killUid(int uid, String reason) {
3890        IActivityManager am = ActivityManagerNative.getDefault();
3891        if (am != null) {
3892            try {
3893                am.killUid(uid, reason);
3894            } catch (RemoteException e) {
3895                /* ignore - same process */
3896            }
3897        }
3898    }
3899
3900    /**
3901     * Compares two sets of signatures. Returns:
3902     * <br />
3903     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3904     * <br />
3905     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3906     * <br />
3907     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3908     * <br />
3909     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3910     * <br />
3911     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3912     */
3913    static int compareSignatures(Signature[] s1, Signature[] s2) {
3914        if (s1 == null) {
3915            return s2 == null
3916                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3917                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3918        }
3919
3920        if (s2 == null) {
3921            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3922        }
3923
3924        if (s1.length != s2.length) {
3925            return PackageManager.SIGNATURE_NO_MATCH;
3926        }
3927
3928        // Since both signature sets are of size 1, we can compare without HashSets.
3929        if (s1.length == 1) {
3930            return s1[0].equals(s2[0]) ?
3931                    PackageManager.SIGNATURE_MATCH :
3932                    PackageManager.SIGNATURE_NO_MATCH;
3933        }
3934
3935        ArraySet<Signature> set1 = new ArraySet<Signature>();
3936        for (Signature sig : s1) {
3937            set1.add(sig);
3938        }
3939        ArraySet<Signature> set2 = new ArraySet<Signature>();
3940        for (Signature sig : s2) {
3941            set2.add(sig);
3942        }
3943        // Make sure s2 contains all signatures in s1.
3944        if (set1.equals(set2)) {
3945            return PackageManager.SIGNATURE_MATCH;
3946        }
3947        return PackageManager.SIGNATURE_NO_MATCH;
3948    }
3949
3950    /**
3951     * If the database version for this type of package (internal storage or
3952     * external storage) is less than the version where package signatures
3953     * were updated, return true.
3954     */
3955    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3956        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3957        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3958    }
3959
3960    /**
3961     * Used for backward compatibility to make sure any packages with
3962     * certificate chains get upgraded to the new style. {@code existingSigs}
3963     * will be in the old format (since they were stored on disk from before the
3964     * system upgrade) and {@code scannedSigs} will be in the newer format.
3965     */
3966    private int compareSignaturesCompat(PackageSignatures existingSigs,
3967            PackageParser.Package scannedPkg) {
3968        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3969            return PackageManager.SIGNATURE_NO_MATCH;
3970        }
3971
3972        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3973        for (Signature sig : existingSigs.mSignatures) {
3974            existingSet.add(sig);
3975        }
3976        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3977        for (Signature sig : scannedPkg.mSignatures) {
3978            try {
3979                Signature[] chainSignatures = sig.getChainSignatures();
3980                for (Signature chainSig : chainSignatures) {
3981                    scannedCompatSet.add(chainSig);
3982                }
3983            } catch (CertificateEncodingException e) {
3984                scannedCompatSet.add(sig);
3985            }
3986        }
3987        /*
3988         * Make sure the expanded scanned set contains all signatures in the
3989         * existing one.
3990         */
3991        if (scannedCompatSet.equals(existingSet)) {
3992            // Migrate the old signatures to the new scheme.
3993            existingSigs.assignSignatures(scannedPkg.mSignatures);
3994            // The new KeySets will be re-added later in the scanning process.
3995            synchronized (mPackages) {
3996                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3997            }
3998            return PackageManager.SIGNATURE_MATCH;
3999        }
4000        return PackageManager.SIGNATURE_NO_MATCH;
4001    }
4002
4003    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4004        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4005        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4006    }
4007
4008    private int compareSignaturesRecover(PackageSignatures existingSigs,
4009            PackageParser.Package scannedPkg) {
4010        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4011            return PackageManager.SIGNATURE_NO_MATCH;
4012        }
4013
4014        String msg = null;
4015        try {
4016            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4017                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4018                        + scannedPkg.packageName);
4019                return PackageManager.SIGNATURE_MATCH;
4020            }
4021        } catch (CertificateException e) {
4022            msg = e.getMessage();
4023        }
4024
4025        logCriticalInfo(Log.INFO,
4026                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4027        return PackageManager.SIGNATURE_NO_MATCH;
4028    }
4029
4030    @Override
4031    public String[] getPackagesForUid(int uid) {
4032        uid = UserHandle.getAppId(uid);
4033        // reader
4034        synchronized (mPackages) {
4035            Object obj = mSettings.getUserIdLPr(uid);
4036            if (obj instanceof SharedUserSetting) {
4037                final SharedUserSetting sus = (SharedUserSetting) obj;
4038                final int N = sus.packages.size();
4039                final String[] res = new String[N];
4040                final Iterator<PackageSetting> it = sus.packages.iterator();
4041                int i = 0;
4042                while (it.hasNext()) {
4043                    res[i++] = it.next().name;
4044                }
4045                return res;
4046            } else if (obj instanceof PackageSetting) {
4047                final PackageSetting ps = (PackageSetting) obj;
4048                return new String[] { ps.name };
4049            }
4050        }
4051        return null;
4052    }
4053
4054    @Override
4055    public String getNameForUid(int uid) {
4056        // reader
4057        synchronized (mPackages) {
4058            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4059            if (obj instanceof SharedUserSetting) {
4060                final SharedUserSetting sus = (SharedUserSetting) obj;
4061                return sus.name + ":" + sus.userId;
4062            } else if (obj instanceof PackageSetting) {
4063                final PackageSetting ps = (PackageSetting) obj;
4064                return ps.name;
4065            }
4066        }
4067        return null;
4068    }
4069
4070    @Override
4071    public int getUidForSharedUser(String sharedUserName) {
4072        if(sharedUserName == null) {
4073            return -1;
4074        }
4075        // reader
4076        synchronized (mPackages) {
4077            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4078            if (suid == null) {
4079                return -1;
4080            }
4081            return suid.userId;
4082        }
4083    }
4084
4085    @Override
4086    public int getFlagsForUid(int uid) {
4087        synchronized (mPackages) {
4088            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4089            if (obj instanceof SharedUserSetting) {
4090                final SharedUserSetting sus = (SharedUserSetting) obj;
4091                return sus.pkgFlags;
4092            } else if (obj instanceof PackageSetting) {
4093                final PackageSetting ps = (PackageSetting) obj;
4094                return ps.pkgFlags;
4095            }
4096        }
4097        return 0;
4098    }
4099
4100    @Override
4101    public int getPrivateFlagsForUid(int uid) {
4102        synchronized (mPackages) {
4103            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4104            if (obj instanceof SharedUserSetting) {
4105                final SharedUserSetting sus = (SharedUserSetting) obj;
4106                return sus.pkgPrivateFlags;
4107            } else if (obj instanceof PackageSetting) {
4108                final PackageSetting ps = (PackageSetting) obj;
4109                return ps.pkgPrivateFlags;
4110            }
4111        }
4112        return 0;
4113    }
4114
4115    @Override
4116    public boolean isUidPrivileged(int uid) {
4117        uid = UserHandle.getAppId(uid);
4118        // reader
4119        synchronized (mPackages) {
4120            Object obj = mSettings.getUserIdLPr(uid);
4121            if (obj instanceof SharedUserSetting) {
4122                final SharedUserSetting sus = (SharedUserSetting) obj;
4123                final Iterator<PackageSetting> it = sus.packages.iterator();
4124                while (it.hasNext()) {
4125                    if (it.next().isPrivileged()) {
4126                        return true;
4127                    }
4128                }
4129            } else if (obj instanceof PackageSetting) {
4130                final PackageSetting ps = (PackageSetting) obj;
4131                return ps.isPrivileged();
4132            }
4133        }
4134        return false;
4135    }
4136
4137    @Override
4138    public String[] getAppOpPermissionPackages(String permissionName) {
4139        synchronized (mPackages) {
4140            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4141            if (pkgs == null) {
4142                return null;
4143            }
4144            return pkgs.toArray(new String[pkgs.size()]);
4145        }
4146    }
4147
4148    @Override
4149    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4150            int flags, int userId) {
4151        if (!sUserManager.exists(userId)) return null;
4152        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4153        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4154        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4155    }
4156
4157    @Override
4158    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4159            IntentFilter filter, int match, ComponentName activity) {
4160        final int userId = UserHandle.getCallingUserId();
4161        if (DEBUG_PREFERRED) {
4162            Log.v(TAG, "setLastChosenActivity intent=" + intent
4163                + " resolvedType=" + resolvedType
4164                + " flags=" + flags
4165                + " filter=" + filter
4166                + " match=" + match
4167                + " activity=" + activity);
4168            filter.dump(new PrintStreamPrinter(System.out), "    ");
4169        }
4170        intent.setComponent(null);
4171        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4172        // Find any earlier preferred or last chosen entries and nuke them
4173        findPreferredActivity(intent, resolvedType,
4174                flags, query, 0, false, true, false, userId);
4175        // Add the new activity as the last chosen for this filter
4176        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4177                "Setting last chosen");
4178    }
4179
4180    @Override
4181    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4182        final int userId = UserHandle.getCallingUserId();
4183        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4184        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4185        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4186                false, false, false, userId);
4187    }
4188
4189    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4190            int flags, List<ResolveInfo> query, int userId) {
4191        if (query != null) {
4192            final int N = query.size();
4193            if (N == 1) {
4194                return query.get(0);
4195            } else if (N > 1) {
4196                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4197                // If there is more than one activity with the same priority,
4198                // then let the user decide between them.
4199                ResolveInfo r0 = query.get(0);
4200                ResolveInfo r1 = query.get(1);
4201                if (DEBUG_INTENT_MATCHING || debug) {
4202                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4203                            + r1.activityInfo.name + "=" + r1.priority);
4204                }
4205                // If the first activity has a higher priority, or a different
4206                // default, then it is always desireable to pick it.
4207                if (r0.priority != r1.priority
4208                        || r0.preferredOrder != r1.preferredOrder
4209                        || r0.isDefault != r1.isDefault) {
4210                    return query.get(0);
4211                }
4212                // If we have saved a preference for a preferred activity for
4213                // this Intent, use that.
4214                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4215                        flags, query, r0.priority, true, false, debug, userId);
4216                if (ri != null) {
4217                    return ri;
4218                }
4219                if (userId != 0) {
4220                    ri = new ResolveInfo(mResolveInfo);
4221                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4222                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4223                            ri.activityInfo.applicationInfo);
4224                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4225                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4226                    return ri;
4227                }
4228                return mResolveInfo;
4229            }
4230        }
4231        return null;
4232    }
4233
4234    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4235            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4236        final int N = query.size();
4237        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4238                .get(userId);
4239        // Get the list of persistent preferred activities that handle the intent
4240        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4241        List<PersistentPreferredActivity> pprefs = ppir != null
4242                ? ppir.queryIntent(intent, resolvedType,
4243                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4244                : null;
4245        if (pprefs != null && pprefs.size() > 0) {
4246            final int M = pprefs.size();
4247            for (int i=0; i<M; i++) {
4248                final PersistentPreferredActivity ppa = pprefs.get(i);
4249                if (DEBUG_PREFERRED || debug) {
4250                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4251                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4252                            + "\n  component=" + ppa.mComponent);
4253                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4254                }
4255                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4256                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4257                if (DEBUG_PREFERRED || debug) {
4258                    Slog.v(TAG, "Found persistent preferred activity:");
4259                    if (ai != null) {
4260                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4261                    } else {
4262                        Slog.v(TAG, "  null");
4263                    }
4264                }
4265                if (ai == null) {
4266                    // This previously registered persistent preferred activity
4267                    // component is no longer known. Ignore it and do NOT remove it.
4268                    continue;
4269                }
4270                for (int j=0; j<N; j++) {
4271                    final ResolveInfo ri = query.get(j);
4272                    if (!ri.activityInfo.applicationInfo.packageName
4273                            .equals(ai.applicationInfo.packageName)) {
4274                        continue;
4275                    }
4276                    if (!ri.activityInfo.name.equals(ai.name)) {
4277                        continue;
4278                    }
4279                    //  Found a persistent preference that can handle the intent.
4280                    if (DEBUG_PREFERRED || debug) {
4281                        Slog.v(TAG, "Returning persistent preferred activity: " +
4282                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4283                    }
4284                    return ri;
4285                }
4286            }
4287        }
4288        return null;
4289    }
4290
4291    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4292            List<ResolveInfo> query, int priority, boolean always,
4293            boolean removeMatches, boolean debug, int userId) {
4294        if (!sUserManager.exists(userId)) return null;
4295        // writer
4296        synchronized (mPackages) {
4297            if (intent.getSelector() != null) {
4298                intent = intent.getSelector();
4299            }
4300            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4301
4302            // Try to find a matching persistent preferred activity.
4303            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4304                    debug, userId);
4305
4306            // If a persistent preferred activity matched, use it.
4307            if (pri != null) {
4308                return pri;
4309            }
4310
4311            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4312            // Get the list of preferred activities that handle the intent
4313            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4314            List<PreferredActivity> prefs = pir != null
4315                    ? pir.queryIntent(intent, resolvedType,
4316                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4317                    : null;
4318            if (prefs != null && prefs.size() > 0) {
4319                boolean changed = false;
4320                try {
4321                    // First figure out how good the original match set is.
4322                    // We will only allow preferred activities that came
4323                    // from the same match quality.
4324                    int match = 0;
4325
4326                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4327
4328                    final int N = query.size();
4329                    for (int j=0; j<N; j++) {
4330                        final ResolveInfo ri = query.get(j);
4331                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4332                                + ": 0x" + Integer.toHexString(match));
4333                        if (ri.match > match) {
4334                            match = ri.match;
4335                        }
4336                    }
4337
4338                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4339                            + Integer.toHexString(match));
4340
4341                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4342                    final int M = prefs.size();
4343                    for (int i=0; i<M; i++) {
4344                        final PreferredActivity pa = prefs.get(i);
4345                        if (DEBUG_PREFERRED || debug) {
4346                            Slog.v(TAG, "Checking PreferredActivity ds="
4347                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4348                                    + "\n  component=" + pa.mPref.mComponent);
4349                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4350                        }
4351                        if (pa.mPref.mMatch != match) {
4352                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4353                                    + Integer.toHexString(pa.mPref.mMatch));
4354                            continue;
4355                        }
4356                        // If it's not an "always" type preferred activity and that's what we're
4357                        // looking for, skip it.
4358                        if (always && !pa.mPref.mAlways) {
4359                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4360                            continue;
4361                        }
4362                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4363                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4364                        if (DEBUG_PREFERRED || debug) {
4365                            Slog.v(TAG, "Found preferred activity:");
4366                            if (ai != null) {
4367                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4368                            } else {
4369                                Slog.v(TAG, "  null");
4370                            }
4371                        }
4372                        if (ai == null) {
4373                            // This previously registered preferred activity
4374                            // component is no longer known.  Most likely an update
4375                            // to the app was installed and in the new version this
4376                            // component no longer exists.  Clean it up by removing
4377                            // it from the preferred activities list, and skip it.
4378                            Slog.w(TAG, "Removing dangling preferred activity: "
4379                                    + pa.mPref.mComponent);
4380                            pir.removeFilter(pa);
4381                            changed = true;
4382                            continue;
4383                        }
4384                        for (int j=0; j<N; j++) {
4385                            final ResolveInfo ri = query.get(j);
4386                            if (!ri.activityInfo.applicationInfo.packageName
4387                                    .equals(ai.applicationInfo.packageName)) {
4388                                continue;
4389                            }
4390                            if (!ri.activityInfo.name.equals(ai.name)) {
4391                                continue;
4392                            }
4393
4394                            if (removeMatches) {
4395                                pir.removeFilter(pa);
4396                                changed = true;
4397                                if (DEBUG_PREFERRED) {
4398                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4399                                }
4400                                break;
4401                            }
4402
4403                            // Okay we found a previously set preferred or last chosen app.
4404                            // If the result set is different from when this
4405                            // was created, we need to clear it and re-ask the
4406                            // user their preference, if we're looking for an "always" type entry.
4407                            if (always && !pa.mPref.sameSet(query)) {
4408                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4409                                        + intent + " type " + resolvedType);
4410                                if (DEBUG_PREFERRED) {
4411                                    Slog.v(TAG, "Removing preferred activity since set changed "
4412                                            + pa.mPref.mComponent);
4413                                }
4414                                pir.removeFilter(pa);
4415                                // Re-add the filter as a "last chosen" entry (!always)
4416                                PreferredActivity lastChosen = new PreferredActivity(
4417                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4418                                pir.addFilter(lastChosen);
4419                                changed = true;
4420                                return null;
4421                            }
4422
4423                            // Yay! Either the set matched or we're looking for the last chosen
4424                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4425                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4426                            return ri;
4427                        }
4428                    }
4429                } finally {
4430                    if (changed) {
4431                        if (DEBUG_PREFERRED) {
4432                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4433                        }
4434                        scheduleWritePackageRestrictionsLocked(userId);
4435                    }
4436                }
4437            }
4438        }
4439        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4440        return null;
4441    }
4442
4443    /*
4444     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4445     */
4446    @Override
4447    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4448            int targetUserId) {
4449        mContext.enforceCallingOrSelfPermission(
4450                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4451        List<CrossProfileIntentFilter> matches =
4452                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4453        if (matches != null) {
4454            int size = matches.size();
4455            for (int i = 0; i < size; i++) {
4456                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4457            }
4458        }
4459        if (hasWebURI(intent)) {
4460            // cross-profile app linking works only towards the parent.
4461            final UserInfo parent = getProfileParent(sourceUserId);
4462            synchronized(mPackages) {
4463                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4464                        intent, resolvedType, 0, sourceUserId, parent.id);
4465                return xpDomainInfo != null;
4466            }
4467        }
4468        return false;
4469    }
4470
4471    private UserInfo getProfileParent(int userId) {
4472        final long identity = Binder.clearCallingIdentity();
4473        try {
4474            return sUserManager.getProfileParent(userId);
4475        } finally {
4476            Binder.restoreCallingIdentity(identity);
4477        }
4478    }
4479
4480    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4481            String resolvedType, int userId) {
4482        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4483        if (resolver != null) {
4484            return resolver.queryIntent(intent, resolvedType, false, userId);
4485        }
4486        return null;
4487    }
4488
4489    @Override
4490    public List<ResolveInfo> queryIntentActivities(Intent intent,
4491            String resolvedType, int flags, int userId) {
4492        if (!sUserManager.exists(userId)) return Collections.emptyList();
4493        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4494        ComponentName comp = intent.getComponent();
4495        if (comp == null) {
4496            if (intent.getSelector() != null) {
4497                intent = intent.getSelector();
4498                comp = intent.getComponent();
4499            }
4500        }
4501
4502        if (comp != null) {
4503            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4504            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4505            if (ai != null) {
4506                final ResolveInfo ri = new ResolveInfo();
4507                ri.activityInfo = ai;
4508                list.add(ri);
4509            }
4510            return list;
4511        }
4512
4513        // reader
4514        synchronized (mPackages) {
4515            final String pkgName = intent.getPackage();
4516            if (pkgName == null) {
4517                List<CrossProfileIntentFilter> matchingFilters =
4518                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4519                // Check for results that need to skip the current profile.
4520                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4521                        resolvedType, flags, userId);
4522                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4523                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4524                    result.add(xpResolveInfo);
4525                    return filterIfNotPrimaryUser(result, userId);
4526                }
4527
4528                // Check for results in the current profile.
4529                List<ResolveInfo> result = mActivities.queryIntent(
4530                        intent, resolvedType, flags, userId);
4531
4532                // Check for cross profile results.
4533                xpResolveInfo = queryCrossProfileIntents(
4534                        matchingFilters, intent, resolvedType, flags, userId);
4535                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4536                    result.add(xpResolveInfo);
4537                    Collections.sort(result, mResolvePrioritySorter);
4538                }
4539                result = filterIfNotPrimaryUser(result, userId);
4540                if (hasWebURI(intent)) {
4541                    CrossProfileDomainInfo xpDomainInfo = null;
4542                    final UserInfo parent = getProfileParent(userId);
4543                    if (parent != null) {
4544                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4545                                flags, userId, parent.id);
4546                    }
4547                    if (xpDomainInfo != null) {
4548                        if (xpResolveInfo != null) {
4549                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4550                            // in the result.
4551                            result.remove(xpResolveInfo);
4552                        }
4553                        if (result.size() == 0) {
4554                            result.add(xpDomainInfo.resolveInfo);
4555                            return result;
4556                        }
4557                    } else if (result.size() <= 1) {
4558                        return result;
4559                    }
4560                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4561                            xpDomainInfo, userId);
4562                    Collections.sort(result, mResolvePrioritySorter);
4563                }
4564                return result;
4565            }
4566            final PackageParser.Package pkg = mPackages.get(pkgName);
4567            if (pkg != null) {
4568                return filterIfNotPrimaryUser(
4569                        mActivities.queryIntentForPackage(
4570                                intent, resolvedType, flags, pkg.activities, userId),
4571                        userId);
4572            }
4573            return new ArrayList<ResolveInfo>();
4574        }
4575    }
4576
4577    private static class CrossProfileDomainInfo {
4578        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4579        ResolveInfo resolveInfo;
4580        /* Best domain verification status of the activities found in the other profile */
4581        int bestDomainVerificationStatus;
4582    }
4583
4584    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4585            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4586        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4587                sourceUserId)) {
4588            return null;
4589        }
4590        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4591                resolvedType, flags, parentUserId);
4592
4593        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4594            return null;
4595        }
4596        CrossProfileDomainInfo result = null;
4597        int size = resultTargetUser.size();
4598        for (int i = 0; i < size; i++) {
4599            ResolveInfo riTargetUser = resultTargetUser.get(i);
4600            // Intent filter verification is only for filters that specify a host. So don't return
4601            // those that handle all web uris.
4602            if (riTargetUser.handleAllWebDataURI) {
4603                continue;
4604            }
4605            String packageName = riTargetUser.activityInfo.packageName;
4606            PackageSetting ps = mSettings.mPackages.get(packageName);
4607            if (ps == null) {
4608                continue;
4609            }
4610            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4611            int status = (int)(verificationState >> 32);
4612            if (result == null) {
4613                result = new CrossProfileDomainInfo();
4614                result.resolveInfo =
4615                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4616                result.bestDomainVerificationStatus = status;
4617            } else {
4618                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4619                        result.bestDomainVerificationStatus);
4620            }
4621        }
4622        // Don't consider matches with status NEVER across profiles.
4623        if (result != null && result.bestDomainVerificationStatus
4624                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4625            return null;
4626        }
4627        return result;
4628    }
4629
4630    /**
4631     * Verification statuses are ordered from the worse to the best, except for
4632     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4633     */
4634    private int bestDomainVerificationStatus(int status1, int status2) {
4635        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4636            return status2;
4637        }
4638        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4639            return status1;
4640        }
4641        return (int) MathUtils.max(status1, status2);
4642    }
4643
4644    private boolean isUserEnabled(int userId) {
4645        long callingId = Binder.clearCallingIdentity();
4646        try {
4647            UserInfo userInfo = sUserManager.getUserInfo(userId);
4648            return userInfo != null && userInfo.isEnabled();
4649        } finally {
4650            Binder.restoreCallingIdentity(callingId);
4651        }
4652    }
4653
4654    /**
4655     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4656     *
4657     * @return filtered list
4658     */
4659    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4660        if (userId == UserHandle.USER_OWNER) {
4661            return resolveInfos;
4662        }
4663        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4664            ResolveInfo info = resolveInfos.get(i);
4665            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4666                resolveInfos.remove(i);
4667            }
4668        }
4669        return resolveInfos;
4670    }
4671
4672    private static boolean hasWebURI(Intent intent) {
4673        if (intent.getData() == null) {
4674            return false;
4675        }
4676        final String scheme = intent.getScheme();
4677        if (TextUtils.isEmpty(scheme)) {
4678            return false;
4679        }
4680        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4681    }
4682
4683    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4684            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4685            int userId) {
4686        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4687
4688        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4689            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4690                    candidates.size());
4691        }
4692
4693        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4694        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4695        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4696        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4697        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4698
4699        synchronized (mPackages) {
4700            final int count = candidates.size();
4701            // First, try to use linked apps. Partition the candidates into four lists:
4702            // one for the final results, one for the "do not use ever", one for "undefined status"
4703            // and finally one for "browser app type".
4704            for (int n=0; n<count; n++) {
4705                ResolveInfo info = candidates.get(n);
4706                String packageName = info.activityInfo.packageName;
4707                PackageSetting ps = mSettings.mPackages.get(packageName);
4708                if (ps != null) {
4709                    // Add to the special match all list (Browser use case)
4710                    if (info.handleAllWebDataURI) {
4711                        matchAllList.add(info);
4712                        continue;
4713                    }
4714                    // Try to get the status from User settings first
4715                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4716                    int status = (int)(packedStatus >> 32);
4717                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4718                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4719                        if (DEBUG_DOMAIN_VERIFICATION) {
4720                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4721                                    + " : linkgen=" + linkGeneration);
4722                        }
4723                        // Use link-enabled generation as preferredOrder, i.e.
4724                        // prefer newly-enabled over earlier-enabled.
4725                        info.preferredOrder = linkGeneration;
4726                        alwaysList.add(info);
4727                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4728                        if (DEBUG_DOMAIN_VERIFICATION) {
4729                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4730                        }
4731                        neverList.add(info);
4732                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4733                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4734                        if (DEBUG_DOMAIN_VERIFICATION) {
4735                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4736                        }
4737                        undefinedList.add(info);
4738                    }
4739                }
4740            }
4741            // First try to add the "always" resolution(s) for the current user, if any
4742            if (alwaysList.size() > 0) {
4743                result.addAll(alwaysList);
4744            // if there is an "always" for the parent user, add it.
4745            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4746                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4747                result.add(xpDomainInfo.resolveInfo);
4748            } else {
4749                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4750                result.addAll(undefinedList);
4751                if (xpDomainInfo != null && (
4752                        xpDomainInfo.bestDomainVerificationStatus
4753                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4754                        || xpDomainInfo.bestDomainVerificationStatus
4755                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4756                    result.add(xpDomainInfo.resolveInfo);
4757                }
4758                // Also add Browsers (all of them or only the default one)
4759                if ((matchFlags & MATCH_ALL) != 0) {
4760                    result.addAll(matchAllList);
4761                } else {
4762                    // Browser/generic handling case.  If there's a default browser, go straight
4763                    // to that (but only if there is no other higher-priority match).
4764                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4765                    int maxMatchPrio = 0;
4766                    ResolveInfo defaultBrowserMatch = null;
4767                    final int numCandidates = matchAllList.size();
4768                    for (int n = 0; n < numCandidates; n++) {
4769                        ResolveInfo info = matchAllList.get(n);
4770                        // track the highest overall match priority...
4771                        if (info.priority > maxMatchPrio) {
4772                            maxMatchPrio = info.priority;
4773                        }
4774                        // ...and the highest-priority default browser match
4775                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4776                            if (defaultBrowserMatch == null
4777                                    || (defaultBrowserMatch.priority < info.priority)) {
4778                                if (debug) {
4779                                    Slog.v(TAG, "Considering default browser match " + info);
4780                                }
4781                                defaultBrowserMatch = info;
4782                            }
4783                        }
4784                    }
4785                    if (defaultBrowserMatch != null
4786                            && defaultBrowserMatch.priority >= maxMatchPrio
4787                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4788                    {
4789                        if (debug) {
4790                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4791                        }
4792                        result.add(defaultBrowserMatch);
4793                    } else {
4794                        result.addAll(matchAllList);
4795                    }
4796                }
4797
4798                // If there is nothing selected, add all candidates and remove the ones that the user
4799                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4800                if (result.size() == 0) {
4801                    result.addAll(candidates);
4802                    result.removeAll(neverList);
4803                }
4804            }
4805        }
4806        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4807            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4808                    result.size());
4809            for (ResolveInfo info : result) {
4810                Slog.v(TAG, "  + " + info.activityInfo);
4811            }
4812        }
4813        return result;
4814    }
4815
4816    // Returns a packed value as a long:
4817    //
4818    // high 'int'-sized word: link status: undefined/ask/never/always.
4819    // low 'int'-sized word: relative priority among 'always' results.
4820    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4821        long result = ps.getDomainVerificationStatusForUser(userId);
4822        // if none available, get the master status
4823        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4824            if (ps.getIntentFilterVerificationInfo() != null) {
4825                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4826            }
4827        }
4828        return result;
4829    }
4830
4831    private ResolveInfo querySkipCurrentProfileIntents(
4832            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4833            int flags, int sourceUserId) {
4834        if (matchingFilters != null) {
4835            int size = matchingFilters.size();
4836            for (int i = 0; i < size; i ++) {
4837                CrossProfileIntentFilter filter = matchingFilters.get(i);
4838                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4839                    // Checking if there are activities in the target user that can handle the
4840                    // intent.
4841                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4842                            flags, sourceUserId);
4843                    if (resolveInfo != null) {
4844                        return resolveInfo;
4845                    }
4846                }
4847            }
4848        }
4849        return null;
4850    }
4851
4852    // Return matching ResolveInfo if any for skip current profile intent filters.
4853    private ResolveInfo queryCrossProfileIntents(
4854            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4855            int flags, int sourceUserId) {
4856        if (matchingFilters != null) {
4857            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4858            // match the same intent. For performance reasons, it is better not to
4859            // run queryIntent twice for the same userId
4860            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4861            int size = matchingFilters.size();
4862            for (int i = 0; i < size; i++) {
4863                CrossProfileIntentFilter filter = matchingFilters.get(i);
4864                int targetUserId = filter.getTargetUserId();
4865                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4866                        && !alreadyTriedUserIds.get(targetUserId)) {
4867                    // Checking if there are activities in the target user that can handle the
4868                    // intent.
4869                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4870                            flags, sourceUserId);
4871                    if (resolveInfo != null) return resolveInfo;
4872                    alreadyTriedUserIds.put(targetUserId, true);
4873                }
4874            }
4875        }
4876        return null;
4877    }
4878
4879    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4880            String resolvedType, int flags, int sourceUserId) {
4881        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4882                resolvedType, flags, filter.getTargetUserId());
4883        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4884            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4885        }
4886        return null;
4887    }
4888
4889    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4890            int sourceUserId, int targetUserId) {
4891        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4892        String className;
4893        if (targetUserId == UserHandle.USER_OWNER) {
4894            className = FORWARD_INTENT_TO_USER_OWNER;
4895        } else {
4896            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4897        }
4898        ComponentName forwardingActivityComponentName = new ComponentName(
4899                mAndroidApplication.packageName, className);
4900        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4901                sourceUserId);
4902        if (targetUserId == UserHandle.USER_OWNER) {
4903            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4904            forwardingResolveInfo.noResourceId = true;
4905        }
4906        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4907        forwardingResolveInfo.priority = 0;
4908        forwardingResolveInfo.preferredOrder = 0;
4909        forwardingResolveInfo.match = 0;
4910        forwardingResolveInfo.isDefault = true;
4911        forwardingResolveInfo.filter = filter;
4912        forwardingResolveInfo.targetUserId = targetUserId;
4913        return forwardingResolveInfo;
4914    }
4915
4916    @Override
4917    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4918            Intent[] specifics, String[] specificTypes, Intent intent,
4919            String resolvedType, int flags, int userId) {
4920        if (!sUserManager.exists(userId)) return Collections.emptyList();
4921        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4922                false, "query intent activity options");
4923        final String resultsAction = intent.getAction();
4924
4925        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4926                | PackageManager.GET_RESOLVED_FILTER, userId);
4927
4928        if (DEBUG_INTENT_MATCHING) {
4929            Log.v(TAG, "Query " + intent + ": " + results);
4930        }
4931
4932        int specificsPos = 0;
4933        int N;
4934
4935        // todo: note that the algorithm used here is O(N^2).  This
4936        // isn't a problem in our current environment, but if we start running
4937        // into situations where we have more than 5 or 10 matches then this
4938        // should probably be changed to something smarter...
4939
4940        // First we go through and resolve each of the specific items
4941        // that were supplied, taking care of removing any corresponding
4942        // duplicate items in the generic resolve list.
4943        if (specifics != null) {
4944            for (int i=0; i<specifics.length; i++) {
4945                final Intent sintent = specifics[i];
4946                if (sintent == null) {
4947                    continue;
4948                }
4949
4950                if (DEBUG_INTENT_MATCHING) {
4951                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4952                }
4953
4954                String action = sintent.getAction();
4955                if (resultsAction != null && resultsAction.equals(action)) {
4956                    // If this action was explicitly requested, then don't
4957                    // remove things that have it.
4958                    action = null;
4959                }
4960
4961                ResolveInfo ri = null;
4962                ActivityInfo ai = null;
4963
4964                ComponentName comp = sintent.getComponent();
4965                if (comp == null) {
4966                    ri = resolveIntent(
4967                        sintent,
4968                        specificTypes != null ? specificTypes[i] : null,
4969                            flags, userId);
4970                    if (ri == null) {
4971                        continue;
4972                    }
4973                    if (ri == mResolveInfo) {
4974                        // ACK!  Must do something better with this.
4975                    }
4976                    ai = ri.activityInfo;
4977                    comp = new ComponentName(ai.applicationInfo.packageName,
4978                            ai.name);
4979                } else {
4980                    ai = getActivityInfo(comp, flags, userId);
4981                    if (ai == null) {
4982                        continue;
4983                    }
4984                }
4985
4986                // Look for any generic query activities that are duplicates
4987                // of this specific one, and remove them from the results.
4988                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4989                N = results.size();
4990                int j;
4991                for (j=specificsPos; j<N; j++) {
4992                    ResolveInfo sri = results.get(j);
4993                    if ((sri.activityInfo.name.equals(comp.getClassName())
4994                            && sri.activityInfo.applicationInfo.packageName.equals(
4995                                    comp.getPackageName()))
4996                        || (action != null && sri.filter.matchAction(action))) {
4997                        results.remove(j);
4998                        if (DEBUG_INTENT_MATCHING) Log.v(
4999                            TAG, "Removing duplicate item from " + j
5000                            + " due to specific " + specificsPos);
5001                        if (ri == null) {
5002                            ri = sri;
5003                        }
5004                        j--;
5005                        N--;
5006                    }
5007                }
5008
5009                // Add this specific item to its proper place.
5010                if (ri == null) {
5011                    ri = new ResolveInfo();
5012                    ri.activityInfo = ai;
5013                }
5014                results.add(specificsPos, ri);
5015                ri.specificIndex = i;
5016                specificsPos++;
5017            }
5018        }
5019
5020        // Now we go through the remaining generic results and remove any
5021        // duplicate actions that are found here.
5022        N = results.size();
5023        for (int i=specificsPos; i<N-1; i++) {
5024            final ResolveInfo rii = results.get(i);
5025            if (rii.filter == null) {
5026                continue;
5027            }
5028
5029            // Iterate over all of the actions of this result's intent
5030            // filter...  typically this should be just one.
5031            final Iterator<String> it = rii.filter.actionsIterator();
5032            if (it == null) {
5033                continue;
5034            }
5035            while (it.hasNext()) {
5036                final String action = it.next();
5037                if (resultsAction != null && resultsAction.equals(action)) {
5038                    // If this action was explicitly requested, then don't
5039                    // remove things that have it.
5040                    continue;
5041                }
5042                for (int j=i+1; j<N; j++) {
5043                    final ResolveInfo rij = results.get(j);
5044                    if (rij.filter != null && rij.filter.hasAction(action)) {
5045                        results.remove(j);
5046                        if (DEBUG_INTENT_MATCHING) Log.v(
5047                            TAG, "Removing duplicate item from " + j
5048                            + " due to action " + action + " at " + i);
5049                        j--;
5050                        N--;
5051                    }
5052                }
5053            }
5054
5055            // If the caller didn't request filter information, drop it now
5056            // so we don't have to marshall/unmarshall it.
5057            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5058                rii.filter = null;
5059            }
5060        }
5061
5062        // Filter out the caller activity if so requested.
5063        if (caller != null) {
5064            N = results.size();
5065            for (int i=0; i<N; i++) {
5066                ActivityInfo ainfo = results.get(i).activityInfo;
5067                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5068                        && caller.getClassName().equals(ainfo.name)) {
5069                    results.remove(i);
5070                    break;
5071                }
5072            }
5073        }
5074
5075        // If the caller didn't request filter information,
5076        // drop them now so we don't have to
5077        // marshall/unmarshall it.
5078        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5079            N = results.size();
5080            for (int i=0; i<N; i++) {
5081                results.get(i).filter = null;
5082            }
5083        }
5084
5085        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5086        return results;
5087    }
5088
5089    @Override
5090    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5091            int userId) {
5092        if (!sUserManager.exists(userId)) return Collections.emptyList();
5093        ComponentName comp = intent.getComponent();
5094        if (comp == null) {
5095            if (intent.getSelector() != null) {
5096                intent = intent.getSelector();
5097                comp = intent.getComponent();
5098            }
5099        }
5100        if (comp != null) {
5101            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5102            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5103            if (ai != null) {
5104                ResolveInfo ri = new ResolveInfo();
5105                ri.activityInfo = ai;
5106                list.add(ri);
5107            }
5108            return list;
5109        }
5110
5111        // reader
5112        synchronized (mPackages) {
5113            String pkgName = intent.getPackage();
5114            if (pkgName == null) {
5115                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5116            }
5117            final PackageParser.Package pkg = mPackages.get(pkgName);
5118            if (pkg != null) {
5119                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5120                        userId);
5121            }
5122            return null;
5123        }
5124    }
5125
5126    @Override
5127    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5128        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5129        if (!sUserManager.exists(userId)) return null;
5130        if (query != null) {
5131            if (query.size() >= 1) {
5132                // If there is more than one service with the same priority,
5133                // just arbitrarily pick the first one.
5134                return query.get(0);
5135            }
5136        }
5137        return null;
5138    }
5139
5140    @Override
5141    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5142            int userId) {
5143        if (!sUserManager.exists(userId)) return Collections.emptyList();
5144        ComponentName comp = intent.getComponent();
5145        if (comp == null) {
5146            if (intent.getSelector() != null) {
5147                intent = intent.getSelector();
5148                comp = intent.getComponent();
5149            }
5150        }
5151        if (comp != null) {
5152            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5153            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5154            if (si != null) {
5155                final ResolveInfo ri = new ResolveInfo();
5156                ri.serviceInfo = si;
5157                list.add(ri);
5158            }
5159            return list;
5160        }
5161
5162        // reader
5163        synchronized (mPackages) {
5164            String pkgName = intent.getPackage();
5165            if (pkgName == null) {
5166                return mServices.queryIntent(intent, resolvedType, flags, userId);
5167            }
5168            final PackageParser.Package pkg = mPackages.get(pkgName);
5169            if (pkg != null) {
5170                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5171                        userId);
5172            }
5173            return null;
5174        }
5175    }
5176
5177    @Override
5178    public List<ResolveInfo> queryIntentContentProviders(
5179            Intent intent, String resolvedType, int flags, int userId) {
5180        if (!sUserManager.exists(userId)) return Collections.emptyList();
5181        ComponentName comp = intent.getComponent();
5182        if (comp == null) {
5183            if (intent.getSelector() != null) {
5184                intent = intent.getSelector();
5185                comp = intent.getComponent();
5186            }
5187        }
5188        if (comp != null) {
5189            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5190            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5191            if (pi != null) {
5192                final ResolveInfo ri = new ResolveInfo();
5193                ri.providerInfo = pi;
5194                list.add(ri);
5195            }
5196            return list;
5197        }
5198
5199        // reader
5200        synchronized (mPackages) {
5201            String pkgName = intent.getPackage();
5202            if (pkgName == null) {
5203                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5204            }
5205            final PackageParser.Package pkg = mPackages.get(pkgName);
5206            if (pkg != null) {
5207                return mProviders.queryIntentForPackage(
5208                        intent, resolvedType, flags, pkg.providers, userId);
5209            }
5210            return null;
5211        }
5212    }
5213
5214    @Override
5215    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5216        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5217
5218        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5219
5220        // writer
5221        synchronized (mPackages) {
5222            ArrayList<PackageInfo> list;
5223            if (listUninstalled) {
5224                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5225                for (PackageSetting ps : mSettings.mPackages.values()) {
5226                    PackageInfo pi;
5227                    if (ps.pkg != null) {
5228                        pi = generatePackageInfo(ps.pkg, flags, userId);
5229                    } else {
5230                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5231                    }
5232                    if (pi != null) {
5233                        list.add(pi);
5234                    }
5235                }
5236            } else {
5237                list = new ArrayList<PackageInfo>(mPackages.size());
5238                for (PackageParser.Package p : mPackages.values()) {
5239                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5240                    if (pi != null) {
5241                        list.add(pi);
5242                    }
5243                }
5244            }
5245
5246            return new ParceledListSlice<PackageInfo>(list);
5247        }
5248    }
5249
5250    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5251            String[] permissions, boolean[] tmp, int flags, int userId) {
5252        int numMatch = 0;
5253        final PermissionsState permissionsState = ps.getPermissionsState();
5254        for (int i=0; i<permissions.length; i++) {
5255            final String permission = permissions[i];
5256            if (permissionsState.hasPermission(permission, userId)) {
5257                tmp[i] = true;
5258                numMatch++;
5259            } else {
5260                tmp[i] = false;
5261            }
5262        }
5263        if (numMatch == 0) {
5264            return;
5265        }
5266        PackageInfo pi;
5267        if (ps.pkg != null) {
5268            pi = generatePackageInfo(ps.pkg, flags, userId);
5269        } else {
5270            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5271        }
5272        // The above might return null in cases of uninstalled apps or install-state
5273        // skew across users/profiles.
5274        if (pi != null) {
5275            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5276                if (numMatch == permissions.length) {
5277                    pi.requestedPermissions = permissions;
5278                } else {
5279                    pi.requestedPermissions = new String[numMatch];
5280                    numMatch = 0;
5281                    for (int i=0; i<permissions.length; i++) {
5282                        if (tmp[i]) {
5283                            pi.requestedPermissions[numMatch] = permissions[i];
5284                            numMatch++;
5285                        }
5286                    }
5287                }
5288            }
5289            list.add(pi);
5290        }
5291    }
5292
5293    @Override
5294    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5295            String[] permissions, int flags, int userId) {
5296        if (!sUserManager.exists(userId)) return null;
5297        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5298
5299        // writer
5300        synchronized (mPackages) {
5301            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5302            boolean[] tmpBools = new boolean[permissions.length];
5303            if (listUninstalled) {
5304                for (PackageSetting ps : mSettings.mPackages.values()) {
5305                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5306                }
5307            } else {
5308                for (PackageParser.Package pkg : mPackages.values()) {
5309                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5310                    if (ps != null) {
5311                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5312                                userId);
5313                    }
5314                }
5315            }
5316
5317            return new ParceledListSlice<PackageInfo>(list);
5318        }
5319    }
5320
5321    @Override
5322    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5323        if (!sUserManager.exists(userId)) return null;
5324        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5325
5326        // writer
5327        synchronized (mPackages) {
5328            ArrayList<ApplicationInfo> list;
5329            if (listUninstalled) {
5330                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5331                for (PackageSetting ps : mSettings.mPackages.values()) {
5332                    ApplicationInfo ai;
5333                    if (ps.pkg != null) {
5334                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5335                                ps.readUserState(userId), userId);
5336                    } else {
5337                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5338                    }
5339                    if (ai != null) {
5340                        list.add(ai);
5341                    }
5342                }
5343            } else {
5344                list = new ArrayList<ApplicationInfo>(mPackages.size());
5345                for (PackageParser.Package p : mPackages.values()) {
5346                    if (p.mExtras != null) {
5347                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5348                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5349                        if (ai != null) {
5350                            list.add(ai);
5351                        }
5352                    }
5353                }
5354            }
5355
5356            return new ParceledListSlice<ApplicationInfo>(list);
5357        }
5358    }
5359
5360    public List<ApplicationInfo> getPersistentApplications(int flags) {
5361        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5362
5363        // reader
5364        synchronized (mPackages) {
5365            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5366            final int userId = UserHandle.getCallingUserId();
5367            while (i.hasNext()) {
5368                final PackageParser.Package p = i.next();
5369                if (p.applicationInfo != null
5370                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5371                        && (!mSafeMode || isSystemApp(p))) {
5372                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5373                    if (ps != null) {
5374                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5375                                ps.readUserState(userId), userId);
5376                        if (ai != null) {
5377                            finalList.add(ai);
5378                        }
5379                    }
5380                }
5381            }
5382        }
5383
5384        return finalList;
5385    }
5386
5387    @Override
5388    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5389        if (!sUserManager.exists(userId)) return null;
5390        // reader
5391        synchronized (mPackages) {
5392            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5393            PackageSetting ps = provider != null
5394                    ? mSettings.mPackages.get(provider.owner.packageName)
5395                    : null;
5396            return ps != null
5397                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5398                    && (!mSafeMode || (provider.info.applicationInfo.flags
5399                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5400                    ? PackageParser.generateProviderInfo(provider, flags,
5401                            ps.readUserState(userId), userId)
5402                    : null;
5403        }
5404    }
5405
5406    /**
5407     * @deprecated
5408     */
5409    @Deprecated
5410    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5411        // reader
5412        synchronized (mPackages) {
5413            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5414                    .entrySet().iterator();
5415            final int userId = UserHandle.getCallingUserId();
5416            while (i.hasNext()) {
5417                Map.Entry<String, PackageParser.Provider> entry = i.next();
5418                PackageParser.Provider p = entry.getValue();
5419                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5420
5421                if (ps != null && p.syncable
5422                        && (!mSafeMode || (p.info.applicationInfo.flags
5423                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5424                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5425                            ps.readUserState(userId), userId);
5426                    if (info != null) {
5427                        outNames.add(entry.getKey());
5428                        outInfo.add(info);
5429                    }
5430                }
5431            }
5432        }
5433    }
5434
5435    @Override
5436    public List<ProviderInfo> queryContentProviders(String processName,
5437            int uid, int flags) {
5438        ArrayList<ProviderInfo> finalList = null;
5439        // reader
5440        synchronized (mPackages) {
5441            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5442            final int userId = processName != null ?
5443                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5444            while (i.hasNext()) {
5445                final PackageParser.Provider p = i.next();
5446                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5447                if (ps != null && p.info.authority != null
5448                        && (processName == null
5449                                || (p.info.processName.equals(processName)
5450                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5451                        && mSettings.isEnabledLPr(p.info, flags, userId)
5452                        && (!mSafeMode
5453                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5454                    if (finalList == null) {
5455                        finalList = new ArrayList<ProviderInfo>(3);
5456                    }
5457                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5458                            ps.readUserState(userId), userId);
5459                    if (info != null) {
5460                        finalList.add(info);
5461                    }
5462                }
5463            }
5464        }
5465
5466        if (finalList != null) {
5467            Collections.sort(finalList, mProviderInitOrderSorter);
5468        }
5469
5470        return finalList;
5471    }
5472
5473    @Override
5474    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5475            int flags) {
5476        // reader
5477        synchronized (mPackages) {
5478            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5479            return PackageParser.generateInstrumentationInfo(i, flags);
5480        }
5481    }
5482
5483    @Override
5484    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5485            int flags) {
5486        ArrayList<InstrumentationInfo> finalList =
5487            new ArrayList<InstrumentationInfo>();
5488
5489        // reader
5490        synchronized (mPackages) {
5491            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5492            while (i.hasNext()) {
5493                final PackageParser.Instrumentation p = i.next();
5494                if (targetPackage == null
5495                        || targetPackage.equals(p.info.targetPackage)) {
5496                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5497                            flags);
5498                    if (ii != null) {
5499                        finalList.add(ii);
5500                    }
5501                }
5502            }
5503        }
5504
5505        return finalList;
5506    }
5507
5508    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5509        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5510        if (overlays == null) {
5511            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5512            return;
5513        }
5514        for (PackageParser.Package opkg : overlays.values()) {
5515            // Not much to do if idmap fails: we already logged the error
5516            // and we certainly don't want to abort installation of pkg simply
5517            // because an overlay didn't fit properly. For these reasons,
5518            // ignore the return value of createIdmapForPackagePairLI.
5519            createIdmapForPackagePairLI(pkg, opkg);
5520        }
5521    }
5522
5523    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5524            PackageParser.Package opkg) {
5525        if (!opkg.mTrustedOverlay) {
5526            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5527                    opkg.baseCodePath + ": overlay not trusted");
5528            return false;
5529        }
5530        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5531        if (overlaySet == null) {
5532            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5533                    opkg.baseCodePath + " but target package has no known overlays");
5534            return false;
5535        }
5536        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5537        // TODO: generate idmap for split APKs
5538        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5539            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5540                    + opkg.baseCodePath);
5541            return false;
5542        }
5543        PackageParser.Package[] overlayArray =
5544            overlaySet.values().toArray(new PackageParser.Package[0]);
5545        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5546            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5547                return p1.mOverlayPriority - p2.mOverlayPriority;
5548            }
5549        };
5550        Arrays.sort(overlayArray, cmp);
5551
5552        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5553        int i = 0;
5554        for (PackageParser.Package p : overlayArray) {
5555            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5556        }
5557        return true;
5558    }
5559
5560    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5561        final File[] files = dir.listFiles();
5562        if (ArrayUtils.isEmpty(files)) {
5563            Log.d(TAG, "No files in app dir " + dir);
5564            return;
5565        }
5566
5567        if (DEBUG_PACKAGE_SCANNING) {
5568            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5569                    + " flags=0x" + Integer.toHexString(parseFlags));
5570        }
5571
5572        for (File file : files) {
5573            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5574                    && !PackageInstallerService.isStageName(file.getName());
5575            if (!isPackage) {
5576                // Ignore entries which are not packages
5577                continue;
5578            }
5579            try {
5580                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5581                        scanFlags, currentTime, null);
5582            } catch (PackageManagerException e) {
5583                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5584
5585                // Delete invalid userdata apps
5586                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5587                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5588                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5589                    if (file.isDirectory()) {
5590                        mInstaller.rmPackageDir(file.getAbsolutePath());
5591                    } else {
5592                        file.delete();
5593                    }
5594                }
5595            }
5596        }
5597    }
5598
5599    private static File getSettingsProblemFile() {
5600        File dataDir = Environment.getDataDirectory();
5601        File systemDir = new File(dataDir, "system");
5602        File fname = new File(systemDir, "uiderrors.txt");
5603        return fname;
5604    }
5605
5606    static void reportSettingsProblem(int priority, String msg) {
5607        logCriticalInfo(priority, msg);
5608    }
5609
5610    static void logCriticalInfo(int priority, String msg) {
5611        Slog.println(priority, TAG, msg);
5612        EventLogTags.writePmCriticalInfo(msg);
5613        try {
5614            File fname = getSettingsProblemFile();
5615            FileOutputStream out = new FileOutputStream(fname, true);
5616            PrintWriter pw = new FastPrintWriter(out);
5617            SimpleDateFormat formatter = new SimpleDateFormat();
5618            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5619            pw.println(dateString + ": " + msg);
5620            pw.close();
5621            FileUtils.setPermissions(
5622                    fname.toString(),
5623                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5624                    -1, -1);
5625        } catch (java.io.IOException e) {
5626        }
5627    }
5628
5629    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5630            PackageParser.Package pkg, File srcFile, int parseFlags)
5631            throws PackageManagerException {
5632        if (ps != null
5633                && ps.codePath.equals(srcFile)
5634                && ps.timeStamp == srcFile.lastModified()
5635                && !isCompatSignatureUpdateNeeded(pkg)
5636                && !isRecoverSignatureUpdateNeeded(pkg)) {
5637            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5638            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5639            ArraySet<PublicKey> signingKs;
5640            synchronized (mPackages) {
5641                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5642            }
5643            if (ps.signatures.mSignatures != null
5644                    && ps.signatures.mSignatures.length != 0
5645                    && signingKs != null) {
5646                // Optimization: reuse the existing cached certificates
5647                // if the package appears to be unchanged.
5648                pkg.mSignatures = ps.signatures.mSignatures;
5649                pkg.mSigningKeys = signingKs;
5650                return;
5651            }
5652
5653            Slog.w(TAG, "PackageSetting for " + ps.name
5654                    + " is missing signatures.  Collecting certs again to recover them.");
5655        } else {
5656            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5657        }
5658
5659        try {
5660            pp.collectCertificates(pkg, parseFlags);
5661            pp.collectManifestDigest(pkg);
5662        } catch (PackageParserException e) {
5663            throw PackageManagerException.from(e);
5664        }
5665    }
5666
5667    /*
5668     *  Scan a package and return the newly parsed package.
5669     *  Returns null in case of errors and the error code is stored in mLastScanError
5670     */
5671    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5672            long currentTime, UserHandle user) throws PackageManagerException {
5673        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5674        parseFlags |= mDefParseFlags;
5675        PackageParser pp = new PackageParser();
5676        pp.setSeparateProcesses(mSeparateProcesses);
5677        pp.setOnlyCoreApps(mOnlyCore);
5678        pp.setDisplayMetrics(mMetrics);
5679
5680        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5681            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5682        }
5683
5684        final PackageParser.Package pkg;
5685        try {
5686            pkg = pp.parsePackage(scanFile, parseFlags);
5687        } catch (PackageParserException e) {
5688            throw PackageManagerException.from(e);
5689        }
5690
5691        PackageSetting ps = null;
5692        PackageSetting updatedPkg;
5693        // reader
5694        synchronized (mPackages) {
5695            // Look to see if we already know about this package.
5696            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5697            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5698                // This package has been renamed to its original name.  Let's
5699                // use that.
5700                ps = mSettings.peekPackageLPr(oldName);
5701            }
5702            // If there was no original package, see one for the real package name.
5703            if (ps == null) {
5704                ps = mSettings.peekPackageLPr(pkg.packageName);
5705            }
5706            // Check to see if this package could be hiding/updating a system
5707            // package.  Must look for it either under the original or real
5708            // package name depending on our state.
5709            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5710            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5711        }
5712        boolean updatedPkgBetter = false;
5713        // First check if this is a system package that may involve an update
5714        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5715            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5716            // it needs to drop FLAG_PRIVILEGED.
5717            if (locationIsPrivileged(scanFile)) {
5718                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5719            } else {
5720                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5721            }
5722
5723            if (ps != null && !ps.codePath.equals(scanFile)) {
5724                // The path has changed from what was last scanned...  check the
5725                // version of the new path against what we have stored to determine
5726                // what to do.
5727                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5728                if (pkg.mVersionCode <= ps.versionCode) {
5729                    // The system package has been updated and the code path does not match
5730                    // Ignore entry. Skip it.
5731                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5732                            + " ignored: updated version " + ps.versionCode
5733                            + " better than this " + pkg.mVersionCode);
5734                    if (!updatedPkg.codePath.equals(scanFile)) {
5735                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5736                                + ps.name + " changing from " + updatedPkg.codePathString
5737                                + " to " + scanFile);
5738                        updatedPkg.codePath = scanFile;
5739                        updatedPkg.codePathString = scanFile.toString();
5740                        updatedPkg.resourcePath = scanFile;
5741                        updatedPkg.resourcePathString = scanFile.toString();
5742                    }
5743                    updatedPkg.pkg = pkg;
5744                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5745                            "Package " + ps.name + " at " + scanFile
5746                                    + " ignored: updated version " + ps.versionCode
5747                                    + " better than this " + pkg.mVersionCode);
5748                } else {
5749                    // The current app on the system partition is better than
5750                    // what we have updated to on the data partition; switch
5751                    // back to the system partition version.
5752                    // At this point, its safely assumed that package installation for
5753                    // apps in system partition will go through. If not there won't be a working
5754                    // version of the app
5755                    // writer
5756                    synchronized (mPackages) {
5757                        // Just remove the loaded entries from package lists.
5758                        mPackages.remove(ps.name);
5759                    }
5760
5761                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5762                            + " reverting from " + ps.codePathString
5763                            + ": new version " + pkg.mVersionCode
5764                            + " better than installed " + ps.versionCode);
5765
5766                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5767                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5768                    synchronized (mInstallLock) {
5769                        args.cleanUpResourcesLI();
5770                    }
5771                    synchronized (mPackages) {
5772                        mSettings.enableSystemPackageLPw(ps.name);
5773                    }
5774                    updatedPkgBetter = true;
5775                }
5776            }
5777        }
5778
5779        if (updatedPkg != null) {
5780            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5781            // initially
5782            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5783
5784            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5785            // flag set initially
5786            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5787                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5788            }
5789        }
5790
5791        // Verify certificates against what was last scanned
5792        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5793
5794        /*
5795         * A new system app appeared, but we already had a non-system one of the
5796         * same name installed earlier.
5797         */
5798        boolean shouldHideSystemApp = false;
5799        if (updatedPkg == null && ps != null
5800                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5801            /*
5802             * Check to make sure the signatures match first. If they don't,
5803             * wipe the installed application and its data.
5804             */
5805            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5806                    != PackageManager.SIGNATURE_MATCH) {
5807                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5808                        + " signatures don't match existing userdata copy; removing");
5809                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5810                ps = null;
5811            } else {
5812                /*
5813                 * If the newly-added system app is an older version than the
5814                 * already installed version, hide it. It will be scanned later
5815                 * and re-added like an update.
5816                 */
5817                if (pkg.mVersionCode <= ps.versionCode) {
5818                    shouldHideSystemApp = true;
5819                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5820                            + " but new version " + pkg.mVersionCode + " better than installed "
5821                            + ps.versionCode + "; hiding system");
5822                } else {
5823                    /*
5824                     * The newly found system app is a newer version that the
5825                     * one previously installed. Simply remove the
5826                     * already-installed application and replace it with our own
5827                     * while keeping the application data.
5828                     */
5829                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5830                            + " reverting from " + ps.codePathString + ": new version "
5831                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5832                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5833                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5834                    synchronized (mInstallLock) {
5835                        args.cleanUpResourcesLI();
5836                    }
5837                }
5838            }
5839        }
5840
5841        // The apk is forward locked (not public) if its code and resources
5842        // are kept in different files. (except for app in either system or
5843        // vendor path).
5844        // TODO grab this value from PackageSettings
5845        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5846            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5847                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5848            }
5849        }
5850
5851        // TODO: extend to support forward-locked splits
5852        String resourcePath = null;
5853        String baseResourcePath = null;
5854        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5855            if (ps != null && ps.resourcePathString != null) {
5856                resourcePath = ps.resourcePathString;
5857                baseResourcePath = ps.resourcePathString;
5858            } else {
5859                // Should not happen at all. Just log an error.
5860                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5861            }
5862        } else {
5863            resourcePath = pkg.codePath;
5864            baseResourcePath = pkg.baseCodePath;
5865        }
5866
5867        // Set application objects path explicitly.
5868        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5869        pkg.applicationInfo.setCodePath(pkg.codePath);
5870        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5871        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5872        pkg.applicationInfo.setResourcePath(resourcePath);
5873        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5874        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5875
5876        // Note that we invoke the following method only if we are about to unpack an application
5877        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5878                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5879
5880        /*
5881         * If the system app should be overridden by a previously installed
5882         * data, hide the system app now and let the /data/app scan pick it up
5883         * again.
5884         */
5885        if (shouldHideSystemApp) {
5886            synchronized (mPackages) {
5887                /*
5888                 * We have to grant systems permissions before we hide, because
5889                 * grantPermissions will assume the package update is trying to
5890                 * expand its permissions.
5891                 */
5892                grantPermissionsLPw(pkg, true, pkg.packageName);
5893                mSettings.disableSystemPackageLPw(pkg.packageName);
5894            }
5895        }
5896
5897        return scannedPkg;
5898    }
5899
5900    private static String fixProcessName(String defProcessName,
5901            String processName, int uid) {
5902        if (processName == null) {
5903            return defProcessName;
5904        }
5905        return processName;
5906    }
5907
5908    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5909            throws PackageManagerException {
5910        if (pkgSetting.signatures.mSignatures != null) {
5911            // Already existing package. Make sure signatures match
5912            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5913                    == PackageManager.SIGNATURE_MATCH;
5914            if (!match) {
5915                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5916                        == PackageManager.SIGNATURE_MATCH;
5917            }
5918            if (!match) {
5919                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5920                        == PackageManager.SIGNATURE_MATCH;
5921            }
5922            if (!match) {
5923                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5924                        + pkg.packageName + " signatures do not match the "
5925                        + "previously installed version; ignoring!");
5926            }
5927        }
5928
5929        // Check for shared user signatures
5930        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5931            // Already existing package. Make sure signatures match
5932            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5933                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5934            if (!match) {
5935                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5936                        == PackageManager.SIGNATURE_MATCH;
5937            }
5938            if (!match) {
5939                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5940                        == PackageManager.SIGNATURE_MATCH;
5941            }
5942            if (!match) {
5943                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5944                        "Package " + pkg.packageName
5945                        + " has no signatures that match those in shared user "
5946                        + pkgSetting.sharedUser.name + "; ignoring!");
5947            }
5948        }
5949    }
5950
5951    /**
5952     * Enforces that only the system UID or root's UID can call a method exposed
5953     * via Binder.
5954     *
5955     * @param message used as message if SecurityException is thrown
5956     * @throws SecurityException if the caller is not system or root
5957     */
5958    private static final void enforceSystemOrRoot(String message) {
5959        final int uid = Binder.getCallingUid();
5960        if (uid != Process.SYSTEM_UID && uid != 0) {
5961            throw new SecurityException(message);
5962        }
5963    }
5964
5965    @Override
5966    public void performBootDexOpt() {
5967        enforceSystemOrRoot("Only the system can request dexopt be performed");
5968
5969        // Before everything else, see whether we need to fstrim.
5970        try {
5971            IMountService ms = PackageHelper.getMountService();
5972            if (ms != null) {
5973                final boolean isUpgrade = isUpgrade();
5974                boolean doTrim = isUpgrade;
5975                if (doTrim) {
5976                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5977                } else {
5978                    final long interval = android.provider.Settings.Global.getLong(
5979                            mContext.getContentResolver(),
5980                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5981                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5982                    if (interval > 0) {
5983                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5984                        if (timeSinceLast > interval) {
5985                            doTrim = true;
5986                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5987                                    + "; running immediately");
5988                        }
5989                    }
5990                }
5991                if (doTrim) {
5992                    if (!isFirstBoot()) {
5993                        try {
5994                            ActivityManagerNative.getDefault().showBootMessage(
5995                                    mContext.getResources().getString(
5996                                            R.string.android_upgrading_fstrim), true);
5997                        } catch (RemoteException e) {
5998                        }
5999                    }
6000                    ms.runMaintenance();
6001                }
6002            } else {
6003                Slog.e(TAG, "Mount service unavailable!");
6004            }
6005        } catch (RemoteException e) {
6006            // Can't happen; MountService is local
6007        }
6008
6009        final ArraySet<PackageParser.Package> pkgs;
6010        synchronized (mPackages) {
6011            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6012        }
6013
6014        if (pkgs != null) {
6015            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6016            // in case the device runs out of space.
6017            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6018            // Give priority to core apps.
6019            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6020                PackageParser.Package pkg = it.next();
6021                if (pkg.coreApp) {
6022                    if (DEBUG_DEXOPT) {
6023                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6024                    }
6025                    sortedPkgs.add(pkg);
6026                    it.remove();
6027                }
6028            }
6029            // Give priority to system apps that listen for pre boot complete.
6030            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6031            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6032            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6033                PackageParser.Package pkg = it.next();
6034                if (pkgNames.contains(pkg.packageName)) {
6035                    if (DEBUG_DEXOPT) {
6036                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6037                    }
6038                    sortedPkgs.add(pkg);
6039                    it.remove();
6040                }
6041            }
6042            // Give priority to system apps.
6043            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6044                PackageParser.Package pkg = it.next();
6045                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6046                    if (DEBUG_DEXOPT) {
6047                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6048                    }
6049                    sortedPkgs.add(pkg);
6050                    it.remove();
6051                }
6052            }
6053            // Give priority to updated system apps.
6054            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6055                PackageParser.Package pkg = it.next();
6056                if (pkg.isUpdatedSystemApp()) {
6057                    if (DEBUG_DEXOPT) {
6058                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6059                    }
6060                    sortedPkgs.add(pkg);
6061                    it.remove();
6062                }
6063            }
6064            // Give priority to apps that listen for boot complete.
6065            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6066            pkgNames = getPackageNamesForIntent(intent);
6067            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6068                PackageParser.Package pkg = it.next();
6069                if (pkgNames.contains(pkg.packageName)) {
6070                    if (DEBUG_DEXOPT) {
6071                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6072                    }
6073                    sortedPkgs.add(pkg);
6074                    it.remove();
6075                }
6076            }
6077            // Filter out packages that aren't recently used.
6078            filterRecentlyUsedApps(pkgs);
6079            // Add all remaining apps.
6080            for (PackageParser.Package pkg : pkgs) {
6081                if (DEBUG_DEXOPT) {
6082                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6083                }
6084                sortedPkgs.add(pkg);
6085            }
6086
6087            // If we want to be lazy, filter everything that wasn't recently used.
6088            if (mLazyDexOpt) {
6089                filterRecentlyUsedApps(sortedPkgs);
6090            }
6091
6092            int i = 0;
6093            int total = sortedPkgs.size();
6094            File dataDir = Environment.getDataDirectory();
6095            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6096            if (lowThreshold == 0) {
6097                throw new IllegalStateException("Invalid low memory threshold");
6098            }
6099            for (PackageParser.Package pkg : sortedPkgs) {
6100                long usableSpace = dataDir.getUsableSpace();
6101                if (usableSpace < lowThreshold) {
6102                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6103                    break;
6104                }
6105                performBootDexOpt(pkg, ++i, total);
6106            }
6107        }
6108    }
6109
6110    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6111        // Filter out packages that aren't recently used.
6112        //
6113        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6114        // should do a full dexopt.
6115        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6116            int total = pkgs.size();
6117            int skipped = 0;
6118            long now = System.currentTimeMillis();
6119            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6120                PackageParser.Package pkg = i.next();
6121                long then = pkg.mLastPackageUsageTimeInMills;
6122                if (then + mDexOptLRUThresholdInMills < now) {
6123                    if (DEBUG_DEXOPT) {
6124                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6125                              ((then == 0) ? "never" : new Date(then)));
6126                    }
6127                    i.remove();
6128                    skipped++;
6129                }
6130            }
6131            if (DEBUG_DEXOPT) {
6132                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6133            }
6134        }
6135    }
6136
6137    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6138        List<ResolveInfo> ris = null;
6139        try {
6140            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6141                    intent, null, 0, UserHandle.USER_OWNER);
6142        } catch (RemoteException e) {
6143        }
6144        ArraySet<String> pkgNames = new ArraySet<String>();
6145        if (ris != null) {
6146            for (ResolveInfo ri : ris) {
6147                pkgNames.add(ri.activityInfo.packageName);
6148            }
6149        }
6150        return pkgNames;
6151    }
6152
6153    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6154        if (DEBUG_DEXOPT) {
6155            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6156        }
6157        if (!isFirstBoot()) {
6158            try {
6159                ActivityManagerNative.getDefault().showBootMessage(
6160                        mContext.getResources().getString(R.string.android_upgrading_apk,
6161                                curr, total), true);
6162            } catch (RemoteException e) {
6163            }
6164        }
6165        PackageParser.Package p = pkg;
6166        synchronized (mInstallLock) {
6167            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6168                    false /* force dex */, false /* defer */, true /* include dependencies */);
6169        }
6170    }
6171
6172    @Override
6173    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6174        return performDexOpt(packageName, instructionSet, false);
6175    }
6176
6177    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6178        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6179        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6180        if (!dexopt && !updateUsage) {
6181            // We aren't going to dexopt or update usage, so bail early.
6182            return false;
6183        }
6184        PackageParser.Package p;
6185        final String targetInstructionSet;
6186        synchronized (mPackages) {
6187            p = mPackages.get(packageName);
6188            if (p == null) {
6189                return false;
6190            }
6191            if (updateUsage) {
6192                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6193            }
6194            mPackageUsage.write(false);
6195            if (!dexopt) {
6196                // We aren't going to dexopt, so bail early.
6197                return false;
6198            }
6199
6200            targetInstructionSet = instructionSet != null ? instructionSet :
6201                    getPrimaryInstructionSet(p.applicationInfo);
6202            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6203                return false;
6204            }
6205        }
6206        long callingId = Binder.clearCallingIdentity();
6207        try {
6208            synchronized (mInstallLock) {
6209                final String[] instructionSets = new String[] { targetInstructionSet };
6210                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6211                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6212                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6213            }
6214        } finally {
6215            Binder.restoreCallingIdentity(callingId);
6216        }
6217    }
6218
6219    public ArraySet<String> getPackagesThatNeedDexOpt() {
6220        ArraySet<String> pkgs = null;
6221        synchronized (mPackages) {
6222            for (PackageParser.Package p : mPackages.values()) {
6223                if (DEBUG_DEXOPT) {
6224                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6225                }
6226                if (!p.mDexOptPerformed.isEmpty()) {
6227                    continue;
6228                }
6229                if (pkgs == null) {
6230                    pkgs = new ArraySet<String>();
6231                }
6232                pkgs.add(p.packageName);
6233            }
6234        }
6235        return pkgs;
6236    }
6237
6238    public void shutdown() {
6239        mPackageUsage.write(true);
6240    }
6241
6242    @Override
6243    public void forceDexOpt(String packageName) {
6244        enforceSystemOrRoot("forceDexOpt");
6245
6246        PackageParser.Package pkg;
6247        synchronized (mPackages) {
6248            pkg = mPackages.get(packageName);
6249            if (pkg == null) {
6250                throw new IllegalArgumentException("Missing package: " + packageName);
6251            }
6252        }
6253
6254        synchronized (mInstallLock) {
6255            final String[] instructionSets = new String[] {
6256                    getPrimaryInstructionSet(pkg.applicationInfo) };
6257            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6258                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6259            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6260                throw new IllegalStateException("Failed to dexopt: " + res);
6261            }
6262        }
6263    }
6264
6265    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6266        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6267            Slog.w(TAG, "Unable to update from " + oldPkg.name
6268                    + " to " + newPkg.packageName
6269                    + ": old package not in system partition");
6270            return false;
6271        } else if (mPackages.get(oldPkg.name) != null) {
6272            Slog.w(TAG, "Unable to update from " + oldPkg.name
6273                    + " to " + newPkg.packageName
6274                    + ": old package still exists");
6275            return false;
6276        }
6277        return true;
6278    }
6279
6280    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6281        int[] users = sUserManager.getUserIds();
6282        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6283        if (res < 0) {
6284            return res;
6285        }
6286        for (int user : users) {
6287            if (user != 0) {
6288                res = mInstaller.createUserData(volumeUuid, packageName,
6289                        UserHandle.getUid(user, uid), user, seinfo);
6290                if (res < 0) {
6291                    return res;
6292                }
6293            }
6294        }
6295        return res;
6296    }
6297
6298    private int removeDataDirsLI(String volumeUuid, String packageName) {
6299        int[] users = sUserManager.getUserIds();
6300        int res = 0;
6301        for (int user : users) {
6302            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6303            if (resInner < 0) {
6304                res = resInner;
6305            }
6306        }
6307
6308        return res;
6309    }
6310
6311    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6312        int[] users = sUserManager.getUserIds();
6313        int res = 0;
6314        for (int user : users) {
6315            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6316            if (resInner < 0) {
6317                res = resInner;
6318            }
6319        }
6320        return res;
6321    }
6322
6323    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6324            PackageParser.Package changingLib) {
6325        if (file.path != null) {
6326            usesLibraryFiles.add(file.path);
6327            return;
6328        }
6329        PackageParser.Package p = mPackages.get(file.apk);
6330        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6331            // If we are doing this while in the middle of updating a library apk,
6332            // then we need to make sure to use that new apk for determining the
6333            // dependencies here.  (We haven't yet finished committing the new apk
6334            // to the package manager state.)
6335            if (p == null || p.packageName.equals(changingLib.packageName)) {
6336                p = changingLib;
6337            }
6338        }
6339        if (p != null) {
6340            usesLibraryFiles.addAll(p.getAllCodePaths());
6341        }
6342    }
6343
6344    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6345            PackageParser.Package changingLib) throws PackageManagerException {
6346        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6347            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6348            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6349            for (int i=0; i<N; i++) {
6350                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6351                if (file == null) {
6352                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6353                            "Package " + pkg.packageName + " requires unavailable shared library "
6354                            + pkg.usesLibraries.get(i) + "; failing!");
6355                }
6356                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6357            }
6358            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6359            for (int i=0; i<N; i++) {
6360                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6361                if (file == null) {
6362                    Slog.w(TAG, "Package " + pkg.packageName
6363                            + " desires unavailable shared library "
6364                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6365                } else {
6366                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6367                }
6368            }
6369            N = usesLibraryFiles.size();
6370            if (N > 0) {
6371                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6372            } else {
6373                pkg.usesLibraryFiles = null;
6374            }
6375        }
6376    }
6377
6378    private static boolean hasString(List<String> list, List<String> which) {
6379        if (list == null) {
6380            return false;
6381        }
6382        for (int i=list.size()-1; i>=0; i--) {
6383            for (int j=which.size()-1; j>=0; j--) {
6384                if (which.get(j).equals(list.get(i))) {
6385                    return true;
6386                }
6387            }
6388        }
6389        return false;
6390    }
6391
6392    private void updateAllSharedLibrariesLPw() {
6393        for (PackageParser.Package pkg : mPackages.values()) {
6394            try {
6395                updateSharedLibrariesLPw(pkg, null);
6396            } catch (PackageManagerException e) {
6397                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6398            }
6399        }
6400    }
6401
6402    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6403            PackageParser.Package changingPkg) {
6404        ArrayList<PackageParser.Package> res = null;
6405        for (PackageParser.Package pkg : mPackages.values()) {
6406            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6407                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6408                if (res == null) {
6409                    res = new ArrayList<PackageParser.Package>();
6410                }
6411                res.add(pkg);
6412                try {
6413                    updateSharedLibrariesLPw(pkg, changingPkg);
6414                } catch (PackageManagerException e) {
6415                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6416                }
6417            }
6418        }
6419        return res;
6420    }
6421
6422    /**
6423     * Derive the value of the {@code cpuAbiOverride} based on the provided
6424     * value and an optional stored value from the package settings.
6425     */
6426    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6427        String cpuAbiOverride = null;
6428
6429        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6430            cpuAbiOverride = null;
6431        } else if (abiOverride != null) {
6432            cpuAbiOverride = abiOverride;
6433        } else if (settings != null) {
6434            cpuAbiOverride = settings.cpuAbiOverrideString;
6435        }
6436
6437        return cpuAbiOverride;
6438    }
6439
6440    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6441            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6442        boolean success = false;
6443        try {
6444            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6445                    currentTime, user);
6446            success = true;
6447            return res;
6448        } finally {
6449            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6450                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6451            }
6452        }
6453    }
6454
6455    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6456            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6457        final File scanFile = new File(pkg.codePath);
6458        if (pkg.applicationInfo.getCodePath() == null ||
6459                pkg.applicationInfo.getResourcePath() == null) {
6460            // Bail out. The resource and code paths haven't been set.
6461            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6462                    "Code and resource paths haven't been set correctly");
6463        }
6464
6465        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6466            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6467        } else {
6468            // Only allow system apps to be flagged as core apps.
6469            pkg.coreApp = false;
6470        }
6471
6472        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6473            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6474        }
6475
6476        if (mCustomResolverComponentName != null &&
6477                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6478            setUpCustomResolverActivity(pkg);
6479        }
6480
6481        if (pkg.packageName.equals("android")) {
6482            synchronized (mPackages) {
6483                if (mAndroidApplication != null) {
6484                    Slog.w(TAG, "*************************************************");
6485                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6486                    Slog.w(TAG, " file=" + scanFile);
6487                    Slog.w(TAG, "*************************************************");
6488                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6489                            "Core android package being redefined.  Skipping.");
6490                }
6491
6492                // Set up information for our fall-back user intent resolution activity.
6493                mPlatformPackage = pkg;
6494                pkg.mVersionCode = mSdkVersion;
6495                mAndroidApplication = pkg.applicationInfo;
6496
6497                if (!mResolverReplaced) {
6498                    mResolveActivity.applicationInfo = mAndroidApplication;
6499                    mResolveActivity.name = ResolverActivity.class.getName();
6500                    mResolveActivity.packageName = mAndroidApplication.packageName;
6501                    mResolveActivity.processName = "system:ui";
6502                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6503                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6504                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6505                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6506                    mResolveActivity.exported = true;
6507                    mResolveActivity.enabled = true;
6508                    mResolveInfo.activityInfo = mResolveActivity;
6509                    mResolveInfo.priority = 0;
6510                    mResolveInfo.preferredOrder = 0;
6511                    mResolveInfo.match = 0;
6512                    mResolveComponentName = new ComponentName(
6513                            mAndroidApplication.packageName, mResolveActivity.name);
6514                }
6515            }
6516        }
6517
6518        if (DEBUG_PACKAGE_SCANNING) {
6519            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6520                Log.d(TAG, "Scanning package " + pkg.packageName);
6521        }
6522
6523        if (mPackages.containsKey(pkg.packageName)
6524                || mSharedLibraries.containsKey(pkg.packageName)) {
6525            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6526                    "Application package " + pkg.packageName
6527                    + " already installed.  Skipping duplicate.");
6528        }
6529
6530        // If we're only installing presumed-existing packages, require that the
6531        // scanned APK is both already known and at the path previously established
6532        // for it.  Previously unknown packages we pick up normally, but if we have an
6533        // a priori expectation about this package's install presence, enforce it.
6534        // With a singular exception for new system packages. When an OTA contains
6535        // a new system package, we allow the codepath to change from a system location
6536        // to the user-installed location. If we don't allow this change, any newer,
6537        // user-installed version of the application will be ignored.
6538        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6539            if (mExpectingBetter.containsKey(pkg.packageName)) {
6540                logCriticalInfo(Log.WARN,
6541                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6542            } else {
6543                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6544                if (known != null) {
6545                    if (DEBUG_PACKAGE_SCANNING) {
6546                        Log.d(TAG, "Examining " + pkg.codePath
6547                                + " and requiring known paths " + known.codePathString
6548                                + " & " + known.resourcePathString);
6549                    }
6550                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6551                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6552                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6553                                "Application package " + pkg.packageName
6554                                + " found at " + pkg.applicationInfo.getCodePath()
6555                                + " but expected at " + known.codePathString + "; ignoring.");
6556                    }
6557                }
6558            }
6559        }
6560
6561        // Initialize package source and resource directories
6562        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6563        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6564
6565        SharedUserSetting suid = null;
6566        PackageSetting pkgSetting = null;
6567
6568        if (!isSystemApp(pkg)) {
6569            // Only system apps can use these features.
6570            pkg.mOriginalPackages = null;
6571            pkg.mRealPackage = null;
6572            pkg.mAdoptPermissions = null;
6573        }
6574
6575        // writer
6576        synchronized (mPackages) {
6577            if (pkg.mSharedUserId != null) {
6578                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6579                if (suid == null) {
6580                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6581                            "Creating application package " + pkg.packageName
6582                            + " for shared user failed");
6583                }
6584                if (DEBUG_PACKAGE_SCANNING) {
6585                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6586                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6587                                + "): packages=" + suid.packages);
6588                }
6589            }
6590
6591            // Check if we are renaming from an original package name.
6592            PackageSetting origPackage = null;
6593            String realName = null;
6594            if (pkg.mOriginalPackages != null) {
6595                // This package may need to be renamed to a previously
6596                // installed name.  Let's check on that...
6597                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6598                if (pkg.mOriginalPackages.contains(renamed)) {
6599                    // This package had originally been installed as the
6600                    // original name, and we have already taken care of
6601                    // transitioning to the new one.  Just update the new
6602                    // one to continue using the old name.
6603                    realName = pkg.mRealPackage;
6604                    if (!pkg.packageName.equals(renamed)) {
6605                        // Callers into this function may have already taken
6606                        // care of renaming the package; only do it here if
6607                        // it is not already done.
6608                        pkg.setPackageName(renamed);
6609                    }
6610
6611                } else {
6612                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6613                        if ((origPackage = mSettings.peekPackageLPr(
6614                                pkg.mOriginalPackages.get(i))) != null) {
6615                            // We do have the package already installed under its
6616                            // original name...  should we use it?
6617                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6618                                // New package is not compatible with original.
6619                                origPackage = null;
6620                                continue;
6621                            } else if (origPackage.sharedUser != null) {
6622                                // Make sure uid is compatible between packages.
6623                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6624                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6625                                            + " to " + pkg.packageName + ": old uid "
6626                                            + origPackage.sharedUser.name
6627                                            + " differs from " + pkg.mSharedUserId);
6628                                    origPackage = null;
6629                                    continue;
6630                                }
6631                            } else {
6632                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6633                                        + pkg.packageName + " to old name " + origPackage.name);
6634                            }
6635                            break;
6636                        }
6637                    }
6638                }
6639            }
6640
6641            if (mTransferedPackages.contains(pkg.packageName)) {
6642                Slog.w(TAG, "Package " + pkg.packageName
6643                        + " was transferred to another, but its .apk remains");
6644            }
6645
6646            // Just create the setting, don't add it yet. For already existing packages
6647            // the PkgSetting exists already and doesn't have to be created.
6648            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6649                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6650                    pkg.applicationInfo.primaryCpuAbi,
6651                    pkg.applicationInfo.secondaryCpuAbi,
6652                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6653                    user, false);
6654            if (pkgSetting == null) {
6655                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6656                        "Creating application package " + pkg.packageName + " failed");
6657            }
6658
6659            if (pkgSetting.origPackage != null) {
6660                // If we are first transitioning from an original package,
6661                // fix up the new package's name now.  We need to do this after
6662                // looking up the package under its new name, so getPackageLP
6663                // can take care of fiddling things correctly.
6664                pkg.setPackageName(origPackage.name);
6665
6666                // File a report about this.
6667                String msg = "New package " + pkgSetting.realName
6668                        + " renamed to replace old package " + pkgSetting.name;
6669                reportSettingsProblem(Log.WARN, msg);
6670
6671                // Make a note of it.
6672                mTransferedPackages.add(origPackage.name);
6673
6674                // No longer need to retain this.
6675                pkgSetting.origPackage = null;
6676            }
6677
6678            if (realName != null) {
6679                // Make a note of it.
6680                mTransferedPackages.add(pkg.packageName);
6681            }
6682
6683            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6684                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6685            }
6686
6687            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6688                // Check all shared libraries and map to their actual file path.
6689                // We only do this here for apps not on a system dir, because those
6690                // are the only ones that can fail an install due to this.  We
6691                // will take care of the system apps by updating all of their
6692                // library paths after the scan is done.
6693                updateSharedLibrariesLPw(pkg, null);
6694            }
6695
6696            if (mFoundPolicyFile) {
6697                SELinuxMMAC.assignSeinfoValue(pkg);
6698            }
6699
6700            pkg.applicationInfo.uid = pkgSetting.appId;
6701            pkg.mExtras = pkgSetting;
6702            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6703                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6704                    // We just determined the app is signed correctly, so bring
6705                    // over the latest parsed certs.
6706                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6707                } else {
6708                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6709                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6710                                "Package " + pkg.packageName + " upgrade keys do not match the "
6711                                + "previously installed version");
6712                    } else {
6713                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6714                        String msg = "System package " + pkg.packageName
6715                            + " signature changed; retaining data.";
6716                        reportSettingsProblem(Log.WARN, msg);
6717                    }
6718                }
6719            } else {
6720                try {
6721                    verifySignaturesLP(pkgSetting, pkg);
6722                    // We just determined the app is signed correctly, so bring
6723                    // over the latest parsed certs.
6724                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6725                } catch (PackageManagerException e) {
6726                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6727                        throw e;
6728                    }
6729                    // The signature has changed, but this package is in the system
6730                    // image...  let's recover!
6731                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6732                    // However...  if this package is part of a shared user, but it
6733                    // doesn't match the signature of the shared user, let's fail.
6734                    // What this means is that you can't change the signatures
6735                    // associated with an overall shared user, which doesn't seem all
6736                    // that unreasonable.
6737                    if (pkgSetting.sharedUser != null) {
6738                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6739                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6740                            throw new PackageManagerException(
6741                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6742                                            "Signature mismatch for shared user : "
6743                                            + pkgSetting.sharedUser);
6744                        }
6745                    }
6746                    // File a report about this.
6747                    String msg = "System package " + pkg.packageName
6748                        + " signature changed; retaining data.";
6749                    reportSettingsProblem(Log.WARN, msg);
6750                }
6751            }
6752            // Verify that this new package doesn't have any content providers
6753            // that conflict with existing packages.  Only do this if the
6754            // package isn't already installed, since we don't want to break
6755            // things that are installed.
6756            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6757                final int N = pkg.providers.size();
6758                int i;
6759                for (i=0; i<N; i++) {
6760                    PackageParser.Provider p = pkg.providers.get(i);
6761                    if (p.info.authority != null) {
6762                        String names[] = p.info.authority.split(";");
6763                        for (int j = 0; j < names.length; j++) {
6764                            if (mProvidersByAuthority.containsKey(names[j])) {
6765                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6766                                final String otherPackageName =
6767                                        ((other != null && other.getComponentName() != null) ?
6768                                                other.getComponentName().getPackageName() : "?");
6769                                throw new PackageManagerException(
6770                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6771                                                "Can't install because provider name " + names[j]
6772                                                + " (in package " + pkg.applicationInfo.packageName
6773                                                + ") is already used by " + otherPackageName);
6774                            }
6775                        }
6776                    }
6777                }
6778            }
6779
6780            if (pkg.mAdoptPermissions != null) {
6781                // This package wants to adopt ownership of permissions from
6782                // another package.
6783                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6784                    final String origName = pkg.mAdoptPermissions.get(i);
6785                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6786                    if (orig != null) {
6787                        if (verifyPackageUpdateLPr(orig, pkg)) {
6788                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6789                                    + pkg.packageName);
6790                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6791                        }
6792                    }
6793                }
6794            }
6795        }
6796
6797        final String pkgName = pkg.packageName;
6798
6799        final long scanFileTime = scanFile.lastModified();
6800        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6801        pkg.applicationInfo.processName = fixProcessName(
6802                pkg.applicationInfo.packageName,
6803                pkg.applicationInfo.processName,
6804                pkg.applicationInfo.uid);
6805
6806        File dataPath;
6807        if (mPlatformPackage == pkg) {
6808            // The system package is special.
6809            dataPath = new File(Environment.getDataDirectory(), "system");
6810
6811            pkg.applicationInfo.dataDir = dataPath.getPath();
6812
6813        } else {
6814            // This is a normal package, need to make its data directory.
6815            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6816                    UserHandle.USER_OWNER, pkg.packageName);
6817
6818            boolean uidError = false;
6819            if (dataPath.exists()) {
6820                int currentUid = 0;
6821                try {
6822                    StructStat stat = Os.stat(dataPath.getPath());
6823                    currentUid = stat.st_uid;
6824                } catch (ErrnoException e) {
6825                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6826                }
6827
6828                // If we have mismatched owners for the data path, we have a problem.
6829                if (currentUid != pkg.applicationInfo.uid) {
6830                    boolean recovered = false;
6831                    if (currentUid == 0) {
6832                        // The directory somehow became owned by root.  Wow.
6833                        // This is probably because the system was stopped while
6834                        // installd was in the middle of messing with its libs
6835                        // directory.  Ask installd to fix that.
6836                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6837                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6838                        if (ret >= 0) {
6839                            recovered = true;
6840                            String msg = "Package " + pkg.packageName
6841                                    + " unexpectedly changed to uid 0; recovered to " +
6842                                    + pkg.applicationInfo.uid;
6843                            reportSettingsProblem(Log.WARN, msg);
6844                        }
6845                    }
6846                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6847                            || (scanFlags&SCAN_BOOTING) != 0)) {
6848                        // If this is a system app, we can at least delete its
6849                        // current data so the application will still work.
6850                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6851                        if (ret >= 0) {
6852                            // TODO: Kill the processes first
6853                            // Old data gone!
6854                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6855                                    ? "System package " : "Third party package ";
6856                            String msg = prefix + pkg.packageName
6857                                    + " has changed from uid: "
6858                                    + currentUid + " to "
6859                                    + pkg.applicationInfo.uid + "; old data erased";
6860                            reportSettingsProblem(Log.WARN, msg);
6861                            recovered = true;
6862
6863                            // And now re-install the app.
6864                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6865                                    pkg.applicationInfo.seinfo);
6866                            if (ret == -1) {
6867                                // Ack should not happen!
6868                                msg = prefix + pkg.packageName
6869                                        + " could not have data directory re-created after delete.";
6870                                reportSettingsProblem(Log.WARN, msg);
6871                                throw new PackageManagerException(
6872                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6873                            }
6874                        }
6875                        if (!recovered) {
6876                            mHasSystemUidErrors = true;
6877                        }
6878                    } else if (!recovered) {
6879                        // If we allow this install to proceed, we will be broken.
6880                        // Abort, abort!
6881                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6882                                "scanPackageLI");
6883                    }
6884                    if (!recovered) {
6885                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6886                            + pkg.applicationInfo.uid + "/fs_"
6887                            + currentUid;
6888                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6889                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6890                        String msg = "Package " + pkg.packageName
6891                                + " has mismatched uid: "
6892                                + currentUid + " on disk, "
6893                                + pkg.applicationInfo.uid + " in settings";
6894                        // writer
6895                        synchronized (mPackages) {
6896                            mSettings.mReadMessages.append(msg);
6897                            mSettings.mReadMessages.append('\n');
6898                            uidError = true;
6899                            if (!pkgSetting.uidError) {
6900                                reportSettingsProblem(Log.ERROR, msg);
6901                            }
6902                        }
6903                    }
6904                }
6905                pkg.applicationInfo.dataDir = dataPath.getPath();
6906                if (mShouldRestoreconData) {
6907                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6908                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6909                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6910                }
6911            } else {
6912                if (DEBUG_PACKAGE_SCANNING) {
6913                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6914                        Log.v(TAG, "Want this data dir: " + dataPath);
6915                }
6916                //invoke installer to do the actual installation
6917                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6918                        pkg.applicationInfo.seinfo);
6919                if (ret < 0) {
6920                    // Error from installer
6921                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6922                            "Unable to create data dirs [errorCode=" + ret + "]");
6923                }
6924
6925                if (dataPath.exists()) {
6926                    pkg.applicationInfo.dataDir = dataPath.getPath();
6927                } else {
6928                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6929                    pkg.applicationInfo.dataDir = null;
6930                }
6931            }
6932
6933            pkgSetting.uidError = uidError;
6934        }
6935
6936        final String path = scanFile.getPath();
6937        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6938
6939        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6940            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6941
6942            // Some system apps still use directory structure for native libraries
6943            // in which case we might end up not detecting abi solely based on apk
6944            // structure. Try to detect abi based on directory structure.
6945            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6946                    pkg.applicationInfo.primaryCpuAbi == null) {
6947                setBundledAppAbisAndRoots(pkg, pkgSetting);
6948                setNativeLibraryPaths(pkg);
6949            }
6950
6951        } else {
6952            if ((scanFlags & SCAN_MOVE) != 0) {
6953                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6954                // but we already have this packages package info in the PackageSetting. We just
6955                // use that and derive the native library path based on the new codepath.
6956                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6957                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6958            }
6959
6960            // Set native library paths again. For moves, the path will be updated based on the
6961            // ABIs we've determined above. For non-moves, the path will be updated based on the
6962            // ABIs we determined during compilation, but the path will depend on the final
6963            // package path (after the rename away from the stage path).
6964            setNativeLibraryPaths(pkg);
6965        }
6966
6967        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6968        final int[] userIds = sUserManager.getUserIds();
6969        synchronized (mInstallLock) {
6970            // Make sure all user data directories are ready to roll; we're okay
6971            // if they already exist
6972            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6973                for (int userId : userIds) {
6974                    if (userId != 0) {
6975                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6976                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6977                                pkg.applicationInfo.seinfo);
6978                    }
6979                }
6980            }
6981
6982            // Create a native library symlink only if we have native libraries
6983            // and if the native libraries are 32 bit libraries. We do not provide
6984            // this symlink for 64 bit libraries.
6985            if (pkg.applicationInfo.primaryCpuAbi != null &&
6986                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6987                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6988                for (int userId : userIds) {
6989                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6990                            nativeLibPath, userId) < 0) {
6991                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6992                                "Failed linking native library dir (user=" + userId + ")");
6993                    }
6994                }
6995            }
6996        }
6997
6998        // This is a special case for the "system" package, where the ABI is
6999        // dictated by the zygote configuration (and init.rc). We should keep track
7000        // of this ABI so that we can deal with "normal" applications that run under
7001        // the same UID correctly.
7002        if (mPlatformPackage == pkg) {
7003            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7004                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7005        }
7006
7007        // If there's a mismatch between the abi-override in the package setting
7008        // and the abiOverride specified for the install. Warn about this because we
7009        // would've already compiled the app without taking the package setting into
7010        // account.
7011        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7012            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7013                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7014                        " for package: " + pkg.packageName);
7015            }
7016        }
7017
7018        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7019        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7020        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7021
7022        // Copy the derived override back to the parsed package, so that we can
7023        // update the package settings accordingly.
7024        pkg.cpuAbiOverride = cpuAbiOverride;
7025
7026        if (DEBUG_ABI_SELECTION) {
7027            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7028                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7029                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7030        }
7031
7032        // Push the derived path down into PackageSettings so we know what to
7033        // clean up at uninstall time.
7034        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7035
7036        if (DEBUG_ABI_SELECTION) {
7037            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7038                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7039                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7040        }
7041
7042        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7043            // We don't do this here during boot because we can do it all
7044            // at once after scanning all existing packages.
7045            //
7046            // We also do this *before* we perform dexopt on this package, so that
7047            // we can avoid redundant dexopts, and also to make sure we've got the
7048            // code and package path correct.
7049            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7050                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7051        }
7052
7053        if ((scanFlags & SCAN_NO_DEX) == 0) {
7054            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7055                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7056            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7057                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7058            }
7059        }
7060        if (mFactoryTest && pkg.requestedPermissions.contains(
7061                android.Manifest.permission.FACTORY_TEST)) {
7062            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7063        }
7064
7065        ArrayList<PackageParser.Package> clientLibPkgs = null;
7066
7067        // writer
7068        synchronized (mPackages) {
7069            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7070                // Only system apps can add new shared libraries.
7071                if (pkg.libraryNames != null) {
7072                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7073                        String name = pkg.libraryNames.get(i);
7074                        boolean allowed = false;
7075                        if (pkg.isUpdatedSystemApp()) {
7076                            // New library entries can only be added through the
7077                            // system image.  This is important to get rid of a lot
7078                            // of nasty edge cases: for example if we allowed a non-
7079                            // system update of the app to add a library, then uninstalling
7080                            // the update would make the library go away, and assumptions
7081                            // we made such as through app install filtering would now
7082                            // have allowed apps on the device which aren't compatible
7083                            // with it.  Better to just have the restriction here, be
7084                            // conservative, and create many fewer cases that can negatively
7085                            // impact the user experience.
7086                            final PackageSetting sysPs = mSettings
7087                                    .getDisabledSystemPkgLPr(pkg.packageName);
7088                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7089                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7090                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7091                                        allowed = true;
7092                                        allowed = true;
7093                                        break;
7094                                    }
7095                                }
7096                            }
7097                        } else {
7098                            allowed = true;
7099                        }
7100                        if (allowed) {
7101                            if (!mSharedLibraries.containsKey(name)) {
7102                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7103                            } else if (!name.equals(pkg.packageName)) {
7104                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7105                                        + name + " already exists; skipping");
7106                            }
7107                        } else {
7108                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7109                                    + name + " that is not declared on system image; skipping");
7110                        }
7111                    }
7112                    if ((scanFlags&SCAN_BOOTING) == 0) {
7113                        // If we are not booting, we need to update any applications
7114                        // that are clients of our shared library.  If we are booting,
7115                        // this will all be done once the scan is complete.
7116                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7117                    }
7118                }
7119            }
7120        }
7121
7122        // We also need to dexopt any apps that are dependent on this library.  Note that
7123        // if these fail, we should abort the install since installing the library will
7124        // result in some apps being broken.
7125        if (clientLibPkgs != null) {
7126            if ((scanFlags & SCAN_NO_DEX) == 0) {
7127                for (int i = 0; i < clientLibPkgs.size(); i++) {
7128                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7129                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7130                            null /* instruction sets */, forceDex,
7131                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7132                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7133                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7134                                "scanPackageLI failed to dexopt clientLibPkgs");
7135                    }
7136                }
7137            }
7138        }
7139
7140        // Request the ActivityManager to kill the process(only for existing packages)
7141        // so that we do not end up in a confused state while the user is still using the older
7142        // version of the application while the new one gets installed.
7143        if ((scanFlags & SCAN_REPLACING) != 0) {
7144            killApplication(pkg.applicationInfo.packageName,
7145                        pkg.applicationInfo.uid, "replace pkg");
7146        }
7147
7148        // Also need to kill any apps that are dependent on the library.
7149        if (clientLibPkgs != null) {
7150            for (int i=0; i<clientLibPkgs.size(); i++) {
7151                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7152                killApplication(clientPkg.applicationInfo.packageName,
7153                        clientPkg.applicationInfo.uid, "update lib");
7154            }
7155        }
7156
7157        // Make sure we're not adding any bogus keyset info
7158        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7159        ksms.assertScannedPackageValid(pkg);
7160
7161        // writer
7162        synchronized (mPackages) {
7163            // We don't expect installation to fail beyond this point
7164
7165            // Add the new setting to mSettings
7166            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7167            // Add the new setting to mPackages
7168            mPackages.put(pkg.applicationInfo.packageName, pkg);
7169            // Make sure we don't accidentally delete its data.
7170            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7171            while (iter.hasNext()) {
7172                PackageCleanItem item = iter.next();
7173                if (pkgName.equals(item.packageName)) {
7174                    iter.remove();
7175                }
7176            }
7177
7178            // Take care of first install / last update times.
7179            if (currentTime != 0) {
7180                if (pkgSetting.firstInstallTime == 0) {
7181                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7182                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7183                    pkgSetting.lastUpdateTime = currentTime;
7184                }
7185            } else if (pkgSetting.firstInstallTime == 0) {
7186                // We need *something*.  Take time time stamp of the file.
7187                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7188            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7189                if (scanFileTime != pkgSetting.timeStamp) {
7190                    // A package on the system image has changed; consider this
7191                    // to be an update.
7192                    pkgSetting.lastUpdateTime = scanFileTime;
7193                }
7194            }
7195
7196            // Add the package's KeySets to the global KeySetManagerService
7197            ksms.addScannedPackageLPw(pkg);
7198
7199            int N = pkg.providers.size();
7200            StringBuilder r = null;
7201            int i;
7202            for (i=0; i<N; i++) {
7203                PackageParser.Provider p = pkg.providers.get(i);
7204                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7205                        p.info.processName, pkg.applicationInfo.uid);
7206                mProviders.addProvider(p);
7207                p.syncable = p.info.isSyncable;
7208                if (p.info.authority != null) {
7209                    String names[] = p.info.authority.split(";");
7210                    p.info.authority = null;
7211                    for (int j = 0; j < names.length; j++) {
7212                        if (j == 1 && p.syncable) {
7213                            // We only want the first authority for a provider to possibly be
7214                            // syncable, so if we already added this provider using a different
7215                            // authority clear the syncable flag. We copy the provider before
7216                            // changing it because the mProviders object contains a reference
7217                            // to a provider that we don't want to change.
7218                            // Only do this for the second authority since the resulting provider
7219                            // object can be the same for all future authorities for this provider.
7220                            p = new PackageParser.Provider(p);
7221                            p.syncable = false;
7222                        }
7223                        if (!mProvidersByAuthority.containsKey(names[j])) {
7224                            mProvidersByAuthority.put(names[j], p);
7225                            if (p.info.authority == null) {
7226                                p.info.authority = names[j];
7227                            } else {
7228                                p.info.authority = p.info.authority + ";" + names[j];
7229                            }
7230                            if (DEBUG_PACKAGE_SCANNING) {
7231                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7232                                    Log.d(TAG, "Registered content provider: " + names[j]
7233                                            + ", className = " + p.info.name + ", isSyncable = "
7234                                            + p.info.isSyncable);
7235                            }
7236                        } else {
7237                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7238                            Slog.w(TAG, "Skipping provider name " + names[j] +
7239                                    " (in package " + pkg.applicationInfo.packageName +
7240                                    "): name already used by "
7241                                    + ((other != null && other.getComponentName() != null)
7242                                            ? other.getComponentName().getPackageName() : "?"));
7243                        }
7244                    }
7245                }
7246                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7247                    if (r == null) {
7248                        r = new StringBuilder(256);
7249                    } else {
7250                        r.append(' ');
7251                    }
7252                    r.append(p.info.name);
7253                }
7254            }
7255            if (r != null) {
7256                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7257            }
7258
7259            N = pkg.services.size();
7260            r = null;
7261            for (i=0; i<N; i++) {
7262                PackageParser.Service s = pkg.services.get(i);
7263                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7264                        s.info.processName, pkg.applicationInfo.uid);
7265                mServices.addService(s);
7266                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7267                    if (r == null) {
7268                        r = new StringBuilder(256);
7269                    } else {
7270                        r.append(' ');
7271                    }
7272                    r.append(s.info.name);
7273                }
7274            }
7275            if (r != null) {
7276                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7277            }
7278
7279            N = pkg.receivers.size();
7280            r = null;
7281            for (i=0; i<N; i++) {
7282                PackageParser.Activity a = pkg.receivers.get(i);
7283                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7284                        a.info.processName, pkg.applicationInfo.uid);
7285                mReceivers.addActivity(a, "receiver");
7286                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7287                    if (r == null) {
7288                        r = new StringBuilder(256);
7289                    } else {
7290                        r.append(' ');
7291                    }
7292                    r.append(a.info.name);
7293                }
7294            }
7295            if (r != null) {
7296                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7297            }
7298
7299            N = pkg.activities.size();
7300            r = null;
7301            for (i=0; i<N; i++) {
7302                PackageParser.Activity a = pkg.activities.get(i);
7303                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7304                        a.info.processName, pkg.applicationInfo.uid);
7305                mActivities.addActivity(a, "activity");
7306                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7307                    if (r == null) {
7308                        r = new StringBuilder(256);
7309                    } else {
7310                        r.append(' ');
7311                    }
7312                    r.append(a.info.name);
7313                }
7314            }
7315            if (r != null) {
7316                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7317            }
7318
7319            N = pkg.permissionGroups.size();
7320            r = null;
7321            for (i=0; i<N; i++) {
7322                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7323                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7324                if (cur == null) {
7325                    mPermissionGroups.put(pg.info.name, pg);
7326                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7327                        if (r == null) {
7328                            r = new StringBuilder(256);
7329                        } else {
7330                            r.append(' ');
7331                        }
7332                        r.append(pg.info.name);
7333                    }
7334                } else {
7335                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7336                            + pg.info.packageName + " ignored: original from "
7337                            + cur.info.packageName);
7338                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7339                        if (r == null) {
7340                            r = new StringBuilder(256);
7341                        } else {
7342                            r.append(' ');
7343                        }
7344                        r.append("DUP:");
7345                        r.append(pg.info.name);
7346                    }
7347                }
7348            }
7349            if (r != null) {
7350                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7351            }
7352
7353            N = pkg.permissions.size();
7354            r = null;
7355            for (i=0; i<N; i++) {
7356                PackageParser.Permission p = pkg.permissions.get(i);
7357
7358                // Assume by default that we did not install this permission into the system.
7359                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7360
7361                // Now that permission groups have a special meaning, we ignore permission
7362                // groups for legacy apps to prevent unexpected behavior. In particular,
7363                // permissions for one app being granted to someone just becuase they happen
7364                // to be in a group defined by another app (before this had no implications).
7365                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7366                    p.group = mPermissionGroups.get(p.info.group);
7367                    // Warn for a permission in an unknown group.
7368                    if (p.info.group != null && p.group == null) {
7369                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7370                                + p.info.packageName + " in an unknown group " + p.info.group);
7371                    }
7372                }
7373
7374                ArrayMap<String, BasePermission> permissionMap =
7375                        p.tree ? mSettings.mPermissionTrees
7376                                : mSettings.mPermissions;
7377                BasePermission bp = permissionMap.get(p.info.name);
7378
7379                // Allow system apps to redefine non-system permissions
7380                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7381                    final boolean currentOwnerIsSystem = (bp.perm != null
7382                            && isSystemApp(bp.perm.owner));
7383                    if (isSystemApp(p.owner)) {
7384                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7385                            // It's a built-in permission and no owner, take ownership now
7386                            bp.packageSetting = pkgSetting;
7387                            bp.perm = p;
7388                            bp.uid = pkg.applicationInfo.uid;
7389                            bp.sourcePackage = p.info.packageName;
7390                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7391                        } else if (!currentOwnerIsSystem) {
7392                            String msg = "New decl " + p.owner + " of permission  "
7393                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7394                            reportSettingsProblem(Log.WARN, msg);
7395                            bp = null;
7396                        }
7397                    }
7398                }
7399
7400                if (bp == null) {
7401                    bp = new BasePermission(p.info.name, p.info.packageName,
7402                            BasePermission.TYPE_NORMAL);
7403                    permissionMap.put(p.info.name, bp);
7404                }
7405
7406                if (bp.perm == null) {
7407                    if (bp.sourcePackage == null
7408                            || bp.sourcePackage.equals(p.info.packageName)) {
7409                        BasePermission tree = findPermissionTreeLP(p.info.name);
7410                        if (tree == null
7411                                || tree.sourcePackage.equals(p.info.packageName)) {
7412                            bp.packageSetting = pkgSetting;
7413                            bp.perm = p;
7414                            bp.uid = pkg.applicationInfo.uid;
7415                            bp.sourcePackage = p.info.packageName;
7416                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7417                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7418                                if (r == null) {
7419                                    r = new StringBuilder(256);
7420                                } else {
7421                                    r.append(' ');
7422                                }
7423                                r.append(p.info.name);
7424                            }
7425                        } else {
7426                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7427                                    + p.info.packageName + " ignored: base tree "
7428                                    + tree.name + " is from package "
7429                                    + tree.sourcePackage);
7430                        }
7431                    } else {
7432                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7433                                + p.info.packageName + " ignored: original from "
7434                                + bp.sourcePackage);
7435                    }
7436                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7437                    if (r == null) {
7438                        r = new StringBuilder(256);
7439                    } else {
7440                        r.append(' ');
7441                    }
7442                    r.append("DUP:");
7443                    r.append(p.info.name);
7444                }
7445                if (bp.perm == p) {
7446                    bp.protectionLevel = p.info.protectionLevel;
7447                }
7448            }
7449
7450            if (r != null) {
7451                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7452            }
7453
7454            N = pkg.instrumentation.size();
7455            r = null;
7456            for (i=0; i<N; i++) {
7457                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7458                a.info.packageName = pkg.applicationInfo.packageName;
7459                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7460                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7461                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7462                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7463                a.info.dataDir = pkg.applicationInfo.dataDir;
7464
7465                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7466                // need other information about the application, like the ABI and what not ?
7467                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7468                mInstrumentation.put(a.getComponentName(), a);
7469                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7470                    if (r == null) {
7471                        r = new StringBuilder(256);
7472                    } else {
7473                        r.append(' ');
7474                    }
7475                    r.append(a.info.name);
7476                }
7477            }
7478            if (r != null) {
7479                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7480            }
7481
7482            if (pkg.protectedBroadcasts != null) {
7483                N = pkg.protectedBroadcasts.size();
7484                for (i=0; i<N; i++) {
7485                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7486                }
7487            }
7488
7489            pkgSetting.setTimeStamp(scanFileTime);
7490
7491            // Create idmap files for pairs of (packages, overlay packages).
7492            // Note: "android", ie framework-res.apk, is handled by native layers.
7493            if (pkg.mOverlayTarget != null) {
7494                // This is an overlay package.
7495                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7496                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7497                        mOverlays.put(pkg.mOverlayTarget,
7498                                new ArrayMap<String, PackageParser.Package>());
7499                    }
7500                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7501                    map.put(pkg.packageName, pkg);
7502                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7503                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7504                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7505                                "scanPackageLI failed to createIdmap");
7506                    }
7507                }
7508            } else if (mOverlays.containsKey(pkg.packageName) &&
7509                    !pkg.packageName.equals("android")) {
7510                // This is a regular package, with one or more known overlay packages.
7511                createIdmapsForPackageLI(pkg);
7512            }
7513        }
7514
7515        return pkg;
7516    }
7517
7518    /**
7519     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7520     * is derived purely on the basis of the contents of {@code scanFile} and
7521     * {@code cpuAbiOverride}.
7522     *
7523     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7524     */
7525    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7526                                 String cpuAbiOverride, boolean extractLibs)
7527            throws PackageManagerException {
7528        // TODO: We can probably be smarter about this stuff. For installed apps,
7529        // we can calculate this information at install time once and for all. For
7530        // system apps, we can probably assume that this information doesn't change
7531        // after the first boot scan. As things stand, we do lots of unnecessary work.
7532
7533        // Give ourselves some initial paths; we'll come back for another
7534        // pass once we've determined ABI below.
7535        setNativeLibraryPaths(pkg);
7536
7537        // We would never need to extract libs for forward-locked and external packages,
7538        // since the container service will do it for us. We shouldn't attempt to
7539        // extract libs from system app when it was not updated.
7540        if (pkg.isForwardLocked() || isExternal(pkg) ||
7541            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7542            extractLibs = false;
7543        }
7544
7545        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7546        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7547
7548        NativeLibraryHelper.Handle handle = null;
7549        try {
7550            handle = NativeLibraryHelper.Handle.create(pkg);
7551            // TODO(multiArch): This can be null for apps that didn't go through the
7552            // usual installation process. We can calculate it again, like we
7553            // do during install time.
7554            //
7555            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7556            // unnecessary.
7557            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7558
7559            // Null out the abis so that they can be recalculated.
7560            pkg.applicationInfo.primaryCpuAbi = null;
7561            pkg.applicationInfo.secondaryCpuAbi = null;
7562            if (isMultiArch(pkg.applicationInfo)) {
7563                // Warn if we've set an abiOverride for multi-lib packages..
7564                // By definition, we need to copy both 32 and 64 bit libraries for
7565                // such packages.
7566                if (pkg.cpuAbiOverride != null
7567                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7568                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7569                }
7570
7571                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7572                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7573                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7574                    if (extractLibs) {
7575                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7576                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7577                                useIsaSpecificSubdirs);
7578                    } else {
7579                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7580                    }
7581                }
7582
7583                maybeThrowExceptionForMultiArchCopy(
7584                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7585
7586                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7587                    if (extractLibs) {
7588                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7589                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7590                                useIsaSpecificSubdirs);
7591                    } else {
7592                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7593                    }
7594                }
7595
7596                maybeThrowExceptionForMultiArchCopy(
7597                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7598
7599                if (abi64 >= 0) {
7600                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7601                }
7602
7603                if (abi32 >= 0) {
7604                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7605                    if (abi64 >= 0) {
7606                        pkg.applicationInfo.secondaryCpuAbi = abi;
7607                    } else {
7608                        pkg.applicationInfo.primaryCpuAbi = abi;
7609                    }
7610                }
7611            } else {
7612                String[] abiList = (cpuAbiOverride != null) ?
7613                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7614
7615                // Enable gross and lame hacks for apps that are built with old
7616                // SDK tools. We must scan their APKs for renderscript bitcode and
7617                // not launch them if it's present. Don't bother checking on devices
7618                // that don't have 64 bit support.
7619                boolean needsRenderScriptOverride = false;
7620                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7621                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7622                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7623                    needsRenderScriptOverride = true;
7624                }
7625
7626                final int copyRet;
7627                if (extractLibs) {
7628                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7629                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7630                } else {
7631                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7632                }
7633
7634                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7635                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7636                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7637                }
7638
7639                if (copyRet >= 0) {
7640                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7641                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7642                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7643                } else if (needsRenderScriptOverride) {
7644                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7645                }
7646            }
7647        } catch (IOException ioe) {
7648            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7649        } finally {
7650            IoUtils.closeQuietly(handle);
7651        }
7652
7653        // Now that we've calculated the ABIs and determined if it's an internal app,
7654        // we will go ahead and populate the nativeLibraryPath.
7655        setNativeLibraryPaths(pkg);
7656    }
7657
7658    /**
7659     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7660     * i.e, so that all packages can be run inside a single process if required.
7661     *
7662     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7663     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7664     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7665     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7666     * updating a package that belongs to a shared user.
7667     *
7668     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7669     * adds unnecessary complexity.
7670     */
7671    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7672            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7673        String requiredInstructionSet = null;
7674        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7675            requiredInstructionSet = VMRuntime.getInstructionSet(
7676                     scannedPackage.applicationInfo.primaryCpuAbi);
7677        }
7678
7679        PackageSetting requirer = null;
7680        for (PackageSetting ps : packagesForUser) {
7681            // If packagesForUser contains scannedPackage, we skip it. This will happen
7682            // when scannedPackage is an update of an existing package. Without this check,
7683            // we will never be able to change the ABI of any package belonging to a shared
7684            // user, even if it's compatible with other packages.
7685            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7686                if (ps.primaryCpuAbiString == null) {
7687                    continue;
7688                }
7689
7690                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7691                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7692                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7693                    // this but there's not much we can do.
7694                    String errorMessage = "Instruction set mismatch, "
7695                            + ((requirer == null) ? "[caller]" : requirer)
7696                            + " requires " + requiredInstructionSet + " whereas " + ps
7697                            + " requires " + instructionSet;
7698                    Slog.w(TAG, errorMessage);
7699                }
7700
7701                if (requiredInstructionSet == null) {
7702                    requiredInstructionSet = instructionSet;
7703                    requirer = ps;
7704                }
7705            }
7706        }
7707
7708        if (requiredInstructionSet != null) {
7709            String adjustedAbi;
7710            if (requirer != null) {
7711                // requirer != null implies that either scannedPackage was null or that scannedPackage
7712                // did not require an ABI, in which case we have to adjust scannedPackage to match
7713                // the ABI of the set (which is the same as requirer's ABI)
7714                adjustedAbi = requirer.primaryCpuAbiString;
7715                if (scannedPackage != null) {
7716                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7717                }
7718            } else {
7719                // requirer == null implies that we're updating all ABIs in the set to
7720                // match scannedPackage.
7721                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7722            }
7723
7724            for (PackageSetting ps : packagesForUser) {
7725                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7726                    if (ps.primaryCpuAbiString != null) {
7727                        continue;
7728                    }
7729
7730                    ps.primaryCpuAbiString = adjustedAbi;
7731                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7732                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7733                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7734
7735                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7736                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7737                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7738                            ps.primaryCpuAbiString = null;
7739                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7740                            return;
7741                        } else {
7742                            mInstaller.rmdex(ps.codePathString,
7743                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7744                        }
7745                    }
7746                }
7747            }
7748        }
7749    }
7750
7751    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7752        synchronized (mPackages) {
7753            mResolverReplaced = true;
7754            // Set up information for custom user intent resolution activity.
7755            mResolveActivity.applicationInfo = pkg.applicationInfo;
7756            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7757            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7758            mResolveActivity.processName = pkg.applicationInfo.packageName;
7759            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7760            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7761                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7762            mResolveActivity.theme = 0;
7763            mResolveActivity.exported = true;
7764            mResolveActivity.enabled = true;
7765            mResolveInfo.activityInfo = mResolveActivity;
7766            mResolveInfo.priority = 0;
7767            mResolveInfo.preferredOrder = 0;
7768            mResolveInfo.match = 0;
7769            mResolveComponentName = mCustomResolverComponentName;
7770            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7771                    mResolveComponentName);
7772        }
7773    }
7774
7775    private static String calculateBundledApkRoot(final String codePathString) {
7776        final File codePath = new File(codePathString);
7777        final File codeRoot;
7778        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7779            codeRoot = Environment.getRootDirectory();
7780        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7781            codeRoot = Environment.getOemDirectory();
7782        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7783            codeRoot = Environment.getVendorDirectory();
7784        } else {
7785            // Unrecognized code path; take its top real segment as the apk root:
7786            // e.g. /something/app/blah.apk => /something
7787            try {
7788                File f = codePath.getCanonicalFile();
7789                File parent = f.getParentFile();    // non-null because codePath is a file
7790                File tmp;
7791                while ((tmp = parent.getParentFile()) != null) {
7792                    f = parent;
7793                    parent = tmp;
7794                }
7795                codeRoot = f;
7796                Slog.w(TAG, "Unrecognized code path "
7797                        + codePath + " - using " + codeRoot);
7798            } catch (IOException e) {
7799                // Can't canonicalize the code path -- shenanigans?
7800                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7801                return Environment.getRootDirectory().getPath();
7802            }
7803        }
7804        return codeRoot.getPath();
7805    }
7806
7807    /**
7808     * Derive and set the location of native libraries for the given package,
7809     * which varies depending on where and how the package was installed.
7810     */
7811    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7812        final ApplicationInfo info = pkg.applicationInfo;
7813        final String codePath = pkg.codePath;
7814        final File codeFile = new File(codePath);
7815        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7816        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7817
7818        info.nativeLibraryRootDir = null;
7819        info.nativeLibraryRootRequiresIsa = false;
7820        info.nativeLibraryDir = null;
7821        info.secondaryNativeLibraryDir = null;
7822
7823        if (isApkFile(codeFile)) {
7824            // Monolithic install
7825            if (bundledApp) {
7826                // If "/system/lib64/apkname" exists, assume that is the per-package
7827                // native library directory to use; otherwise use "/system/lib/apkname".
7828                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7829                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7830                        getPrimaryInstructionSet(info));
7831
7832                // This is a bundled system app so choose the path based on the ABI.
7833                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7834                // is just the default path.
7835                final String apkName = deriveCodePathName(codePath);
7836                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7837                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7838                        apkName).getAbsolutePath();
7839
7840                if (info.secondaryCpuAbi != null) {
7841                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7842                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7843                            secondaryLibDir, apkName).getAbsolutePath();
7844                }
7845            } else if (asecApp) {
7846                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7847                        .getAbsolutePath();
7848            } else {
7849                final String apkName = deriveCodePathName(codePath);
7850                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7851                        .getAbsolutePath();
7852            }
7853
7854            info.nativeLibraryRootRequiresIsa = false;
7855            info.nativeLibraryDir = info.nativeLibraryRootDir;
7856        } else {
7857            // Cluster install
7858            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7859            info.nativeLibraryRootRequiresIsa = true;
7860
7861            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7862                    getPrimaryInstructionSet(info)).getAbsolutePath();
7863
7864            if (info.secondaryCpuAbi != null) {
7865                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7866                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7867            }
7868        }
7869    }
7870
7871    /**
7872     * Calculate the abis and roots for a bundled app. These can uniquely
7873     * be determined from the contents of the system partition, i.e whether
7874     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7875     * of this information, and instead assume that the system was built
7876     * sensibly.
7877     */
7878    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7879                                           PackageSetting pkgSetting) {
7880        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7881
7882        // If "/system/lib64/apkname" exists, assume that is the per-package
7883        // native library directory to use; otherwise use "/system/lib/apkname".
7884        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7885        setBundledAppAbi(pkg, apkRoot, apkName);
7886        // pkgSetting might be null during rescan following uninstall of updates
7887        // to a bundled app, so accommodate that possibility.  The settings in
7888        // that case will be established later from the parsed package.
7889        //
7890        // If the settings aren't null, sync them up with what we've just derived.
7891        // note that apkRoot isn't stored in the package settings.
7892        if (pkgSetting != null) {
7893            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7894            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7895        }
7896    }
7897
7898    /**
7899     * Deduces the ABI of a bundled app and sets the relevant fields on the
7900     * parsed pkg object.
7901     *
7902     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7903     *        under which system libraries are installed.
7904     * @param apkName the name of the installed package.
7905     */
7906    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7907        final File codeFile = new File(pkg.codePath);
7908
7909        final boolean has64BitLibs;
7910        final boolean has32BitLibs;
7911        if (isApkFile(codeFile)) {
7912            // Monolithic install
7913            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7914            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7915        } else {
7916            // Cluster install
7917            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7918            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7919                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7920                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7921                has64BitLibs = (new File(rootDir, isa)).exists();
7922            } else {
7923                has64BitLibs = false;
7924            }
7925            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7926                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7927                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7928                has32BitLibs = (new File(rootDir, isa)).exists();
7929            } else {
7930                has32BitLibs = false;
7931            }
7932        }
7933
7934        if (has64BitLibs && !has32BitLibs) {
7935            // The package has 64 bit libs, but not 32 bit libs. Its primary
7936            // ABI should be 64 bit. We can safely assume here that the bundled
7937            // native libraries correspond to the most preferred ABI in the list.
7938
7939            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7940            pkg.applicationInfo.secondaryCpuAbi = null;
7941        } else if (has32BitLibs && !has64BitLibs) {
7942            // The package has 32 bit libs but not 64 bit libs. Its primary
7943            // ABI should be 32 bit.
7944
7945            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7946            pkg.applicationInfo.secondaryCpuAbi = null;
7947        } else if (has32BitLibs && has64BitLibs) {
7948            // The application has both 64 and 32 bit bundled libraries. We check
7949            // here that the app declares multiArch support, and warn if it doesn't.
7950            //
7951            // We will be lenient here and record both ABIs. The primary will be the
7952            // ABI that's higher on the list, i.e, a device that's configured to prefer
7953            // 64 bit apps will see a 64 bit primary ABI,
7954
7955            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7956                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7957            }
7958
7959            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7960                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7961                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7962            } else {
7963                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7964                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7965            }
7966        } else {
7967            pkg.applicationInfo.primaryCpuAbi = null;
7968            pkg.applicationInfo.secondaryCpuAbi = null;
7969        }
7970    }
7971
7972    private void killApplication(String pkgName, int appId, String reason) {
7973        // Request the ActivityManager to kill the process(only for existing packages)
7974        // so that we do not end up in a confused state while the user is still using the older
7975        // version of the application while the new one gets installed.
7976        IActivityManager am = ActivityManagerNative.getDefault();
7977        if (am != null) {
7978            try {
7979                am.killApplicationWithAppId(pkgName, appId, reason);
7980            } catch (RemoteException e) {
7981            }
7982        }
7983    }
7984
7985    void removePackageLI(PackageSetting ps, boolean chatty) {
7986        if (DEBUG_INSTALL) {
7987            if (chatty)
7988                Log.d(TAG, "Removing package " + ps.name);
7989        }
7990
7991        // writer
7992        synchronized (mPackages) {
7993            mPackages.remove(ps.name);
7994            final PackageParser.Package pkg = ps.pkg;
7995            if (pkg != null) {
7996                cleanPackageDataStructuresLILPw(pkg, chatty);
7997            }
7998        }
7999    }
8000
8001    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8002        if (DEBUG_INSTALL) {
8003            if (chatty)
8004                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8005        }
8006
8007        // writer
8008        synchronized (mPackages) {
8009            mPackages.remove(pkg.applicationInfo.packageName);
8010            cleanPackageDataStructuresLILPw(pkg, chatty);
8011        }
8012    }
8013
8014    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8015        int N = pkg.providers.size();
8016        StringBuilder r = null;
8017        int i;
8018        for (i=0; i<N; i++) {
8019            PackageParser.Provider p = pkg.providers.get(i);
8020            mProviders.removeProvider(p);
8021            if (p.info.authority == null) {
8022
8023                /* There was another ContentProvider with this authority when
8024                 * this app was installed so this authority is null,
8025                 * Ignore it as we don't have to unregister the provider.
8026                 */
8027                continue;
8028            }
8029            String names[] = p.info.authority.split(";");
8030            for (int j = 0; j < names.length; j++) {
8031                if (mProvidersByAuthority.get(names[j]) == p) {
8032                    mProvidersByAuthority.remove(names[j]);
8033                    if (DEBUG_REMOVE) {
8034                        if (chatty)
8035                            Log.d(TAG, "Unregistered content provider: " + names[j]
8036                                    + ", className = " + p.info.name + ", isSyncable = "
8037                                    + p.info.isSyncable);
8038                    }
8039                }
8040            }
8041            if (DEBUG_REMOVE && chatty) {
8042                if (r == null) {
8043                    r = new StringBuilder(256);
8044                } else {
8045                    r.append(' ');
8046                }
8047                r.append(p.info.name);
8048            }
8049        }
8050        if (r != null) {
8051            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8052        }
8053
8054        N = pkg.services.size();
8055        r = null;
8056        for (i=0; i<N; i++) {
8057            PackageParser.Service s = pkg.services.get(i);
8058            mServices.removeService(s);
8059            if (chatty) {
8060                if (r == null) {
8061                    r = new StringBuilder(256);
8062                } else {
8063                    r.append(' ');
8064                }
8065                r.append(s.info.name);
8066            }
8067        }
8068        if (r != null) {
8069            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8070        }
8071
8072        N = pkg.receivers.size();
8073        r = null;
8074        for (i=0; i<N; i++) {
8075            PackageParser.Activity a = pkg.receivers.get(i);
8076            mReceivers.removeActivity(a, "receiver");
8077            if (DEBUG_REMOVE && chatty) {
8078                if (r == null) {
8079                    r = new StringBuilder(256);
8080                } else {
8081                    r.append(' ');
8082                }
8083                r.append(a.info.name);
8084            }
8085        }
8086        if (r != null) {
8087            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8088        }
8089
8090        N = pkg.activities.size();
8091        r = null;
8092        for (i=0; i<N; i++) {
8093            PackageParser.Activity a = pkg.activities.get(i);
8094            mActivities.removeActivity(a, "activity");
8095            if (DEBUG_REMOVE && chatty) {
8096                if (r == null) {
8097                    r = new StringBuilder(256);
8098                } else {
8099                    r.append(' ');
8100                }
8101                r.append(a.info.name);
8102            }
8103        }
8104        if (r != null) {
8105            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8106        }
8107
8108        N = pkg.permissions.size();
8109        r = null;
8110        for (i=0; i<N; i++) {
8111            PackageParser.Permission p = pkg.permissions.get(i);
8112            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8113            if (bp == null) {
8114                bp = mSettings.mPermissionTrees.get(p.info.name);
8115            }
8116            if (bp != null && bp.perm == p) {
8117                bp.perm = null;
8118                if (DEBUG_REMOVE && chatty) {
8119                    if (r == null) {
8120                        r = new StringBuilder(256);
8121                    } else {
8122                        r.append(' ');
8123                    }
8124                    r.append(p.info.name);
8125                }
8126            }
8127            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8128                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8129                if (appOpPerms != null) {
8130                    appOpPerms.remove(pkg.packageName);
8131                }
8132            }
8133        }
8134        if (r != null) {
8135            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8136        }
8137
8138        N = pkg.requestedPermissions.size();
8139        r = null;
8140        for (i=0; i<N; i++) {
8141            String perm = pkg.requestedPermissions.get(i);
8142            BasePermission bp = mSettings.mPermissions.get(perm);
8143            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8144                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8145                if (appOpPerms != null) {
8146                    appOpPerms.remove(pkg.packageName);
8147                    if (appOpPerms.isEmpty()) {
8148                        mAppOpPermissionPackages.remove(perm);
8149                    }
8150                }
8151            }
8152        }
8153        if (r != null) {
8154            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8155        }
8156
8157        N = pkg.instrumentation.size();
8158        r = null;
8159        for (i=0; i<N; i++) {
8160            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8161            mInstrumentation.remove(a.getComponentName());
8162            if (DEBUG_REMOVE && chatty) {
8163                if (r == null) {
8164                    r = new StringBuilder(256);
8165                } else {
8166                    r.append(' ');
8167                }
8168                r.append(a.info.name);
8169            }
8170        }
8171        if (r != null) {
8172            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8173        }
8174
8175        r = null;
8176        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8177            // Only system apps can hold shared libraries.
8178            if (pkg.libraryNames != null) {
8179                for (i=0; i<pkg.libraryNames.size(); i++) {
8180                    String name = pkg.libraryNames.get(i);
8181                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8182                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8183                        mSharedLibraries.remove(name);
8184                        if (DEBUG_REMOVE && chatty) {
8185                            if (r == null) {
8186                                r = new StringBuilder(256);
8187                            } else {
8188                                r.append(' ');
8189                            }
8190                            r.append(name);
8191                        }
8192                    }
8193                }
8194            }
8195        }
8196        if (r != null) {
8197            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8198        }
8199    }
8200
8201    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8202        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8203            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8204                return true;
8205            }
8206        }
8207        return false;
8208    }
8209
8210    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8211    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8212    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8213
8214    private void updatePermissionsLPw(String changingPkg,
8215            PackageParser.Package pkgInfo, int flags) {
8216        // Make sure there are no dangling permission trees.
8217        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8218        while (it.hasNext()) {
8219            final BasePermission bp = it.next();
8220            if (bp.packageSetting == null) {
8221                // We may not yet have parsed the package, so just see if
8222                // we still know about its settings.
8223                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8224            }
8225            if (bp.packageSetting == null) {
8226                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8227                        + " from package " + bp.sourcePackage);
8228                it.remove();
8229            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8230                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8231                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8232                            + " from package " + bp.sourcePackage);
8233                    flags |= UPDATE_PERMISSIONS_ALL;
8234                    it.remove();
8235                }
8236            }
8237        }
8238
8239        // Make sure all dynamic permissions have been assigned to a package,
8240        // and make sure there are no dangling permissions.
8241        it = mSettings.mPermissions.values().iterator();
8242        while (it.hasNext()) {
8243            final BasePermission bp = it.next();
8244            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8245                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8246                        + bp.name + " pkg=" + bp.sourcePackage
8247                        + " info=" + bp.pendingInfo);
8248                if (bp.packageSetting == null && bp.pendingInfo != null) {
8249                    final BasePermission tree = findPermissionTreeLP(bp.name);
8250                    if (tree != null && tree.perm != null) {
8251                        bp.packageSetting = tree.packageSetting;
8252                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8253                                new PermissionInfo(bp.pendingInfo));
8254                        bp.perm.info.packageName = tree.perm.info.packageName;
8255                        bp.perm.info.name = bp.name;
8256                        bp.uid = tree.uid;
8257                    }
8258                }
8259            }
8260            if (bp.packageSetting == null) {
8261                // We may not yet have parsed the package, so just see if
8262                // we still know about its settings.
8263                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8264            }
8265            if (bp.packageSetting == null) {
8266                Slog.w(TAG, "Removing dangling permission: " + bp.name
8267                        + " from package " + bp.sourcePackage);
8268                it.remove();
8269            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8270                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8271                    Slog.i(TAG, "Removing old permission: " + bp.name
8272                            + " from package " + bp.sourcePackage);
8273                    flags |= UPDATE_PERMISSIONS_ALL;
8274                    it.remove();
8275                }
8276            }
8277        }
8278
8279        // Now update the permissions for all packages, in particular
8280        // replace the granted permissions of the system packages.
8281        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8282            for (PackageParser.Package pkg : mPackages.values()) {
8283                if (pkg != pkgInfo) {
8284                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8285                            changingPkg);
8286                }
8287            }
8288        }
8289
8290        if (pkgInfo != null) {
8291            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8292        }
8293    }
8294
8295    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8296            String packageOfInterest) {
8297        // IMPORTANT: There are two types of permissions: install and runtime.
8298        // Install time permissions are granted when the app is installed to
8299        // all device users and users added in the future. Runtime permissions
8300        // are granted at runtime explicitly to specific users. Normal and signature
8301        // protected permissions are install time permissions. Dangerous permissions
8302        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8303        // otherwise they are runtime permissions. This function does not manage
8304        // runtime permissions except for the case an app targeting Lollipop MR1
8305        // being upgraded to target a newer SDK, in which case dangerous permissions
8306        // are transformed from install time to runtime ones.
8307
8308        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8309        if (ps == null) {
8310            return;
8311        }
8312
8313        PermissionsState permissionsState = ps.getPermissionsState();
8314        PermissionsState origPermissions = permissionsState;
8315
8316        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8317
8318        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8319
8320        boolean changedInstallPermission = false;
8321
8322        if (replace) {
8323            ps.installPermissionsFixed = false;
8324            if (!ps.isSharedUser()) {
8325                origPermissions = new PermissionsState(permissionsState);
8326                permissionsState.reset();
8327            }
8328        }
8329
8330        permissionsState.setGlobalGids(mGlobalGids);
8331
8332        final int N = pkg.requestedPermissions.size();
8333        for (int i=0; i<N; i++) {
8334            final String name = pkg.requestedPermissions.get(i);
8335            final BasePermission bp = mSettings.mPermissions.get(name);
8336
8337            if (DEBUG_INSTALL) {
8338                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8339            }
8340
8341            if (bp == null || bp.packageSetting == null) {
8342                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8343                    Slog.w(TAG, "Unknown permission " + name
8344                            + " in package " + pkg.packageName);
8345                }
8346                continue;
8347            }
8348
8349            final String perm = bp.name;
8350            boolean allowedSig = false;
8351            int grant = GRANT_DENIED;
8352
8353            // Keep track of app op permissions.
8354            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8355                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8356                if (pkgs == null) {
8357                    pkgs = new ArraySet<>();
8358                    mAppOpPermissionPackages.put(bp.name, pkgs);
8359                }
8360                pkgs.add(pkg.packageName);
8361            }
8362
8363            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8364            switch (level) {
8365                case PermissionInfo.PROTECTION_NORMAL: {
8366                    // For all apps normal permissions are install time ones.
8367                    grant = GRANT_INSTALL;
8368                } break;
8369
8370                case PermissionInfo.PROTECTION_DANGEROUS: {
8371                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8372                        // For legacy apps dangerous permissions are install time ones.
8373                        grant = GRANT_INSTALL_LEGACY;
8374                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8375                        // For legacy apps that became modern, install becomes runtime.
8376                        grant = GRANT_UPGRADE;
8377                    } else {
8378                        // For modern apps keep runtime permissions unchanged.
8379                        grant = GRANT_RUNTIME;
8380                    }
8381                } break;
8382
8383                case PermissionInfo.PROTECTION_SIGNATURE: {
8384                    // For all apps signature permissions are install time ones.
8385                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8386                    if (allowedSig) {
8387                        grant = GRANT_INSTALL;
8388                    }
8389                } break;
8390            }
8391
8392            if (DEBUG_INSTALL) {
8393                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8394            }
8395
8396            if (grant != GRANT_DENIED) {
8397                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8398                    // If this is an existing, non-system package, then
8399                    // we can't add any new permissions to it.
8400                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8401                        // Except...  if this is a permission that was added
8402                        // to the platform (note: need to only do this when
8403                        // updating the platform).
8404                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8405                            grant = GRANT_DENIED;
8406                        }
8407                    }
8408                }
8409
8410                switch (grant) {
8411                    case GRANT_INSTALL: {
8412                        // Revoke this as runtime permission to handle the case of
8413                        // a runtime permission being downgraded to an install one.
8414                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8415                            if (origPermissions.getRuntimePermissionState(
8416                                    bp.name, userId) != null) {
8417                                // Revoke the runtime permission and clear the flags.
8418                                origPermissions.revokeRuntimePermission(bp, userId);
8419                                origPermissions.updatePermissionFlags(bp, userId,
8420                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8421                                // If we revoked a permission permission, we have to write.
8422                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8423                                        changedRuntimePermissionUserIds, userId);
8424                            }
8425                        }
8426                        // Grant an install permission.
8427                        if (permissionsState.grantInstallPermission(bp) !=
8428                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8429                            changedInstallPermission = true;
8430                        }
8431                    } break;
8432
8433                    case GRANT_INSTALL_LEGACY: {
8434                        // Grant an install permission.
8435                        if (permissionsState.grantInstallPermission(bp) !=
8436                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8437                            changedInstallPermission = true;
8438                        }
8439                    } break;
8440
8441                    case GRANT_RUNTIME: {
8442                        // Grant previously granted runtime permissions.
8443                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8444                            PermissionState permissionState = origPermissions
8445                                    .getRuntimePermissionState(bp.name, userId);
8446                            final int flags = permissionState != null
8447                                    ? permissionState.getFlags() : 0;
8448                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8449                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8450                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8451                                    // If we cannot put the permission as it was, we have to write.
8452                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8453                                            changedRuntimePermissionUserIds, userId);
8454                                }
8455                            }
8456                            // Propagate the permission flags.
8457                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8458                        }
8459                    } break;
8460
8461                    case GRANT_UPGRADE: {
8462                        // Grant runtime permissions for a previously held install permission.
8463                        PermissionState permissionState = origPermissions
8464                                .getInstallPermissionState(bp.name);
8465                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8466
8467                        if (origPermissions.revokeInstallPermission(bp)
8468                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8469                            // We will be transferring the permission flags, so clear them.
8470                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8471                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8472                            changedInstallPermission = true;
8473                        }
8474
8475                        // If the permission is not to be promoted to runtime we ignore it and
8476                        // also its other flags as they are not applicable to install permissions.
8477                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8478                            for (int userId : currentUserIds) {
8479                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8480                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8481                                    // Transfer the permission flags.
8482                                    permissionsState.updatePermissionFlags(bp, userId,
8483                                            flags, flags);
8484                                    // If we granted the permission, we have to write.
8485                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8486                                            changedRuntimePermissionUserIds, userId);
8487                                }
8488                            }
8489                        }
8490                    } break;
8491
8492                    default: {
8493                        if (packageOfInterest == null
8494                                || packageOfInterest.equals(pkg.packageName)) {
8495                            Slog.w(TAG, "Not granting permission " + perm
8496                                    + " to package " + pkg.packageName
8497                                    + " because it was previously installed without");
8498                        }
8499                    } break;
8500                }
8501            } else {
8502                if (permissionsState.revokeInstallPermission(bp) !=
8503                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8504                    // Also drop the permission flags.
8505                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8506                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8507                    changedInstallPermission = true;
8508                    Slog.i(TAG, "Un-granting permission " + perm
8509                            + " from package " + pkg.packageName
8510                            + " (protectionLevel=" + bp.protectionLevel
8511                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8512                            + ")");
8513                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8514                    // Don't print warning for app op permissions, since it is fine for them
8515                    // not to be granted, there is a UI for the user to decide.
8516                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8517                        Slog.w(TAG, "Not granting permission " + perm
8518                                + " to package " + pkg.packageName
8519                                + " (protectionLevel=" + bp.protectionLevel
8520                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8521                                + ")");
8522                    }
8523                }
8524            }
8525        }
8526
8527        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8528                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8529            // This is the first that we have heard about this package, so the
8530            // permissions we have now selected are fixed until explicitly
8531            // changed.
8532            ps.installPermissionsFixed = true;
8533        }
8534
8535        // Persist the runtime permissions state for users with changes.
8536        for (int userId : changedRuntimePermissionUserIds) {
8537            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8538        }
8539    }
8540
8541    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8542        boolean allowed = false;
8543        final int NP = PackageParser.NEW_PERMISSIONS.length;
8544        for (int ip=0; ip<NP; ip++) {
8545            final PackageParser.NewPermissionInfo npi
8546                    = PackageParser.NEW_PERMISSIONS[ip];
8547            if (npi.name.equals(perm)
8548                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8549                allowed = true;
8550                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8551                        + pkg.packageName);
8552                break;
8553            }
8554        }
8555        return allowed;
8556    }
8557
8558    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8559            BasePermission bp, PermissionsState origPermissions) {
8560        boolean allowed;
8561        allowed = (compareSignatures(
8562                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8563                        == PackageManager.SIGNATURE_MATCH)
8564                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8565                        == PackageManager.SIGNATURE_MATCH);
8566        if (!allowed && (bp.protectionLevel
8567                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8568            if (isSystemApp(pkg)) {
8569                // For updated system applications, a system permission
8570                // is granted only if it had been defined by the original application.
8571                if (pkg.isUpdatedSystemApp()) {
8572                    final PackageSetting sysPs = mSettings
8573                            .getDisabledSystemPkgLPr(pkg.packageName);
8574                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8575                        // If the original was granted this permission, we take
8576                        // that grant decision as read and propagate it to the
8577                        // update.
8578                        if (sysPs.isPrivileged()) {
8579                            allowed = true;
8580                        }
8581                    } else {
8582                        // The system apk may have been updated with an older
8583                        // version of the one on the data partition, but which
8584                        // granted a new system permission that it didn't have
8585                        // before.  In this case we do want to allow the app to
8586                        // now get the new permission if the ancestral apk is
8587                        // privileged to get it.
8588                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8589                            for (int j=0;
8590                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8591                                if (perm.equals(
8592                                        sysPs.pkg.requestedPermissions.get(j))) {
8593                                    allowed = true;
8594                                    break;
8595                                }
8596                            }
8597                        }
8598                    }
8599                } else {
8600                    allowed = isPrivilegedApp(pkg);
8601                }
8602            }
8603        }
8604        if (!allowed) {
8605            if (!allowed && (bp.protectionLevel
8606                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8607                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8608                // If this was a previously normal/dangerous permission that got moved
8609                // to a system permission as part of the runtime permission redesign, then
8610                // we still want to blindly grant it to old apps.
8611                allowed = true;
8612            }
8613            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8614                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8615                // If this permission is to be granted to the system installer and
8616                // this app is an installer, then it gets the permission.
8617                allowed = true;
8618            }
8619            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8620                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8621                // If this permission is to be granted to the system verifier and
8622                // this app is a verifier, then it gets the permission.
8623                allowed = true;
8624            }
8625            if (!allowed && (bp.protectionLevel
8626                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8627                    && isSystemApp(pkg)) {
8628                // Any pre-installed system app is allowed to get this permission.
8629                allowed = true;
8630            }
8631            if (!allowed && (bp.protectionLevel
8632                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8633                // For development permissions, a development permission
8634                // is granted only if it was already granted.
8635                allowed = origPermissions.hasInstallPermission(perm);
8636            }
8637        }
8638        return allowed;
8639    }
8640
8641    final class ActivityIntentResolver
8642            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8643        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8644                boolean defaultOnly, int userId) {
8645            if (!sUserManager.exists(userId)) return null;
8646            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8647            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8648        }
8649
8650        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8651                int userId) {
8652            if (!sUserManager.exists(userId)) return null;
8653            mFlags = flags;
8654            return super.queryIntent(intent, resolvedType,
8655                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8656        }
8657
8658        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8659                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8660            if (!sUserManager.exists(userId)) return null;
8661            if (packageActivities == null) {
8662                return null;
8663            }
8664            mFlags = flags;
8665            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8666            final int N = packageActivities.size();
8667            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8668                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8669
8670            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8671            for (int i = 0; i < N; ++i) {
8672                intentFilters = packageActivities.get(i).intents;
8673                if (intentFilters != null && intentFilters.size() > 0) {
8674                    PackageParser.ActivityIntentInfo[] array =
8675                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8676                    intentFilters.toArray(array);
8677                    listCut.add(array);
8678                }
8679            }
8680            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8681        }
8682
8683        public final void addActivity(PackageParser.Activity a, String type) {
8684            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8685            mActivities.put(a.getComponentName(), a);
8686            if (DEBUG_SHOW_INFO)
8687                Log.v(
8688                TAG, "  " + type + " " +
8689                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8690            if (DEBUG_SHOW_INFO)
8691                Log.v(TAG, "    Class=" + a.info.name);
8692            final int NI = a.intents.size();
8693            for (int j=0; j<NI; j++) {
8694                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8695                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8696                    intent.setPriority(0);
8697                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8698                            + a.className + " with priority > 0, forcing to 0");
8699                }
8700                if (DEBUG_SHOW_INFO) {
8701                    Log.v(TAG, "    IntentFilter:");
8702                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8703                }
8704                if (!intent.debugCheck()) {
8705                    Log.w(TAG, "==> For Activity " + a.info.name);
8706                }
8707                addFilter(intent);
8708            }
8709        }
8710
8711        public final void removeActivity(PackageParser.Activity a, String type) {
8712            mActivities.remove(a.getComponentName());
8713            if (DEBUG_SHOW_INFO) {
8714                Log.v(TAG, "  " + type + " "
8715                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8716                                : a.info.name) + ":");
8717                Log.v(TAG, "    Class=" + a.info.name);
8718            }
8719            final int NI = a.intents.size();
8720            for (int j=0; j<NI; j++) {
8721                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8722                if (DEBUG_SHOW_INFO) {
8723                    Log.v(TAG, "    IntentFilter:");
8724                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8725                }
8726                removeFilter(intent);
8727            }
8728        }
8729
8730        @Override
8731        protected boolean allowFilterResult(
8732                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8733            ActivityInfo filterAi = filter.activity.info;
8734            for (int i=dest.size()-1; i>=0; i--) {
8735                ActivityInfo destAi = dest.get(i).activityInfo;
8736                if (destAi.name == filterAi.name
8737                        && destAi.packageName == filterAi.packageName) {
8738                    return false;
8739                }
8740            }
8741            return true;
8742        }
8743
8744        @Override
8745        protected ActivityIntentInfo[] newArray(int size) {
8746            return new ActivityIntentInfo[size];
8747        }
8748
8749        @Override
8750        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8751            if (!sUserManager.exists(userId)) return true;
8752            PackageParser.Package p = filter.activity.owner;
8753            if (p != null) {
8754                PackageSetting ps = (PackageSetting)p.mExtras;
8755                if (ps != null) {
8756                    // System apps are never considered stopped for purposes of
8757                    // filtering, because there may be no way for the user to
8758                    // actually re-launch them.
8759                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8760                            && ps.getStopped(userId);
8761                }
8762            }
8763            return false;
8764        }
8765
8766        @Override
8767        protected boolean isPackageForFilter(String packageName,
8768                PackageParser.ActivityIntentInfo info) {
8769            return packageName.equals(info.activity.owner.packageName);
8770        }
8771
8772        @Override
8773        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8774                int match, int userId) {
8775            if (!sUserManager.exists(userId)) return null;
8776            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8777                return null;
8778            }
8779            final PackageParser.Activity activity = info.activity;
8780            if (mSafeMode && (activity.info.applicationInfo.flags
8781                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8782                return null;
8783            }
8784            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8785            if (ps == null) {
8786                return null;
8787            }
8788            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8789                    ps.readUserState(userId), userId);
8790            if (ai == null) {
8791                return null;
8792            }
8793            final ResolveInfo res = new ResolveInfo();
8794            res.activityInfo = ai;
8795            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8796                res.filter = info;
8797            }
8798            if (info != null) {
8799                res.handleAllWebDataURI = info.handleAllWebDataURI();
8800            }
8801            res.priority = info.getPriority();
8802            res.preferredOrder = activity.owner.mPreferredOrder;
8803            //System.out.println("Result: " + res.activityInfo.className +
8804            //                   " = " + res.priority);
8805            res.match = match;
8806            res.isDefault = info.hasDefault;
8807            res.labelRes = info.labelRes;
8808            res.nonLocalizedLabel = info.nonLocalizedLabel;
8809            if (userNeedsBadging(userId)) {
8810                res.noResourceId = true;
8811            } else {
8812                res.icon = info.icon;
8813            }
8814            res.iconResourceId = info.icon;
8815            res.system = res.activityInfo.applicationInfo.isSystemApp();
8816            return res;
8817        }
8818
8819        @Override
8820        protected void sortResults(List<ResolveInfo> results) {
8821            Collections.sort(results, mResolvePrioritySorter);
8822        }
8823
8824        @Override
8825        protected void dumpFilter(PrintWriter out, String prefix,
8826                PackageParser.ActivityIntentInfo filter) {
8827            out.print(prefix); out.print(
8828                    Integer.toHexString(System.identityHashCode(filter.activity)));
8829                    out.print(' ');
8830                    filter.activity.printComponentShortName(out);
8831                    out.print(" filter ");
8832                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8833        }
8834
8835        @Override
8836        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8837            return filter.activity;
8838        }
8839
8840        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8841            PackageParser.Activity activity = (PackageParser.Activity)label;
8842            out.print(prefix); out.print(
8843                    Integer.toHexString(System.identityHashCode(activity)));
8844                    out.print(' ');
8845                    activity.printComponentShortName(out);
8846            if (count > 1) {
8847                out.print(" ("); out.print(count); out.print(" filters)");
8848            }
8849            out.println();
8850        }
8851
8852//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8853//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8854//            final List<ResolveInfo> retList = Lists.newArrayList();
8855//            while (i.hasNext()) {
8856//                final ResolveInfo resolveInfo = i.next();
8857//                if (isEnabledLP(resolveInfo.activityInfo)) {
8858//                    retList.add(resolveInfo);
8859//                }
8860//            }
8861//            return retList;
8862//        }
8863
8864        // Keys are String (activity class name), values are Activity.
8865        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8866                = new ArrayMap<ComponentName, PackageParser.Activity>();
8867        private int mFlags;
8868    }
8869
8870    private final class ServiceIntentResolver
8871            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8872        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8873                boolean defaultOnly, int userId) {
8874            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8875            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8876        }
8877
8878        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8879                int userId) {
8880            if (!sUserManager.exists(userId)) return null;
8881            mFlags = flags;
8882            return super.queryIntent(intent, resolvedType,
8883                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8884        }
8885
8886        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8887                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8888            if (!sUserManager.exists(userId)) return null;
8889            if (packageServices == null) {
8890                return null;
8891            }
8892            mFlags = flags;
8893            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8894            final int N = packageServices.size();
8895            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8896                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8897
8898            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8899            for (int i = 0; i < N; ++i) {
8900                intentFilters = packageServices.get(i).intents;
8901                if (intentFilters != null && intentFilters.size() > 0) {
8902                    PackageParser.ServiceIntentInfo[] array =
8903                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8904                    intentFilters.toArray(array);
8905                    listCut.add(array);
8906                }
8907            }
8908            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8909        }
8910
8911        public final void addService(PackageParser.Service s) {
8912            mServices.put(s.getComponentName(), s);
8913            if (DEBUG_SHOW_INFO) {
8914                Log.v(TAG, "  "
8915                        + (s.info.nonLocalizedLabel != null
8916                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8917                Log.v(TAG, "    Class=" + s.info.name);
8918            }
8919            final int NI = s.intents.size();
8920            int j;
8921            for (j=0; j<NI; j++) {
8922                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8923                if (DEBUG_SHOW_INFO) {
8924                    Log.v(TAG, "    IntentFilter:");
8925                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8926                }
8927                if (!intent.debugCheck()) {
8928                    Log.w(TAG, "==> For Service " + s.info.name);
8929                }
8930                addFilter(intent);
8931            }
8932        }
8933
8934        public final void removeService(PackageParser.Service s) {
8935            mServices.remove(s.getComponentName());
8936            if (DEBUG_SHOW_INFO) {
8937                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8938                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8939                Log.v(TAG, "    Class=" + s.info.name);
8940            }
8941            final int NI = s.intents.size();
8942            int j;
8943            for (j=0; j<NI; j++) {
8944                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8945                if (DEBUG_SHOW_INFO) {
8946                    Log.v(TAG, "    IntentFilter:");
8947                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8948                }
8949                removeFilter(intent);
8950            }
8951        }
8952
8953        @Override
8954        protected boolean allowFilterResult(
8955                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8956            ServiceInfo filterSi = filter.service.info;
8957            for (int i=dest.size()-1; i>=0; i--) {
8958                ServiceInfo destAi = dest.get(i).serviceInfo;
8959                if (destAi.name == filterSi.name
8960                        && destAi.packageName == filterSi.packageName) {
8961                    return false;
8962                }
8963            }
8964            return true;
8965        }
8966
8967        @Override
8968        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8969            return new PackageParser.ServiceIntentInfo[size];
8970        }
8971
8972        @Override
8973        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8974            if (!sUserManager.exists(userId)) return true;
8975            PackageParser.Package p = filter.service.owner;
8976            if (p != null) {
8977                PackageSetting ps = (PackageSetting)p.mExtras;
8978                if (ps != null) {
8979                    // System apps are never considered stopped for purposes of
8980                    // filtering, because there may be no way for the user to
8981                    // actually re-launch them.
8982                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8983                            && ps.getStopped(userId);
8984                }
8985            }
8986            return false;
8987        }
8988
8989        @Override
8990        protected boolean isPackageForFilter(String packageName,
8991                PackageParser.ServiceIntentInfo info) {
8992            return packageName.equals(info.service.owner.packageName);
8993        }
8994
8995        @Override
8996        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8997                int match, int userId) {
8998            if (!sUserManager.exists(userId)) return null;
8999            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9000            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9001                return null;
9002            }
9003            final PackageParser.Service service = info.service;
9004            if (mSafeMode && (service.info.applicationInfo.flags
9005                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9006                return null;
9007            }
9008            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9009            if (ps == null) {
9010                return null;
9011            }
9012            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9013                    ps.readUserState(userId), userId);
9014            if (si == null) {
9015                return null;
9016            }
9017            final ResolveInfo res = new ResolveInfo();
9018            res.serviceInfo = si;
9019            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9020                res.filter = filter;
9021            }
9022            res.priority = info.getPriority();
9023            res.preferredOrder = service.owner.mPreferredOrder;
9024            res.match = match;
9025            res.isDefault = info.hasDefault;
9026            res.labelRes = info.labelRes;
9027            res.nonLocalizedLabel = info.nonLocalizedLabel;
9028            res.icon = info.icon;
9029            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9030            return res;
9031        }
9032
9033        @Override
9034        protected void sortResults(List<ResolveInfo> results) {
9035            Collections.sort(results, mResolvePrioritySorter);
9036        }
9037
9038        @Override
9039        protected void dumpFilter(PrintWriter out, String prefix,
9040                PackageParser.ServiceIntentInfo filter) {
9041            out.print(prefix); out.print(
9042                    Integer.toHexString(System.identityHashCode(filter.service)));
9043                    out.print(' ');
9044                    filter.service.printComponentShortName(out);
9045                    out.print(" filter ");
9046                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9047        }
9048
9049        @Override
9050        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9051            return filter.service;
9052        }
9053
9054        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9055            PackageParser.Service service = (PackageParser.Service)label;
9056            out.print(prefix); out.print(
9057                    Integer.toHexString(System.identityHashCode(service)));
9058                    out.print(' ');
9059                    service.printComponentShortName(out);
9060            if (count > 1) {
9061                out.print(" ("); out.print(count); out.print(" filters)");
9062            }
9063            out.println();
9064        }
9065
9066//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9067//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9068//            final List<ResolveInfo> retList = Lists.newArrayList();
9069//            while (i.hasNext()) {
9070//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9071//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9072//                    retList.add(resolveInfo);
9073//                }
9074//            }
9075//            return retList;
9076//        }
9077
9078        // Keys are String (activity class name), values are Activity.
9079        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9080                = new ArrayMap<ComponentName, PackageParser.Service>();
9081        private int mFlags;
9082    };
9083
9084    private final class ProviderIntentResolver
9085            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9086        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9087                boolean defaultOnly, int userId) {
9088            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9089            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9090        }
9091
9092        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9093                int userId) {
9094            if (!sUserManager.exists(userId))
9095                return null;
9096            mFlags = flags;
9097            return super.queryIntent(intent, resolvedType,
9098                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9099        }
9100
9101        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9102                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9103            if (!sUserManager.exists(userId))
9104                return null;
9105            if (packageProviders == null) {
9106                return null;
9107            }
9108            mFlags = flags;
9109            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9110            final int N = packageProviders.size();
9111            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9112                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9113
9114            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9115            for (int i = 0; i < N; ++i) {
9116                intentFilters = packageProviders.get(i).intents;
9117                if (intentFilters != null && intentFilters.size() > 0) {
9118                    PackageParser.ProviderIntentInfo[] array =
9119                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9120                    intentFilters.toArray(array);
9121                    listCut.add(array);
9122                }
9123            }
9124            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9125        }
9126
9127        public final void addProvider(PackageParser.Provider p) {
9128            if (mProviders.containsKey(p.getComponentName())) {
9129                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9130                return;
9131            }
9132
9133            mProviders.put(p.getComponentName(), p);
9134            if (DEBUG_SHOW_INFO) {
9135                Log.v(TAG, "  "
9136                        + (p.info.nonLocalizedLabel != null
9137                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9138                Log.v(TAG, "    Class=" + p.info.name);
9139            }
9140            final int NI = p.intents.size();
9141            int j;
9142            for (j = 0; j < NI; j++) {
9143                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9144                if (DEBUG_SHOW_INFO) {
9145                    Log.v(TAG, "    IntentFilter:");
9146                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9147                }
9148                if (!intent.debugCheck()) {
9149                    Log.w(TAG, "==> For Provider " + p.info.name);
9150                }
9151                addFilter(intent);
9152            }
9153        }
9154
9155        public final void removeProvider(PackageParser.Provider p) {
9156            mProviders.remove(p.getComponentName());
9157            if (DEBUG_SHOW_INFO) {
9158                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9159                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9160                Log.v(TAG, "    Class=" + p.info.name);
9161            }
9162            final int NI = p.intents.size();
9163            int j;
9164            for (j = 0; j < NI; j++) {
9165                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9166                if (DEBUG_SHOW_INFO) {
9167                    Log.v(TAG, "    IntentFilter:");
9168                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9169                }
9170                removeFilter(intent);
9171            }
9172        }
9173
9174        @Override
9175        protected boolean allowFilterResult(
9176                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9177            ProviderInfo filterPi = filter.provider.info;
9178            for (int i = dest.size() - 1; i >= 0; i--) {
9179                ProviderInfo destPi = dest.get(i).providerInfo;
9180                if (destPi.name == filterPi.name
9181                        && destPi.packageName == filterPi.packageName) {
9182                    return false;
9183                }
9184            }
9185            return true;
9186        }
9187
9188        @Override
9189        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9190            return new PackageParser.ProviderIntentInfo[size];
9191        }
9192
9193        @Override
9194        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9195            if (!sUserManager.exists(userId))
9196                return true;
9197            PackageParser.Package p = filter.provider.owner;
9198            if (p != null) {
9199                PackageSetting ps = (PackageSetting) p.mExtras;
9200                if (ps != null) {
9201                    // System apps are never considered stopped for purposes of
9202                    // filtering, because there may be no way for the user to
9203                    // actually re-launch them.
9204                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9205                            && ps.getStopped(userId);
9206                }
9207            }
9208            return false;
9209        }
9210
9211        @Override
9212        protected boolean isPackageForFilter(String packageName,
9213                PackageParser.ProviderIntentInfo info) {
9214            return packageName.equals(info.provider.owner.packageName);
9215        }
9216
9217        @Override
9218        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9219                int match, int userId) {
9220            if (!sUserManager.exists(userId))
9221                return null;
9222            final PackageParser.ProviderIntentInfo info = filter;
9223            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9224                return null;
9225            }
9226            final PackageParser.Provider provider = info.provider;
9227            if (mSafeMode && (provider.info.applicationInfo.flags
9228                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9229                return null;
9230            }
9231            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9232            if (ps == null) {
9233                return null;
9234            }
9235            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9236                    ps.readUserState(userId), userId);
9237            if (pi == null) {
9238                return null;
9239            }
9240            final ResolveInfo res = new ResolveInfo();
9241            res.providerInfo = pi;
9242            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9243                res.filter = filter;
9244            }
9245            res.priority = info.getPriority();
9246            res.preferredOrder = provider.owner.mPreferredOrder;
9247            res.match = match;
9248            res.isDefault = info.hasDefault;
9249            res.labelRes = info.labelRes;
9250            res.nonLocalizedLabel = info.nonLocalizedLabel;
9251            res.icon = info.icon;
9252            res.system = res.providerInfo.applicationInfo.isSystemApp();
9253            return res;
9254        }
9255
9256        @Override
9257        protected void sortResults(List<ResolveInfo> results) {
9258            Collections.sort(results, mResolvePrioritySorter);
9259        }
9260
9261        @Override
9262        protected void dumpFilter(PrintWriter out, String prefix,
9263                PackageParser.ProviderIntentInfo filter) {
9264            out.print(prefix);
9265            out.print(
9266                    Integer.toHexString(System.identityHashCode(filter.provider)));
9267            out.print(' ');
9268            filter.provider.printComponentShortName(out);
9269            out.print(" filter ");
9270            out.println(Integer.toHexString(System.identityHashCode(filter)));
9271        }
9272
9273        @Override
9274        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9275            return filter.provider;
9276        }
9277
9278        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9279            PackageParser.Provider provider = (PackageParser.Provider)label;
9280            out.print(prefix); out.print(
9281                    Integer.toHexString(System.identityHashCode(provider)));
9282                    out.print(' ');
9283                    provider.printComponentShortName(out);
9284            if (count > 1) {
9285                out.print(" ("); out.print(count); out.print(" filters)");
9286            }
9287            out.println();
9288        }
9289
9290        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9291                = new ArrayMap<ComponentName, PackageParser.Provider>();
9292        private int mFlags;
9293    };
9294
9295    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9296            new Comparator<ResolveInfo>() {
9297        public int compare(ResolveInfo r1, ResolveInfo r2) {
9298            int v1 = r1.priority;
9299            int v2 = r2.priority;
9300            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9301            if (v1 != v2) {
9302                return (v1 > v2) ? -1 : 1;
9303            }
9304            v1 = r1.preferredOrder;
9305            v2 = r2.preferredOrder;
9306            if (v1 != v2) {
9307                return (v1 > v2) ? -1 : 1;
9308            }
9309            if (r1.isDefault != r2.isDefault) {
9310                return r1.isDefault ? -1 : 1;
9311            }
9312            v1 = r1.match;
9313            v2 = r2.match;
9314            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9315            if (v1 != v2) {
9316                return (v1 > v2) ? -1 : 1;
9317            }
9318            if (r1.system != r2.system) {
9319                return r1.system ? -1 : 1;
9320            }
9321            return 0;
9322        }
9323    };
9324
9325    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9326            new Comparator<ProviderInfo>() {
9327        public int compare(ProviderInfo p1, ProviderInfo p2) {
9328            final int v1 = p1.initOrder;
9329            final int v2 = p2.initOrder;
9330            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9331        }
9332    };
9333
9334    final void sendPackageBroadcast(final String action, final String pkg,
9335            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9336            final int[] userIds) {
9337        mHandler.post(new Runnable() {
9338            @Override
9339            public void run() {
9340                try {
9341                    final IActivityManager am = ActivityManagerNative.getDefault();
9342                    if (am == null) return;
9343                    final int[] resolvedUserIds;
9344                    if (userIds == null) {
9345                        resolvedUserIds = am.getRunningUserIds();
9346                    } else {
9347                        resolvedUserIds = userIds;
9348                    }
9349                    for (int id : resolvedUserIds) {
9350                        final Intent intent = new Intent(action,
9351                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9352                        if (extras != null) {
9353                            intent.putExtras(extras);
9354                        }
9355                        if (targetPkg != null) {
9356                            intent.setPackage(targetPkg);
9357                        }
9358                        // Modify the UID when posting to other users
9359                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9360                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9361                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9362                            intent.putExtra(Intent.EXTRA_UID, uid);
9363                        }
9364                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9365                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9366                        if (DEBUG_BROADCASTS) {
9367                            RuntimeException here = new RuntimeException("here");
9368                            here.fillInStackTrace();
9369                            Slog.d(TAG, "Sending to user " + id + ": "
9370                                    + intent.toShortString(false, true, false, false)
9371                                    + " " + intent.getExtras(), here);
9372                        }
9373                        am.broadcastIntent(null, intent, null, finishedReceiver,
9374                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9375                                null, finishedReceiver != null, false, id);
9376                    }
9377                } catch (RemoteException ex) {
9378                }
9379            }
9380        });
9381    }
9382
9383    /**
9384     * Check if the external storage media is available. This is true if there
9385     * is a mounted external storage medium or if the external storage is
9386     * emulated.
9387     */
9388    private boolean isExternalMediaAvailable() {
9389        return mMediaMounted || Environment.isExternalStorageEmulated();
9390    }
9391
9392    @Override
9393    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9394        // writer
9395        synchronized (mPackages) {
9396            if (!isExternalMediaAvailable()) {
9397                // If the external storage is no longer mounted at this point,
9398                // the caller may not have been able to delete all of this
9399                // packages files and can not delete any more.  Bail.
9400                return null;
9401            }
9402            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9403            if (lastPackage != null) {
9404                pkgs.remove(lastPackage);
9405            }
9406            if (pkgs.size() > 0) {
9407                return pkgs.get(0);
9408            }
9409        }
9410        return null;
9411    }
9412
9413    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9414        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9415                userId, andCode ? 1 : 0, packageName);
9416        if (mSystemReady) {
9417            msg.sendToTarget();
9418        } else {
9419            if (mPostSystemReadyMessages == null) {
9420                mPostSystemReadyMessages = new ArrayList<>();
9421            }
9422            mPostSystemReadyMessages.add(msg);
9423        }
9424    }
9425
9426    void startCleaningPackages() {
9427        // reader
9428        synchronized (mPackages) {
9429            if (!isExternalMediaAvailable()) {
9430                return;
9431            }
9432            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9433                return;
9434            }
9435        }
9436        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9437        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9438        IActivityManager am = ActivityManagerNative.getDefault();
9439        if (am != null) {
9440            try {
9441                am.startService(null, intent, null, mContext.getOpPackageName(),
9442                        UserHandle.USER_OWNER);
9443            } catch (RemoteException e) {
9444            }
9445        }
9446    }
9447
9448    @Override
9449    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9450            int installFlags, String installerPackageName, VerificationParams verificationParams,
9451            String packageAbiOverride) {
9452        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9453                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9454    }
9455
9456    @Override
9457    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9458            int installFlags, String installerPackageName, VerificationParams verificationParams,
9459            String packageAbiOverride, int userId) {
9460        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9461
9462        final int callingUid = Binder.getCallingUid();
9463        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9464
9465        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9466            try {
9467                if (observer != null) {
9468                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9469                }
9470            } catch (RemoteException re) {
9471            }
9472            return;
9473        }
9474
9475        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9476            installFlags |= PackageManager.INSTALL_FROM_ADB;
9477
9478        } else {
9479            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9480            // about installerPackageName.
9481
9482            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9483            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9484        }
9485
9486        UserHandle user;
9487        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9488            user = UserHandle.ALL;
9489        } else {
9490            user = new UserHandle(userId);
9491        }
9492
9493        // Only system components can circumvent runtime permissions when installing.
9494        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9495                && mContext.checkCallingOrSelfPermission(Manifest.permission
9496                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9497            throw new SecurityException("You need the "
9498                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9499                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9500        }
9501
9502        verificationParams.setInstallerUid(callingUid);
9503
9504        final File originFile = new File(originPath);
9505        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9506
9507        final Message msg = mHandler.obtainMessage(INIT_COPY);
9508        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9509                null, verificationParams, user, packageAbiOverride, null);
9510        mHandler.sendMessage(msg);
9511    }
9512
9513    void installStage(String packageName, File stagedDir, String stagedCid,
9514            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9515            String installerPackageName, int installerUid, UserHandle user) {
9516        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9517                params.referrerUri, installerUid, null);
9518        verifParams.setInstallerUid(installerUid);
9519
9520        final OriginInfo origin;
9521        if (stagedDir != null) {
9522            origin = OriginInfo.fromStagedFile(stagedDir);
9523        } else {
9524            origin = OriginInfo.fromStagedContainer(stagedCid);
9525        }
9526
9527        final Message msg = mHandler.obtainMessage(INIT_COPY);
9528        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9529                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9530                params.grantedRuntimePermissions);
9531        mHandler.sendMessage(msg);
9532    }
9533
9534    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9535        Bundle extras = new Bundle(1);
9536        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9537
9538        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9539                packageName, extras, null, null, new int[] {userId});
9540        try {
9541            IActivityManager am = ActivityManagerNative.getDefault();
9542            final boolean isSystem =
9543                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9544            if (isSystem && am.isUserRunning(userId, false)) {
9545                // The just-installed/enabled app is bundled on the system, so presumed
9546                // to be able to run automatically without needing an explicit launch.
9547                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9548                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9549                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9550                        .setPackage(packageName);
9551                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9552                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9553            }
9554        } catch (RemoteException e) {
9555            // shouldn't happen
9556            Slog.w(TAG, "Unable to bootstrap installed package", e);
9557        }
9558    }
9559
9560    @Override
9561    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9562            int userId) {
9563        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9564        PackageSetting pkgSetting;
9565        final int uid = Binder.getCallingUid();
9566        enforceCrossUserPermission(uid, userId, true, true,
9567                "setApplicationHiddenSetting for user " + userId);
9568
9569        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9570            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9571            return false;
9572        }
9573
9574        long callingId = Binder.clearCallingIdentity();
9575        try {
9576            boolean sendAdded = false;
9577            boolean sendRemoved = false;
9578            // writer
9579            synchronized (mPackages) {
9580                pkgSetting = mSettings.mPackages.get(packageName);
9581                if (pkgSetting == null) {
9582                    return false;
9583                }
9584                if (pkgSetting.getHidden(userId) != hidden) {
9585                    pkgSetting.setHidden(hidden, userId);
9586                    mSettings.writePackageRestrictionsLPr(userId);
9587                    if (hidden) {
9588                        sendRemoved = true;
9589                    } else {
9590                        sendAdded = true;
9591                    }
9592                }
9593            }
9594            if (sendAdded) {
9595                sendPackageAddedForUser(packageName, pkgSetting, userId);
9596                return true;
9597            }
9598            if (sendRemoved) {
9599                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9600                        "hiding pkg");
9601                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9602            }
9603        } finally {
9604            Binder.restoreCallingIdentity(callingId);
9605        }
9606        return false;
9607    }
9608
9609    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9610            int userId) {
9611        final PackageRemovedInfo info = new PackageRemovedInfo();
9612        info.removedPackage = packageName;
9613        info.removedUsers = new int[] {userId};
9614        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9615        info.sendBroadcast(false, false, false);
9616    }
9617
9618    /**
9619     * Returns true if application is not found or there was an error. Otherwise it returns
9620     * the hidden state of the package for the given user.
9621     */
9622    @Override
9623    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9624        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9625        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9626                false, "getApplicationHidden for user " + userId);
9627        PackageSetting pkgSetting;
9628        long callingId = Binder.clearCallingIdentity();
9629        try {
9630            // writer
9631            synchronized (mPackages) {
9632                pkgSetting = mSettings.mPackages.get(packageName);
9633                if (pkgSetting == null) {
9634                    return true;
9635                }
9636                return pkgSetting.getHidden(userId);
9637            }
9638        } finally {
9639            Binder.restoreCallingIdentity(callingId);
9640        }
9641    }
9642
9643    /**
9644     * @hide
9645     */
9646    @Override
9647    public int installExistingPackageAsUser(String packageName, int userId) {
9648        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9649                null);
9650        PackageSetting pkgSetting;
9651        final int uid = Binder.getCallingUid();
9652        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9653                + userId);
9654        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9655            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9656        }
9657
9658        long callingId = Binder.clearCallingIdentity();
9659        try {
9660            boolean sendAdded = false;
9661
9662            // writer
9663            synchronized (mPackages) {
9664                pkgSetting = mSettings.mPackages.get(packageName);
9665                if (pkgSetting == null) {
9666                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9667                }
9668                if (!pkgSetting.getInstalled(userId)) {
9669                    pkgSetting.setInstalled(true, userId);
9670                    pkgSetting.setHidden(false, userId);
9671                    mSettings.writePackageRestrictionsLPr(userId);
9672                    sendAdded = true;
9673                }
9674            }
9675
9676            if (sendAdded) {
9677                sendPackageAddedForUser(packageName, pkgSetting, userId);
9678            }
9679        } finally {
9680            Binder.restoreCallingIdentity(callingId);
9681        }
9682
9683        return PackageManager.INSTALL_SUCCEEDED;
9684    }
9685
9686    boolean isUserRestricted(int userId, String restrictionKey) {
9687        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9688        if (restrictions.getBoolean(restrictionKey, false)) {
9689            Log.w(TAG, "User is restricted: " + restrictionKey);
9690            return true;
9691        }
9692        return false;
9693    }
9694
9695    @Override
9696    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9697        mContext.enforceCallingOrSelfPermission(
9698                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9699                "Only package verification agents can verify applications");
9700
9701        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9702        final PackageVerificationResponse response = new PackageVerificationResponse(
9703                verificationCode, Binder.getCallingUid());
9704        msg.arg1 = id;
9705        msg.obj = response;
9706        mHandler.sendMessage(msg);
9707    }
9708
9709    @Override
9710    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9711            long millisecondsToDelay) {
9712        mContext.enforceCallingOrSelfPermission(
9713                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9714                "Only package verification agents can extend verification timeouts");
9715
9716        final PackageVerificationState state = mPendingVerification.get(id);
9717        final PackageVerificationResponse response = new PackageVerificationResponse(
9718                verificationCodeAtTimeout, Binder.getCallingUid());
9719
9720        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9721            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9722        }
9723        if (millisecondsToDelay < 0) {
9724            millisecondsToDelay = 0;
9725        }
9726        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9727                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9728            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9729        }
9730
9731        if ((state != null) && !state.timeoutExtended()) {
9732            state.extendTimeout();
9733
9734            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9735            msg.arg1 = id;
9736            msg.obj = response;
9737            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9738        }
9739    }
9740
9741    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9742            int verificationCode, UserHandle user) {
9743        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9744        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9745        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9746        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9747        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9748
9749        mContext.sendBroadcastAsUser(intent, user,
9750                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9751    }
9752
9753    private ComponentName matchComponentForVerifier(String packageName,
9754            List<ResolveInfo> receivers) {
9755        ActivityInfo targetReceiver = null;
9756
9757        final int NR = receivers.size();
9758        for (int i = 0; i < NR; i++) {
9759            final ResolveInfo info = receivers.get(i);
9760            if (info.activityInfo == null) {
9761                continue;
9762            }
9763
9764            if (packageName.equals(info.activityInfo.packageName)) {
9765                targetReceiver = info.activityInfo;
9766                break;
9767            }
9768        }
9769
9770        if (targetReceiver == null) {
9771            return null;
9772        }
9773
9774        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9775    }
9776
9777    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9778            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9779        if (pkgInfo.verifiers.length == 0) {
9780            return null;
9781        }
9782
9783        final int N = pkgInfo.verifiers.length;
9784        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9785        for (int i = 0; i < N; i++) {
9786            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9787
9788            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9789                    receivers);
9790            if (comp == null) {
9791                continue;
9792            }
9793
9794            final int verifierUid = getUidForVerifier(verifierInfo);
9795            if (verifierUid == -1) {
9796                continue;
9797            }
9798
9799            if (DEBUG_VERIFY) {
9800                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9801                        + " with the correct signature");
9802            }
9803            sufficientVerifiers.add(comp);
9804            verificationState.addSufficientVerifier(verifierUid);
9805        }
9806
9807        return sufficientVerifiers;
9808    }
9809
9810    private int getUidForVerifier(VerifierInfo verifierInfo) {
9811        synchronized (mPackages) {
9812            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9813            if (pkg == null) {
9814                return -1;
9815            } else if (pkg.mSignatures.length != 1) {
9816                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9817                        + " has more than one signature; ignoring");
9818                return -1;
9819            }
9820
9821            /*
9822             * If the public key of the package's signature does not match
9823             * our expected public key, then this is a different package and
9824             * we should skip.
9825             */
9826
9827            final byte[] expectedPublicKey;
9828            try {
9829                final Signature verifierSig = pkg.mSignatures[0];
9830                final PublicKey publicKey = verifierSig.getPublicKey();
9831                expectedPublicKey = publicKey.getEncoded();
9832            } catch (CertificateException e) {
9833                return -1;
9834            }
9835
9836            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9837
9838            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9839                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9840                        + " does not have the expected public key; ignoring");
9841                return -1;
9842            }
9843
9844            return pkg.applicationInfo.uid;
9845        }
9846    }
9847
9848    @Override
9849    public void finishPackageInstall(int token) {
9850        enforceSystemOrRoot("Only the system is allowed to finish installs");
9851
9852        if (DEBUG_INSTALL) {
9853            Slog.v(TAG, "BM finishing package install for " + token);
9854        }
9855
9856        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9857        mHandler.sendMessage(msg);
9858    }
9859
9860    /**
9861     * Get the verification agent timeout.
9862     *
9863     * @return verification timeout in milliseconds
9864     */
9865    private long getVerificationTimeout() {
9866        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9867                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9868                DEFAULT_VERIFICATION_TIMEOUT);
9869    }
9870
9871    /**
9872     * Get the default verification agent response code.
9873     *
9874     * @return default verification response code
9875     */
9876    private int getDefaultVerificationResponse() {
9877        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9878                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9879                DEFAULT_VERIFICATION_RESPONSE);
9880    }
9881
9882    /**
9883     * Check whether or not package verification has been enabled.
9884     *
9885     * @return true if verification should be performed
9886     */
9887    private boolean isVerificationEnabled(int userId, int installFlags) {
9888        if (!DEFAULT_VERIFY_ENABLE) {
9889            return false;
9890        }
9891
9892        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9893
9894        // Check if installing from ADB
9895        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9896            // Do not run verification in a test harness environment
9897            if (ActivityManager.isRunningInTestHarness()) {
9898                return false;
9899            }
9900            if (ensureVerifyAppsEnabled) {
9901                return true;
9902            }
9903            // Check if the developer does not want package verification for ADB installs
9904            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9905                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9906                return false;
9907            }
9908        }
9909
9910        if (ensureVerifyAppsEnabled) {
9911            return true;
9912        }
9913
9914        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9915                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9916    }
9917
9918    @Override
9919    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9920            throws RemoteException {
9921        mContext.enforceCallingOrSelfPermission(
9922                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9923                "Only intentfilter verification agents can verify applications");
9924
9925        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9926        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9927                Binder.getCallingUid(), verificationCode, failedDomains);
9928        msg.arg1 = id;
9929        msg.obj = response;
9930        mHandler.sendMessage(msg);
9931    }
9932
9933    @Override
9934    public int getIntentVerificationStatus(String packageName, int userId) {
9935        synchronized (mPackages) {
9936            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9937        }
9938    }
9939
9940    @Override
9941    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9942        mContext.enforceCallingOrSelfPermission(
9943                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9944
9945        boolean result = false;
9946        synchronized (mPackages) {
9947            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9948        }
9949        if (result) {
9950            scheduleWritePackageRestrictionsLocked(userId);
9951        }
9952        return result;
9953    }
9954
9955    @Override
9956    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9957        synchronized (mPackages) {
9958            return mSettings.getIntentFilterVerificationsLPr(packageName);
9959        }
9960    }
9961
9962    @Override
9963    public List<IntentFilter> getAllIntentFilters(String packageName) {
9964        if (TextUtils.isEmpty(packageName)) {
9965            return Collections.<IntentFilter>emptyList();
9966        }
9967        synchronized (mPackages) {
9968            PackageParser.Package pkg = mPackages.get(packageName);
9969            if (pkg == null || pkg.activities == null) {
9970                return Collections.<IntentFilter>emptyList();
9971            }
9972            final int count = pkg.activities.size();
9973            ArrayList<IntentFilter> result = new ArrayList<>();
9974            for (int n=0; n<count; n++) {
9975                PackageParser.Activity activity = pkg.activities.get(n);
9976                if (activity.intents != null || activity.intents.size() > 0) {
9977                    result.addAll(activity.intents);
9978                }
9979            }
9980            return result;
9981        }
9982    }
9983
9984    @Override
9985    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9986        mContext.enforceCallingOrSelfPermission(
9987                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9988
9989        synchronized (mPackages) {
9990            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9991            if (packageName != null) {
9992                result |= updateIntentVerificationStatus(packageName,
9993                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9994                        userId);
9995                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9996                        packageName, userId);
9997            }
9998            return result;
9999        }
10000    }
10001
10002    @Override
10003    public String getDefaultBrowserPackageName(int userId) {
10004        synchronized (mPackages) {
10005            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10006        }
10007    }
10008
10009    /**
10010     * Get the "allow unknown sources" setting.
10011     *
10012     * @return the current "allow unknown sources" setting
10013     */
10014    private int getUnknownSourcesSettings() {
10015        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10016                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10017                -1);
10018    }
10019
10020    @Override
10021    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10022        final int uid = Binder.getCallingUid();
10023        // writer
10024        synchronized (mPackages) {
10025            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10026            if (targetPackageSetting == null) {
10027                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10028            }
10029
10030            PackageSetting installerPackageSetting;
10031            if (installerPackageName != null) {
10032                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10033                if (installerPackageSetting == null) {
10034                    throw new IllegalArgumentException("Unknown installer package: "
10035                            + installerPackageName);
10036                }
10037            } else {
10038                installerPackageSetting = null;
10039            }
10040
10041            Signature[] callerSignature;
10042            Object obj = mSettings.getUserIdLPr(uid);
10043            if (obj != null) {
10044                if (obj instanceof SharedUserSetting) {
10045                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10046                } else if (obj instanceof PackageSetting) {
10047                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10048                } else {
10049                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10050                }
10051            } else {
10052                throw new SecurityException("Unknown calling uid " + uid);
10053            }
10054
10055            // Verify: can't set installerPackageName to a package that is
10056            // not signed with the same cert as the caller.
10057            if (installerPackageSetting != null) {
10058                if (compareSignatures(callerSignature,
10059                        installerPackageSetting.signatures.mSignatures)
10060                        != PackageManager.SIGNATURE_MATCH) {
10061                    throw new SecurityException(
10062                            "Caller does not have same cert as new installer package "
10063                            + installerPackageName);
10064                }
10065            }
10066
10067            // Verify: if target already has an installer package, it must
10068            // be signed with the same cert as the caller.
10069            if (targetPackageSetting.installerPackageName != null) {
10070                PackageSetting setting = mSettings.mPackages.get(
10071                        targetPackageSetting.installerPackageName);
10072                // If the currently set package isn't valid, then it's always
10073                // okay to change it.
10074                if (setting != null) {
10075                    if (compareSignatures(callerSignature,
10076                            setting.signatures.mSignatures)
10077                            != PackageManager.SIGNATURE_MATCH) {
10078                        throw new SecurityException(
10079                                "Caller does not have same cert as old installer package "
10080                                + targetPackageSetting.installerPackageName);
10081                    }
10082                }
10083            }
10084
10085            // Okay!
10086            targetPackageSetting.installerPackageName = installerPackageName;
10087            scheduleWriteSettingsLocked();
10088        }
10089    }
10090
10091    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10092        // Queue up an async operation since the package installation may take a little while.
10093        mHandler.post(new Runnable() {
10094            public void run() {
10095                mHandler.removeCallbacks(this);
10096                 // Result object to be returned
10097                PackageInstalledInfo res = new PackageInstalledInfo();
10098                res.returnCode = currentStatus;
10099                res.uid = -1;
10100                res.pkg = null;
10101                res.removedInfo = new PackageRemovedInfo();
10102                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10103                    args.doPreInstall(res.returnCode);
10104                    synchronized (mInstallLock) {
10105                        installPackageLI(args, res);
10106                    }
10107                    args.doPostInstall(res.returnCode, res.uid);
10108                }
10109
10110                // A restore should be performed at this point if (a) the install
10111                // succeeded, (b) the operation is not an update, and (c) the new
10112                // package has not opted out of backup participation.
10113                final boolean update = res.removedInfo.removedPackage != null;
10114                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10115                boolean doRestore = !update
10116                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10117
10118                // Set up the post-install work request bookkeeping.  This will be used
10119                // and cleaned up by the post-install event handling regardless of whether
10120                // there's a restore pass performed.  Token values are >= 1.
10121                int token;
10122                if (mNextInstallToken < 0) mNextInstallToken = 1;
10123                token = mNextInstallToken++;
10124
10125                PostInstallData data = new PostInstallData(args, res);
10126                mRunningInstalls.put(token, data);
10127                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10128
10129                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10130                    // Pass responsibility to the Backup Manager.  It will perform a
10131                    // restore if appropriate, then pass responsibility back to the
10132                    // Package Manager to run the post-install observer callbacks
10133                    // and broadcasts.
10134                    IBackupManager bm = IBackupManager.Stub.asInterface(
10135                            ServiceManager.getService(Context.BACKUP_SERVICE));
10136                    if (bm != null) {
10137                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10138                                + " to BM for possible restore");
10139                        try {
10140                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10141                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10142                            } else {
10143                                doRestore = false;
10144                            }
10145                        } catch (RemoteException e) {
10146                            // can't happen; the backup manager is local
10147                        } catch (Exception e) {
10148                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10149                            doRestore = false;
10150                        }
10151                    } else {
10152                        Slog.e(TAG, "Backup Manager not found!");
10153                        doRestore = false;
10154                    }
10155                }
10156
10157                if (!doRestore) {
10158                    // No restore possible, or the Backup Manager was mysteriously not
10159                    // available -- just fire the post-install work request directly.
10160                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10161                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10162                    mHandler.sendMessage(msg);
10163                }
10164            }
10165        });
10166    }
10167
10168    private abstract class HandlerParams {
10169        private static final int MAX_RETRIES = 4;
10170
10171        /**
10172         * Number of times startCopy() has been attempted and had a non-fatal
10173         * error.
10174         */
10175        private int mRetries = 0;
10176
10177        /** User handle for the user requesting the information or installation. */
10178        private final UserHandle mUser;
10179
10180        HandlerParams(UserHandle user) {
10181            mUser = user;
10182        }
10183
10184        UserHandle getUser() {
10185            return mUser;
10186        }
10187
10188        final boolean startCopy() {
10189            boolean res;
10190            try {
10191                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10192
10193                if (++mRetries > MAX_RETRIES) {
10194                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10195                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10196                    handleServiceError();
10197                    return false;
10198                } else {
10199                    handleStartCopy();
10200                    res = true;
10201                }
10202            } catch (RemoteException e) {
10203                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10204                mHandler.sendEmptyMessage(MCS_RECONNECT);
10205                res = false;
10206            }
10207            handleReturnCode();
10208            return res;
10209        }
10210
10211        final void serviceError() {
10212            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10213            handleServiceError();
10214            handleReturnCode();
10215        }
10216
10217        abstract void handleStartCopy() throws RemoteException;
10218        abstract void handleServiceError();
10219        abstract void handleReturnCode();
10220    }
10221
10222    class MeasureParams extends HandlerParams {
10223        private final PackageStats mStats;
10224        private boolean mSuccess;
10225
10226        private final IPackageStatsObserver mObserver;
10227
10228        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10229            super(new UserHandle(stats.userHandle));
10230            mObserver = observer;
10231            mStats = stats;
10232        }
10233
10234        @Override
10235        public String toString() {
10236            return "MeasureParams{"
10237                + Integer.toHexString(System.identityHashCode(this))
10238                + " " + mStats.packageName + "}";
10239        }
10240
10241        @Override
10242        void handleStartCopy() throws RemoteException {
10243            synchronized (mInstallLock) {
10244                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10245            }
10246
10247            if (mSuccess) {
10248                final boolean mounted;
10249                if (Environment.isExternalStorageEmulated()) {
10250                    mounted = true;
10251                } else {
10252                    final String status = Environment.getExternalStorageState();
10253                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10254                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10255                }
10256
10257                if (mounted) {
10258                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10259
10260                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10261                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10262
10263                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10264                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10265
10266                    // Always subtract cache size, since it's a subdirectory
10267                    mStats.externalDataSize -= mStats.externalCacheSize;
10268
10269                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10270                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10271
10272                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10273                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10274                }
10275            }
10276        }
10277
10278        @Override
10279        void handleReturnCode() {
10280            if (mObserver != null) {
10281                try {
10282                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10283                } catch (RemoteException e) {
10284                    Slog.i(TAG, "Observer no longer exists.");
10285                }
10286            }
10287        }
10288
10289        @Override
10290        void handleServiceError() {
10291            Slog.e(TAG, "Could not measure application " + mStats.packageName
10292                            + " external storage");
10293        }
10294    }
10295
10296    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10297            throws RemoteException {
10298        long result = 0;
10299        for (File path : paths) {
10300            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10301        }
10302        return result;
10303    }
10304
10305    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10306        for (File path : paths) {
10307            try {
10308                mcs.clearDirectory(path.getAbsolutePath());
10309            } catch (RemoteException e) {
10310            }
10311        }
10312    }
10313
10314    static class OriginInfo {
10315        /**
10316         * Location where install is coming from, before it has been
10317         * copied/renamed into place. This could be a single monolithic APK
10318         * file, or a cluster directory. This location may be untrusted.
10319         */
10320        final File file;
10321        final String cid;
10322
10323        /**
10324         * Flag indicating that {@link #file} or {@link #cid} has already been
10325         * staged, meaning downstream users don't need to defensively copy the
10326         * contents.
10327         */
10328        final boolean staged;
10329
10330        /**
10331         * Flag indicating that {@link #file} or {@link #cid} is an already
10332         * installed app that is being moved.
10333         */
10334        final boolean existing;
10335
10336        final String resolvedPath;
10337        final File resolvedFile;
10338
10339        static OriginInfo fromNothing() {
10340            return new OriginInfo(null, null, false, false);
10341        }
10342
10343        static OriginInfo fromUntrustedFile(File file) {
10344            return new OriginInfo(file, null, false, false);
10345        }
10346
10347        static OriginInfo fromExistingFile(File file) {
10348            return new OriginInfo(file, null, false, true);
10349        }
10350
10351        static OriginInfo fromStagedFile(File file) {
10352            return new OriginInfo(file, null, true, false);
10353        }
10354
10355        static OriginInfo fromStagedContainer(String cid) {
10356            return new OriginInfo(null, cid, true, false);
10357        }
10358
10359        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10360            this.file = file;
10361            this.cid = cid;
10362            this.staged = staged;
10363            this.existing = existing;
10364
10365            if (cid != null) {
10366                resolvedPath = PackageHelper.getSdDir(cid);
10367                resolvedFile = new File(resolvedPath);
10368            } else if (file != null) {
10369                resolvedPath = file.getAbsolutePath();
10370                resolvedFile = file;
10371            } else {
10372                resolvedPath = null;
10373                resolvedFile = null;
10374            }
10375        }
10376    }
10377
10378    class MoveInfo {
10379        final int moveId;
10380        final String fromUuid;
10381        final String toUuid;
10382        final String packageName;
10383        final String dataAppName;
10384        final int appId;
10385        final String seinfo;
10386
10387        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10388                String dataAppName, int appId, String seinfo) {
10389            this.moveId = moveId;
10390            this.fromUuid = fromUuid;
10391            this.toUuid = toUuid;
10392            this.packageName = packageName;
10393            this.dataAppName = dataAppName;
10394            this.appId = appId;
10395            this.seinfo = seinfo;
10396        }
10397    }
10398
10399    class InstallParams extends HandlerParams {
10400        final OriginInfo origin;
10401        final MoveInfo move;
10402        final IPackageInstallObserver2 observer;
10403        int installFlags;
10404        final String installerPackageName;
10405        final String volumeUuid;
10406        final VerificationParams verificationParams;
10407        private InstallArgs mArgs;
10408        private int mRet;
10409        final String packageAbiOverride;
10410        final String[] grantedRuntimePermissions;
10411
10412
10413        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10414                int installFlags, String installerPackageName, String volumeUuid,
10415                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10416                String[] grantedPermissions) {
10417            super(user);
10418            this.origin = origin;
10419            this.move = move;
10420            this.observer = observer;
10421            this.installFlags = installFlags;
10422            this.installerPackageName = installerPackageName;
10423            this.volumeUuid = volumeUuid;
10424            this.verificationParams = verificationParams;
10425            this.packageAbiOverride = packageAbiOverride;
10426            this.grantedRuntimePermissions = grantedPermissions;
10427        }
10428
10429        @Override
10430        public String toString() {
10431            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10432                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10433        }
10434
10435        public ManifestDigest getManifestDigest() {
10436            if (verificationParams == null) {
10437                return null;
10438            }
10439            return verificationParams.getManifestDigest();
10440        }
10441
10442        private int installLocationPolicy(PackageInfoLite pkgLite) {
10443            String packageName = pkgLite.packageName;
10444            int installLocation = pkgLite.installLocation;
10445            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10446            // reader
10447            synchronized (mPackages) {
10448                PackageParser.Package pkg = mPackages.get(packageName);
10449                if (pkg != null) {
10450                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10451                        // Check for downgrading.
10452                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10453                            try {
10454                                checkDowngrade(pkg, pkgLite);
10455                            } catch (PackageManagerException e) {
10456                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10457                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10458                            }
10459                        }
10460                        // Check for updated system application.
10461                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10462                            if (onSd) {
10463                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10464                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10465                            }
10466                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10467                        } else {
10468                            if (onSd) {
10469                                // Install flag overrides everything.
10470                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10471                            }
10472                            // If current upgrade specifies particular preference
10473                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10474                                // Application explicitly specified internal.
10475                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10476                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10477                                // App explictly prefers external. Let policy decide
10478                            } else {
10479                                // Prefer previous location
10480                                if (isExternal(pkg)) {
10481                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10482                                }
10483                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10484                            }
10485                        }
10486                    } else {
10487                        // Invalid install. Return error code
10488                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10489                    }
10490                }
10491            }
10492            // All the special cases have been taken care of.
10493            // Return result based on recommended install location.
10494            if (onSd) {
10495                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10496            }
10497            return pkgLite.recommendedInstallLocation;
10498        }
10499
10500        /*
10501         * Invoke remote method to get package information and install
10502         * location values. Override install location based on default
10503         * policy if needed and then create install arguments based
10504         * on the install location.
10505         */
10506        public void handleStartCopy() throws RemoteException {
10507            int ret = PackageManager.INSTALL_SUCCEEDED;
10508
10509            // If we're already staged, we've firmly committed to an install location
10510            if (origin.staged) {
10511                if (origin.file != null) {
10512                    installFlags |= PackageManager.INSTALL_INTERNAL;
10513                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10514                } else if (origin.cid != null) {
10515                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10516                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10517                } else {
10518                    throw new IllegalStateException("Invalid stage location");
10519                }
10520            }
10521
10522            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10523            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10524
10525            PackageInfoLite pkgLite = null;
10526
10527            if (onInt && onSd) {
10528                // Check if both bits are set.
10529                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10530                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10531            } else {
10532                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10533                        packageAbiOverride);
10534
10535                /*
10536                 * If we have too little free space, try to free cache
10537                 * before giving up.
10538                 */
10539                if (!origin.staged && pkgLite.recommendedInstallLocation
10540                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10541                    // TODO: focus freeing disk space on the target device
10542                    final StorageManager storage = StorageManager.from(mContext);
10543                    final long lowThreshold = storage.getStorageLowBytes(
10544                            Environment.getDataDirectory());
10545
10546                    final long sizeBytes = mContainerService.calculateInstalledSize(
10547                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10548
10549                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10550                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10551                                installFlags, packageAbiOverride);
10552                    }
10553
10554                    /*
10555                     * The cache free must have deleted the file we
10556                     * downloaded to install.
10557                     *
10558                     * TODO: fix the "freeCache" call to not delete
10559                     *       the file we care about.
10560                     */
10561                    if (pkgLite.recommendedInstallLocation
10562                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10563                        pkgLite.recommendedInstallLocation
10564                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10565                    }
10566                }
10567            }
10568
10569            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10570                int loc = pkgLite.recommendedInstallLocation;
10571                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10572                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10573                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10574                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10575                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10576                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10577                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10578                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10579                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10580                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10581                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10582                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10583                } else {
10584                    // Override with defaults if needed.
10585                    loc = installLocationPolicy(pkgLite);
10586                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10587                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10588                    } else if (!onSd && !onInt) {
10589                        // Override install location with flags
10590                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10591                            // Set the flag to install on external media.
10592                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10593                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10594                        } else {
10595                            // Make sure the flag for installing on external
10596                            // media is unset
10597                            installFlags |= PackageManager.INSTALL_INTERNAL;
10598                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10599                        }
10600                    }
10601                }
10602            }
10603
10604            final InstallArgs args = createInstallArgs(this);
10605            mArgs = args;
10606
10607            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10608                 /*
10609                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10610                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10611                 */
10612                int userIdentifier = getUser().getIdentifier();
10613                if (userIdentifier == UserHandle.USER_ALL
10614                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10615                    userIdentifier = UserHandle.USER_OWNER;
10616                }
10617
10618                /*
10619                 * Determine if we have any installed package verifiers. If we
10620                 * do, then we'll defer to them to verify the packages.
10621                 */
10622                final int requiredUid = mRequiredVerifierPackage == null ? -1
10623                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10624                if (!origin.existing && requiredUid != -1
10625                        && isVerificationEnabled(userIdentifier, installFlags)) {
10626                    final Intent verification = new Intent(
10627                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10628                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10629                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10630                            PACKAGE_MIME_TYPE);
10631                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10632
10633                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10634                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10635                            0 /* TODO: Which userId? */);
10636
10637                    if (DEBUG_VERIFY) {
10638                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10639                                + verification.toString() + " with " + pkgLite.verifiers.length
10640                                + " optional verifiers");
10641                    }
10642
10643                    final int verificationId = mPendingVerificationToken++;
10644
10645                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10646
10647                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10648                            installerPackageName);
10649
10650                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10651                            installFlags);
10652
10653                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10654                            pkgLite.packageName);
10655
10656                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10657                            pkgLite.versionCode);
10658
10659                    if (verificationParams != null) {
10660                        if (verificationParams.getVerificationURI() != null) {
10661                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10662                                 verificationParams.getVerificationURI());
10663                        }
10664                        if (verificationParams.getOriginatingURI() != null) {
10665                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10666                                  verificationParams.getOriginatingURI());
10667                        }
10668                        if (verificationParams.getReferrer() != null) {
10669                            verification.putExtra(Intent.EXTRA_REFERRER,
10670                                  verificationParams.getReferrer());
10671                        }
10672                        if (verificationParams.getOriginatingUid() >= 0) {
10673                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10674                                  verificationParams.getOriginatingUid());
10675                        }
10676                        if (verificationParams.getInstallerUid() >= 0) {
10677                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10678                                  verificationParams.getInstallerUid());
10679                        }
10680                    }
10681
10682                    final PackageVerificationState verificationState = new PackageVerificationState(
10683                            requiredUid, args);
10684
10685                    mPendingVerification.append(verificationId, verificationState);
10686
10687                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10688                            receivers, verificationState);
10689
10690                    // Apps installed for "all" users use the device owner to verify the app
10691                    UserHandle verifierUser = getUser();
10692                    if (verifierUser == UserHandle.ALL) {
10693                        verifierUser = UserHandle.OWNER;
10694                    }
10695
10696                    /*
10697                     * If any sufficient verifiers were listed in the package
10698                     * manifest, attempt to ask them.
10699                     */
10700                    if (sufficientVerifiers != null) {
10701                        final int N = sufficientVerifiers.size();
10702                        if (N == 0) {
10703                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10704                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10705                        } else {
10706                            for (int i = 0; i < N; i++) {
10707                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10708
10709                                final Intent sufficientIntent = new Intent(verification);
10710                                sufficientIntent.setComponent(verifierComponent);
10711                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10712                            }
10713                        }
10714                    }
10715
10716                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10717                            mRequiredVerifierPackage, receivers);
10718                    if (ret == PackageManager.INSTALL_SUCCEEDED
10719                            && mRequiredVerifierPackage != null) {
10720                        /*
10721                         * Send the intent to the required verification agent,
10722                         * but only start the verification timeout after the
10723                         * target BroadcastReceivers have run.
10724                         */
10725                        verification.setComponent(requiredVerifierComponent);
10726                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10727                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10728                                new BroadcastReceiver() {
10729                                    @Override
10730                                    public void onReceive(Context context, Intent intent) {
10731                                        final Message msg = mHandler
10732                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10733                                        msg.arg1 = verificationId;
10734                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10735                                    }
10736                                }, null, 0, null, null);
10737
10738                        /*
10739                         * We don't want the copy to proceed until verification
10740                         * succeeds, so null out this field.
10741                         */
10742                        mArgs = null;
10743                    }
10744                } else {
10745                    /*
10746                     * No package verification is enabled, so immediately start
10747                     * the remote call to initiate copy using temporary file.
10748                     */
10749                    ret = args.copyApk(mContainerService, true);
10750                }
10751            }
10752
10753            mRet = ret;
10754        }
10755
10756        @Override
10757        void handleReturnCode() {
10758            // If mArgs is null, then MCS couldn't be reached. When it
10759            // reconnects, it will try again to install. At that point, this
10760            // will succeed.
10761            if (mArgs != null) {
10762                processPendingInstall(mArgs, mRet);
10763            }
10764        }
10765
10766        @Override
10767        void handleServiceError() {
10768            mArgs = createInstallArgs(this);
10769            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10770        }
10771
10772        public boolean isForwardLocked() {
10773            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10774        }
10775    }
10776
10777    /**
10778     * Used during creation of InstallArgs
10779     *
10780     * @param installFlags package installation flags
10781     * @return true if should be installed on external storage
10782     */
10783    private static boolean installOnExternalAsec(int installFlags) {
10784        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10785            return false;
10786        }
10787        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10788            return true;
10789        }
10790        return false;
10791    }
10792
10793    /**
10794     * Used during creation of InstallArgs
10795     *
10796     * @param installFlags package installation flags
10797     * @return true if should be installed as forward locked
10798     */
10799    private static boolean installForwardLocked(int installFlags) {
10800        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10801    }
10802
10803    private InstallArgs createInstallArgs(InstallParams params) {
10804        if (params.move != null) {
10805            return new MoveInstallArgs(params);
10806        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10807            return new AsecInstallArgs(params);
10808        } else {
10809            return new FileInstallArgs(params);
10810        }
10811    }
10812
10813    /**
10814     * Create args that describe an existing installed package. Typically used
10815     * when cleaning up old installs, or used as a move source.
10816     */
10817    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10818            String resourcePath, String[] instructionSets) {
10819        final boolean isInAsec;
10820        if (installOnExternalAsec(installFlags)) {
10821            /* Apps on SD card are always in ASEC containers. */
10822            isInAsec = true;
10823        } else if (installForwardLocked(installFlags)
10824                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10825            /*
10826             * Forward-locked apps are only in ASEC containers if they're the
10827             * new style
10828             */
10829            isInAsec = true;
10830        } else {
10831            isInAsec = false;
10832        }
10833
10834        if (isInAsec) {
10835            return new AsecInstallArgs(codePath, instructionSets,
10836                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10837        } else {
10838            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10839        }
10840    }
10841
10842    static abstract class InstallArgs {
10843        /** @see InstallParams#origin */
10844        final OriginInfo origin;
10845        /** @see InstallParams#move */
10846        final MoveInfo move;
10847
10848        final IPackageInstallObserver2 observer;
10849        // Always refers to PackageManager flags only
10850        final int installFlags;
10851        final String installerPackageName;
10852        final String volumeUuid;
10853        final ManifestDigest manifestDigest;
10854        final UserHandle user;
10855        final String abiOverride;
10856        final String[] installGrantPermissions;
10857
10858        // The list of instruction sets supported by this app. This is currently
10859        // only used during the rmdex() phase to clean up resources. We can get rid of this
10860        // if we move dex files under the common app path.
10861        /* nullable */ String[] instructionSets;
10862
10863        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10864                int installFlags, String installerPackageName, String volumeUuid,
10865                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10866                String abiOverride, String[] installGrantPermissions) {
10867            this.origin = origin;
10868            this.move = move;
10869            this.installFlags = installFlags;
10870            this.observer = observer;
10871            this.installerPackageName = installerPackageName;
10872            this.volumeUuid = volumeUuid;
10873            this.manifestDigest = manifestDigest;
10874            this.user = user;
10875            this.instructionSets = instructionSets;
10876            this.abiOverride = abiOverride;
10877            this.installGrantPermissions = installGrantPermissions;
10878        }
10879
10880        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10881        abstract int doPreInstall(int status);
10882
10883        /**
10884         * Rename package into final resting place. All paths on the given
10885         * scanned package should be updated to reflect the rename.
10886         */
10887        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10888        abstract int doPostInstall(int status, int uid);
10889
10890        /** @see PackageSettingBase#codePathString */
10891        abstract String getCodePath();
10892        /** @see PackageSettingBase#resourcePathString */
10893        abstract String getResourcePath();
10894
10895        // Need installer lock especially for dex file removal.
10896        abstract void cleanUpResourcesLI();
10897        abstract boolean doPostDeleteLI(boolean delete);
10898
10899        /**
10900         * Called before the source arguments are copied. This is used mostly
10901         * for MoveParams when it needs to read the source file to put it in the
10902         * destination.
10903         */
10904        int doPreCopy() {
10905            return PackageManager.INSTALL_SUCCEEDED;
10906        }
10907
10908        /**
10909         * Called after the source arguments are copied. This is used mostly for
10910         * MoveParams when it needs to read the source file to put it in the
10911         * destination.
10912         *
10913         * @return
10914         */
10915        int doPostCopy(int uid) {
10916            return PackageManager.INSTALL_SUCCEEDED;
10917        }
10918
10919        protected boolean isFwdLocked() {
10920            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10921        }
10922
10923        protected boolean isExternalAsec() {
10924            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10925        }
10926
10927        UserHandle getUser() {
10928            return user;
10929        }
10930    }
10931
10932    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10933        if (!allCodePaths.isEmpty()) {
10934            if (instructionSets == null) {
10935                throw new IllegalStateException("instructionSet == null");
10936            }
10937            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10938            for (String codePath : allCodePaths) {
10939                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10940                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10941                    if (retCode < 0) {
10942                        Slog.w(TAG, "Couldn't remove dex file for package: "
10943                                + " at location " + codePath + ", retcode=" + retCode);
10944                        // we don't consider this to be a failure of the core package deletion
10945                    }
10946                }
10947            }
10948        }
10949    }
10950
10951    /**
10952     * Logic to handle installation of non-ASEC applications, including copying
10953     * and renaming logic.
10954     */
10955    class FileInstallArgs extends InstallArgs {
10956        private File codeFile;
10957        private File resourceFile;
10958
10959        // Example topology:
10960        // /data/app/com.example/base.apk
10961        // /data/app/com.example/split_foo.apk
10962        // /data/app/com.example/lib/arm/libfoo.so
10963        // /data/app/com.example/lib/arm64/libfoo.so
10964        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10965
10966        /** New install */
10967        FileInstallArgs(InstallParams params) {
10968            super(params.origin, params.move, params.observer, params.installFlags,
10969                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10970                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10971                    params.grantedRuntimePermissions);
10972            if (isFwdLocked()) {
10973                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10974            }
10975        }
10976
10977        /** Existing install */
10978        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10979            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10980                    null, null);
10981            this.codeFile = (codePath != null) ? new File(codePath) : null;
10982            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10983        }
10984
10985        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10986            if (origin.staged) {
10987                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10988                codeFile = origin.file;
10989                resourceFile = origin.file;
10990                return PackageManager.INSTALL_SUCCEEDED;
10991            }
10992
10993            try {
10994                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10995                codeFile = tempDir;
10996                resourceFile = tempDir;
10997            } catch (IOException e) {
10998                Slog.w(TAG, "Failed to create copy file: " + e);
10999                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11000            }
11001
11002            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11003                @Override
11004                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11005                    if (!FileUtils.isValidExtFilename(name)) {
11006                        throw new IllegalArgumentException("Invalid filename: " + name);
11007                    }
11008                    try {
11009                        final File file = new File(codeFile, name);
11010                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11011                                O_RDWR | O_CREAT, 0644);
11012                        Os.chmod(file.getAbsolutePath(), 0644);
11013                        return new ParcelFileDescriptor(fd);
11014                    } catch (ErrnoException e) {
11015                        throw new RemoteException("Failed to open: " + e.getMessage());
11016                    }
11017                }
11018            };
11019
11020            int ret = PackageManager.INSTALL_SUCCEEDED;
11021            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11022            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11023                Slog.e(TAG, "Failed to copy package");
11024                return ret;
11025            }
11026
11027            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11028            NativeLibraryHelper.Handle handle = null;
11029            try {
11030                handle = NativeLibraryHelper.Handle.create(codeFile);
11031                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11032                        abiOverride);
11033            } catch (IOException e) {
11034                Slog.e(TAG, "Copying native libraries failed", e);
11035                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11036            } finally {
11037                IoUtils.closeQuietly(handle);
11038            }
11039
11040            return ret;
11041        }
11042
11043        int doPreInstall(int status) {
11044            if (status != PackageManager.INSTALL_SUCCEEDED) {
11045                cleanUp();
11046            }
11047            return status;
11048        }
11049
11050        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11051            if (status != PackageManager.INSTALL_SUCCEEDED) {
11052                cleanUp();
11053                return false;
11054            }
11055
11056            final File targetDir = codeFile.getParentFile();
11057            final File beforeCodeFile = codeFile;
11058            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11059
11060            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11061            try {
11062                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11063            } catch (ErrnoException e) {
11064                Slog.w(TAG, "Failed to rename", e);
11065                return false;
11066            }
11067
11068            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11069                Slog.w(TAG, "Failed to restorecon");
11070                return false;
11071            }
11072
11073            // Reflect the rename internally
11074            codeFile = afterCodeFile;
11075            resourceFile = afterCodeFile;
11076
11077            // Reflect the rename in scanned details
11078            pkg.codePath = afterCodeFile.getAbsolutePath();
11079            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11080                    pkg.baseCodePath);
11081            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11082                    pkg.splitCodePaths);
11083
11084            // Reflect the rename in app info
11085            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11086            pkg.applicationInfo.setCodePath(pkg.codePath);
11087            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11088            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11089            pkg.applicationInfo.setResourcePath(pkg.codePath);
11090            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11091            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11092
11093            return true;
11094        }
11095
11096        int doPostInstall(int status, int uid) {
11097            if (status != PackageManager.INSTALL_SUCCEEDED) {
11098                cleanUp();
11099            }
11100            return status;
11101        }
11102
11103        @Override
11104        String getCodePath() {
11105            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11106        }
11107
11108        @Override
11109        String getResourcePath() {
11110            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11111        }
11112
11113        private boolean cleanUp() {
11114            if (codeFile == null || !codeFile.exists()) {
11115                return false;
11116            }
11117
11118            if (codeFile.isDirectory()) {
11119                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11120            } else {
11121                codeFile.delete();
11122            }
11123
11124            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11125                resourceFile.delete();
11126            }
11127
11128            return true;
11129        }
11130
11131        void cleanUpResourcesLI() {
11132            // Try enumerating all code paths before deleting
11133            List<String> allCodePaths = Collections.EMPTY_LIST;
11134            if (codeFile != null && codeFile.exists()) {
11135                try {
11136                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11137                    allCodePaths = pkg.getAllCodePaths();
11138                } catch (PackageParserException e) {
11139                    // Ignored; we tried our best
11140                }
11141            }
11142
11143            cleanUp();
11144            removeDexFiles(allCodePaths, instructionSets);
11145        }
11146
11147        boolean doPostDeleteLI(boolean delete) {
11148            // XXX err, shouldn't we respect the delete flag?
11149            cleanUpResourcesLI();
11150            return true;
11151        }
11152    }
11153
11154    private boolean isAsecExternal(String cid) {
11155        final String asecPath = PackageHelper.getSdFilesystem(cid);
11156        return !asecPath.startsWith(mAsecInternalPath);
11157    }
11158
11159    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11160            PackageManagerException {
11161        if (copyRet < 0) {
11162            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11163                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11164                throw new PackageManagerException(copyRet, message);
11165            }
11166        }
11167    }
11168
11169    /**
11170     * Extract the MountService "container ID" from the full code path of an
11171     * .apk.
11172     */
11173    static String cidFromCodePath(String fullCodePath) {
11174        int eidx = fullCodePath.lastIndexOf("/");
11175        String subStr1 = fullCodePath.substring(0, eidx);
11176        int sidx = subStr1.lastIndexOf("/");
11177        return subStr1.substring(sidx+1, eidx);
11178    }
11179
11180    /**
11181     * Logic to handle installation of ASEC applications, including copying and
11182     * renaming logic.
11183     */
11184    class AsecInstallArgs extends InstallArgs {
11185        static final String RES_FILE_NAME = "pkg.apk";
11186        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11187
11188        String cid;
11189        String packagePath;
11190        String resourcePath;
11191
11192        /** New install */
11193        AsecInstallArgs(InstallParams params) {
11194            super(params.origin, params.move, params.observer, params.installFlags,
11195                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11196                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11197                    params.grantedRuntimePermissions);
11198        }
11199
11200        /** Existing install */
11201        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11202                        boolean isExternal, boolean isForwardLocked) {
11203            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11204                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11205                    instructionSets, null, null);
11206            // Hackily pretend we're still looking at a full code path
11207            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11208                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11209            }
11210
11211            // Extract cid from fullCodePath
11212            int eidx = fullCodePath.lastIndexOf("/");
11213            String subStr1 = fullCodePath.substring(0, eidx);
11214            int sidx = subStr1.lastIndexOf("/");
11215            cid = subStr1.substring(sidx+1, eidx);
11216            setMountPath(subStr1);
11217        }
11218
11219        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11220            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11221                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11222                    instructionSets, null, null);
11223            this.cid = cid;
11224            setMountPath(PackageHelper.getSdDir(cid));
11225        }
11226
11227        void createCopyFile() {
11228            cid = mInstallerService.allocateExternalStageCidLegacy();
11229        }
11230
11231        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11232            if (origin.staged) {
11233                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11234                cid = origin.cid;
11235                setMountPath(PackageHelper.getSdDir(cid));
11236                return PackageManager.INSTALL_SUCCEEDED;
11237            }
11238
11239            if (temp) {
11240                createCopyFile();
11241            } else {
11242                /*
11243                 * Pre-emptively destroy the container since it's destroyed if
11244                 * copying fails due to it existing anyway.
11245                 */
11246                PackageHelper.destroySdDir(cid);
11247            }
11248
11249            final String newMountPath = imcs.copyPackageToContainer(
11250                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11251                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11252
11253            if (newMountPath != null) {
11254                setMountPath(newMountPath);
11255                return PackageManager.INSTALL_SUCCEEDED;
11256            } else {
11257                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11258            }
11259        }
11260
11261        @Override
11262        String getCodePath() {
11263            return packagePath;
11264        }
11265
11266        @Override
11267        String getResourcePath() {
11268            return resourcePath;
11269        }
11270
11271        int doPreInstall(int status) {
11272            if (status != PackageManager.INSTALL_SUCCEEDED) {
11273                // Destroy container
11274                PackageHelper.destroySdDir(cid);
11275            } else {
11276                boolean mounted = PackageHelper.isContainerMounted(cid);
11277                if (!mounted) {
11278                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11279                            Process.SYSTEM_UID);
11280                    if (newMountPath != null) {
11281                        setMountPath(newMountPath);
11282                    } else {
11283                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11284                    }
11285                }
11286            }
11287            return status;
11288        }
11289
11290        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11291            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11292            String newMountPath = null;
11293            if (PackageHelper.isContainerMounted(cid)) {
11294                // Unmount the container
11295                if (!PackageHelper.unMountSdDir(cid)) {
11296                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11297                    return false;
11298                }
11299            }
11300            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11301                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11302                        " which might be stale. Will try to clean up.");
11303                // Clean up the stale container and proceed to recreate.
11304                if (!PackageHelper.destroySdDir(newCacheId)) {
11305                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11306                    return false;
11307                }
11308                // Successfully cleaned up stale container. Try to rename again.
11309                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11310                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11311                            + " inspite of cleaning it up.");
11312                    return false;
11313                }
11314            }
11315            if (!PackageHelper.isContainerMounted(newCacheId)) {
11316                Slog.w(TAG, "Mounting container " + newCacheId);
11317                newMountPath = PackageHelper.mountSdDir(newCacheId,
11318                        getEncryptKey(), Process.SYSTEM_UID);
11319            } else {
11320                newMountPath = PackageHelper.getSdDir(newCacheId);
11321            }
11322            if (newMountPath == null) {
11323                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11324                return false;
11325            }
11326            Log.i(TAG, "Succesfully renamed " + cid +
11327                    " to " + newCacheId +
11328                    " at new path: " + newMountPath);
11329            cid = newCacheId;
11330
11331            final File beforeCodeFile = new File(packagePath);
11332            setMountPath(newMountPath);
11333            final File afterCodeFile = new File(packagePath);
11334
11335            // Reflect the rename in scanned details
11336            pkg.codePath = afterCodeFile.getAbsolutePath();
11337            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11338                    pkg.baseCodePath);
11339            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11340                    pkg.splitCodePaths);
11341
11342            // Reflect the rename in app info
11343            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11344            pkg.applicationInfo.setCodePath(pkg.codePath);
11345            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11346            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11347            pkg.applicationInfo.setResourcePath(pkg.codePath);
11348            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11349            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11350
11351            return true;
11352        }
11353
11354        private void setMountPath(String mountPath) {
11355            final File mountFile = new File(mountPath);
11356
11357            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11358            if (monolithicFile.exists()) {
11359                packagePath = monolithicFile.getAbsolutePath();
11360                if (isFwdLocked()) {
11361                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11362                } else {
11363                    resourcePath = packagePath;
11364                }
11365            } else {
11366                packagePath = mountFile.getAbsolutePath();
11367                resourcePath = packagePath;
11368            }
11369        }
11370
11371        int doPostInstall(int status, int uid) {
11372            if (status != PackageManager.INSTALL_SUCCEEDED) {
11373                cleanUp();
11374            } else {
11375                final int groupOwner;
11376                final String protectedFile;
11377                if (isFwdLocked()) {
11378                    groupOwner = UserHandle.getSharedAppGid(uid);
11379                    protectedFile = RES_FILE_NAME;
11380                } else {
11381                    groupOwner = -1;
11382                    protectedFile = null;
11383                }
11384
11385                if (uid < Process.FIRST_APPLICATION_UID
11386                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11387                    Slog.e(TAG, "Failed to finalize " + cid);
11388                    PackageHelper.destroySdDir(cid);
11389                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11390                }
11391
11392                boolean mounted = PackageHelper.isContainerMounted(cid);
11393                if (!mounted) {
11394                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11395                }
11396            }
11397            return status;
11398        }
11399
11400        private void cleanUp() {
11401            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11402
11403            // Destroy secure container
11404            PackageHelper.destroySdDir(cid);
11405        }
11406
11407        private List<String> getAllCodePaths() {
11408            final File codeFile = new File(getCodePath());
11409            if (codeFile != null && codeFile.exists()) {
11410                try {
11411                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11412                    return pkg.getAllCodePaths();
11413                } catch (PackageParserException e) {
11414                    // Ignored; we tried our best
11415                }
11416            }
11417            return Collections.EMPTY_LIST;
11418        }
11419
11420        void cleanUpResourcesLI() {
11421            // Enumerate all code paths before deleting
11422            cleanUpResourcesLI(getAllCodePaths());
11423        }
11424
11425        private void cleanUpResourcesLI(List<String> allCodePaths) {
11426            cleanUp();
11427            removeDexFiles(allCodePaths, instructionSets);
11428        }
11429
11430        String getPackageName() {
11431            return getAsecPackageName(cid);
11432        }
11433
11434        boolean doPostDeleteLI(boolean delete) {
11435            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11436            final List<String> allCodePaths = getAllCodePaths();
11437            boolean mounted = PackageHelper.isContainerMounted(cid);
11438            if (mounted) {
11439                // Unmount first
11440                if (PackageHelper.unMountSdDir(cid)) {
11441                    mounted = false;
11442                }
11443            }
11444            if (!mounted && delete) {
11445                cleanUpResourcesLI(allCodePaths);
11446            }
11447            return !mounted;
11448        }
11449
11450        @Override
11451        int doPreCopy() {
11452            if (isFwdLocked()) {
11453                if (!PackageHelper.fixSdPermissions(cid,
11454                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11455                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11456                }
11457            }
11458
11459            return PackageManager.INSTALL_SUCCEEDED;
11460        }
11461
11462        @Override
11463        int doPostCopy(int uid) {
11464            if (isFwdLocked()) {
11465                if (uid < Process.FIRST_APPLICATION_UID
11466                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11467                                RES_FILE_NAME)) {
11468                    Slog.e(TAG, "Failed to finalize " + cid);
11469                    PackageHelper.destroySdDir(cid);
11470                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11471                }
11472            }
11473
11474            return PackageManager.INSTALL_SUCCEEDED;
11475        }
11476    }
11477
11478    /**
11479     * Logic to handle movement of existing installed applications.
11480     */
11481    class MoveInstallArgs extends InstallArgs {
11482        private File codeFile;
11483        private File resourceFile;
11484
11485        /** New install */
11486        MoveInstallArgs(InstallParams params) {
11487            super(params.origin, params.move, params.observer, params.installFlags,
11488                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11489                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11490                    params.grantedRuntimePermissions);
11491        }
11492
11493        int copyApk(IMediaContainerService imcs, boolean temp) {
11494            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11495                    + move.fromUuid + " to " + move.toUuid);
11496            synchronized (mInstaller) {
11497                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11498                        move.dataAppName, move.appId, move.seinfo) != 0) {
11499                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11500                }
11501            }
11502
11503            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11504            resourceFile = codeFile;
11505            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11506
11507            return PackageManager.INSTALL_SUCCEEDED;
11508        }
11509
11510        int doPreInstall(int status) {
11511            if (status != PackageManager.INSTALL_SUCCEEDED) {
11512                cleanUp(move.toUuid);
11513            }
11514            return status;
11515        }
11516
11517        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11518            if (status != PackageManager.INSTALL_SUCCEEDED) {
11519                cleanUp(move.toUuid);
11520                return false;
11521            }
11522
11523            // Reflect the move in app info
11524            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11525            pkg.applicationInfo.setCodePath(pkg.codePath);
11526            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11527            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11528            pkg.applicationInfo.setResourcePath(pkg.codePath);
11529            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11530            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11531
11532            return true;
11533        }
11534
11535        int doPostInstall(int status, int uid) {
11536            if (status == PackageManager.INSTALL_SUCCEEDED) {
11537                cleanUp(move.fromUuid);
11538            } else {
11539                cleanUp(move.toUuid);
11540            }
11541            return status;
11542        }
11543
11544        @Override
11545        String getCodePath() {
11546            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11547        }
11548
11549        @Override
11550        String getResourcePath() {
11551            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11552        }
11553
11554        private boolean cleanUp(String volumeUuid) {
11555            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11556                    move.dataAppName);
11557            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11558            synchronized (mInstallLock) {
11559                // Clean up both app data and code
11560                removeDataDirsLI(volumeUuid, move.packageName);
11561                if (codeFile.isDirectory()) {
11562                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11563                } else {
11564                    codeFile.delete();
11565                }
11566            }
11567            return true;
11568        }
11569
11570        void cleanUpResourcesLI() {
11571            throw new UnsupportedOperationException();
11572        }
11573
11574        boolean doPostDeleteLI(boolean delete) {
11575            throw new UnsupportedOperationException();
11576        }
11577    }
11578
11579    static String getAsecPackageName(String packageCid) {
11580        int idx = packageCid.lastIndexOf("-");
11581        if (idx == -1) {
11582            return packageCid;
11583        }
11584        return packageCid.substring(0, idx);
11585    }
11586
11587    // Utility method used to create code paths based on package name and available index.
11588    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11589        String idxStr = "";
11590        int idx = 1;
11591        // Fall back to default value of idx=1 if prefix is not
11592        // part of oldCodePath
11593        if (oldCodePath != null) {
11594            String subStr = oldCodePath;
11595            // Drop the suffix right away
11596            if (suffix != null && subStr.endsWith(suffix)) {
11597                subStr = subStr.substring(0, subStr.length() - suffix.length());
11598            }
11599            // If oldCodePath already contains prefix find out the
11600            // ending index to either increment or decrement.
11601            int sidx = subStr.lastIndexOf(prefix);
11602            if (sidx != -1) {
11603                subStr = subStr.substring(sidx + prefix.length());
11604                if (subStr != null) {
11605                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11606                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11607                    }
11608                    try {
11609                        idx = Integer.parseInt(subStr);
11610                        if (idx <= 1) {
11611                            idx++;
11612                        } else {
11613                            idx--;
11614                        }
11615                    } catch(NumberFormatException e) {
11616                    }
11617                }
11618            }
11619        }
11620        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11621        return prefix + idxStr;
11622    }
11623
11624    private File getNextCodePath(File targetDir, String packageName) {
11625        int suffix = 1;
11626        File result;
11627        do {
11628            result = new File(targetDir, packageName + "-" + suffix);
11629            suffix++;
11630        } while (result.exists());
11631        return result;
11632    }
11633
11634    // Utility method that returns the relative package path with respect
11635    // to the installation directory. Like say for /data/data/com.test-1.apk
11636    // string com.test-1 is returned.
11637    static String deriveCodePathName(String codePath) {
11638        if (codePath == null) {
11639            return null;
11640        }
11641        final File codeFile = new File(codePath);
11642        final String name = codeFile.getName();
11643        if (codeFile.isDirectory()) {
11644            return name;
11645        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11646            final int lastDot = name.lastIndexOf('.');
11647            return name.substring(0, lastDot);
11648        } else {
11649            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11650            return null;
11651        }
11652    }
11653
11654    class PackageInstalledInfo {
11655        String name;
11656        int uid;
11657        // The set of users that originally had this package installed.
11658        int[] origUsers;
11659        // The set of users that now have this package installed.
11660        int[] newUsers;
11661        PackageParser.Package pkg;
11662        int returnCode;
11663        String returnMsg;
11664        PackageRemovedInfo removedInfo;
11665
11666        public void setError(int code, String msg) {
11667            returnCode = code;
11668            returnMsg = msg;
11669            Slog.w(TAG, msg);
11670        }
11671
11672        public void setError(String msg, PackageParserException e) {
11673            returnCode = e.error;
11674            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11675            Slog.w(TAG, msg, e);
11676        }
11677
11678        public void setError(String msg, PackageManagerException e) {
11679            returnCode = e.error;
11680            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11681            Slog.w(TAG, msg, e);
11682        }
11683
11684        // In some error cases we want to convey more info back to the observer
11685        String origPackage;
11686        String origPermission;
11687    }
11688
11689    /*
11690     * Install a non-existing package.
11691     */
11692    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11693            UserHandle user, String installerPackageName, String volumeUuid,
11694            PackageInstalledInfo res) {
11695        // Remember this for later, in case we need to rollback this install
11696        String pkgName = pkg.packageName;
11697
11698        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11699        final boolean dataDirExists = Environment
11700                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11701        synchronized(mPackages) {
11702            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11703                // A package with the same name is already installed, though
11704                // it has been renamed to an older name.  The package we
11705                // are trying to install should be installed as an update to
11706                // the existing one, but that has not been requested, so bail.
11707                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11708                        + " without first uninstalling package running as "
11709                        + mSettings.mRenamedPackages.get(pkgName));
11710                return;
11711            }
11712            if (mPackages.containsKey(pkgName)) {
11713                // Don't allow installation over an existing package with the same name.
11714                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11715                        + " without first uninstalling.");
11716                return;
11717            }
11718        }
11719
11720        try {
11721            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11722                    System.currentTimeMillis(), user);
11723
11724            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11725            // delete the partially installed application. the data directory will have to be
11726            // restored if it was already existing
11727            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11728                // remove package from internal structures.  Note that we want deletePackageX to
11729                // delete the package data and cache directories that it created in
11730                // scanPackageLocked, unless those directories existed before we even tried to
11731                // install.
11732                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11733                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11734                                res.removedInfo, true);
11735            }
11736
11737        } catch (PackageManagerException e) {
11738            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11739        }
11740    }
11741
11742    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11743        // Can't rotate keys during boot or if sharedUser.
11744        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11745                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11746            return false;
11747        }
11748        // app is using upgradeKeySets; make sure all are valid
11749        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11750        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11751        for (int i = 0; i < upgradeKeySets.length; i++) {
11752            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11753                Slog.wtf(TAG, "Package "
11754                         + (oldPs.name != null ? oldPs.name : "<null>")
11755                         + " contains upgrade-key-set reference to unknown key-set: "
11756                         + upgradeKeySets[i]
11757                         + " reverting to signatures check.");
11758                return false;
11759            }
11760        }
11761        return true;
11762    }
11763
11764    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11765        // Upgrade keysets are being used.  Determine if new package has a superset of the
11766        // required keys.
11767        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11768        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11769        for (int i = 0; i < upgradeKeySets.length; i++) {
11770            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11771            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11772                return true;
11773            }
11774        }
11775        return false;
11776    }
11777
11778    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11779            UserHandle user, String installerPackageName, String volumeUuid,
11780            PackageInstalledInfo res) {
11781        final PackageParser.Package oldPackage;
11782        final String pkgName = pkg.packageName;
11783        final int[] allUsers;
11784        final boolean[] perUserInstalled;
11785
11786        // First find the old package info and check signatures
11787        synchronized(mPackages) {
11788            oldPackage = mPackages.get(pkgName);
11789            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11790            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11791            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11792                if(!checkUpgradeKeySetLP(ps, pkg)) {
11793                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11794                            "New package not signed by keys specified by upgrade-keysets: "
11795                            + pkgName);
11796                    return;
11797                }
11798            } else {
11799                // default to original signature matching
11800                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11801                    != PackageManager.SIGNATURE_MATCH) {
11802                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11803                            "New package has a different signature: " + pkgName);
11804                    return;
11805                }
11806            }
11807
11808            // In case of rollback, remember per-user/profile install state
11809            allUsers = sUserManager.getUserIds();
11810            perUserInstalled = new boolean[allUsers.length];
11811            for (int i = 0; i < allUsers.length; i++) {
11812                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11813            }
11814        }
11815
11816        boolean sysPkg = (isSystemApp(oldPackage));
11817        if (sysPkg) {
11818            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11819                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11820        } else {
11821            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11822                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11823        }
11824    }
11825
11826    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11827            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11828            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11829            String volumeUuid, PackageInstalledInfo res) {
11830        String pkgName = deletedPackage.packageName;
11831        boolean deletedPkg = true;
11832        boolean updatedSettings = false;
11833
11834        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11835                + deletedPackage);
11836        long origUpdateTime;
11837        if (pkg.mExtras != null) {
11838            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11839        } else {
11840            origUpdateTime = 0;
11841        }
11842
11843        // First delete the existing package while retaining the data directory
11844        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11845                res.removedInfo, true)) {
11846            // If the existing package wasn't successfully deleted
11847            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11848            deletedPkg = false;
11849        } else {
11850            // Successfully deleted the old package; proceed with replace.
11851
11852            // If deleted package lived in a container, give users a chance to
11853            // relinquish resources before killing.
11854            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11855                if (DEBUG_INSTALL) {
11856                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11857                }
11858                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11859                final ArrayList<String> pkgList = new ArrayList<String>(1);
11860                pkgList.add(deletedPackage.applicationInfo.packageName);
11861                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11862            }
11863
11864            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11865            try {
11866                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11867                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11868                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11869                        perUserInstalled, res, user);
11870                updatedSettings = true;
11871            } catch (PackageManagerException e) {
11872                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11873            }
11874        }
11875
11876        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11877            // remove package from internal structures.  Note that we want deletePackageX to
11878            // delete the package data and cache directories that it created in
11879            // scanPackageLocked, unless those directories existed before we even tried to
11880            // install.
11881            if(updatedSettings) {
11882                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11883                deletePackageLI(
11884                        pkgName, null, true, allUsers, perUserInstalled,
11885                        PackageManager.DELETE_KEEP_DATA,
11886                                res.removedInfo, true);
11887            }
11888            // Since we failed to install the new package we need to restore the old
11889            // package that we deleted.
11890            if (deletedPkg) {
11891                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11892                File restoreFile = new File(deletedPackage.codePath);
11893                // Parse old package
11894                boolean oldExternal = isExternal(deletedPackage);
11895                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11896                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11897                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11898                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11899                try {
11900                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11901                } catch (PackageManagerException e) {
11902                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11903                            + e.getMessage());
11904                    return;
11905                }
11906                // Restore of old package succeeded. Update permissions.
11907                // writer
11908                synchronized (mPackages) {
11909                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11910                            UPDATE_PERMISSIONS_ALL);
11911                    // can downgrade to reader
11912                    mSettings.writeLPr();
11913                }
11914                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11915            }
11916        }
11917    }
11918
11919    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11920            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11921            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11922            String volumeUuid, PackageInstalledInfo res) {
11923        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11924                + ", old=" + deletedPackage);
11925        boolean disabledSystem = false;
11926        boolean updatedSettings = false;
11927        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11928        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11929                != 0) {
11930            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11931        }
11932        String packageName = deletedPackage.packageName;
11933        if (packageName == null) {
11934            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11935                    "Attempt to delete null packageName.");
11936            return;
11937        }
11938        PackageParser.Package oldPkg;
11939        PackageSetting oldPkgSetting;
11940        // reader
11941        synchronized (mPackages) {
11942            oldPkg = mPackages.get(packageName);
11943            oldPkgSetting = mSettings.mPackages.get(packageName);
11944            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11945                    (oldPkgSetting == null)) {
11946                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11947                        "Couldn't find package:" + packageName + " information");
11948                return;
11949            }
11950        }
11951
11952        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11953
11954        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11955        res.removedInfo.removedPackage = packageName;
11956        // Remove existing system package
11957        removePackageLI(oldPkgSetting, true);
11958        // writer
11959        synchronized (mPackages) {
11960            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11961            if (!disabledSystem && deletedPackage != null) {
11962                // We didn't need to disable the .apk as a current system package,
11963                // which means we are replacing another update that is already
11964                // installed.  We need to make sure to delete the older one's .apk.
11965                res.removedInfo.args = createInstallArgsForExisting(0,
11966                        deletedPackage.applicationInfo.getCodePath(),
11967                        deletedPackage.applicationInfo.getResourcePath(),
11968                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11969            } else {
11970                res.removedInfo.args = null;
11971            }
11972        }
11973
11974        // Successfully disabled the old package. Now proceed with re-installation
11975        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11976
11977        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11978        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11979
11980        PackageParser.Package newPackage = null;
11981        try {
11982            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11983            if (newPackage.mExtras != null) {
11984                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11985                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11986                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11987
11988                // is the update attempting to change shared user? that isn't going to work...
11989                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11990                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11991                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11992                            + " to " + newPkgSetting.sharedUser);
11993                    updatedSettings = true;
11994                }
11995            }
11996
11997            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11998                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11999                        perUserInstalled, res, user);
12000                updatedSettings = true;
12001            }
12002
12003        } catch (PackageManagerException e) {
12004            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12005        }
12006
12007        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12008            // Re installation failed. Restore old information
12009            // Remove new pkg information
12010            if (newPackage != null) {
12011                removeInstalledPackageLI(newPackage, true);
12012            }
12013            // Add back the old system package
12014            try {
12015                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12016            } catch (PackageManagerException e) {
12017                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12018            }
12019            // Restore the old system information in Settings
12020            synchronized (mPackages) {
12021                if (disabledSystem) {
12022                    mSettings.enableSystemPackageLPw(packageName);
12023                }
12024                if (updatedSettings) {
12025                    mSettings.setInstallerPackageName(packageName,
12026                            oldPkgSetting.installerPackageName);
12027                }
12028                mSettings.writeLPr();
12029            }
12030        }
12031    }
12032
12033    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12034            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12035            UserHandle user) {
12036        String pkgName = newPackage.packageName;
12037        synchronized (mPackages) {
12038            //write settings. the installStatus will be incomplete at this stage.
12039            //note that the new package setting would have already been
12040            //added to mPackages. It hasn't been persisted yet.
12041            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12042            mSettings.writeLPr();
12043        }
12044
12045        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12046
12047        synchronized (mPackages) {
12048            updatePermissionsLPw(newPackage.packageName, newPackage,
12049                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12050                            ? UPDATE_PERMISSIONS_ALL : 0));
12051            // For system-bundled packages, we assume that installing an upgraded version
12052            // of the package implies that the user actually wants to run that new code,
12053            // so we enable the package.
12054            PackageSetting ps = mSettings.mPackages.get(pkgName);
12055            if (ps != null) {
12056                if (isSystemApp(newPackage)) {
12057                    // NB: implicit assumption that system package upgrades apply to all users
12058                    if (DEBUG_INSTALL) {
12059                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12060                    }
12061                    if (res.origUsers != null) {
12062                        for (int userHandle : res.origUsers) {
12063                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12064                                    userHandle, installerPackageName);
12065                        }
12066                    }
12067                    // Also convey the prior install/uninstall state
12068                    if (allUsers != null && perUserInstalled != null) {
12069                        for (int i = 0; i < allUsers.length; i++) {
12070                            if (DEBUG_INSTALL) {
12071                                Slog.d(TAG, "    user " + allUsers[i]
12072                                        + " => " + perUserInstalled[i]);
12073                            }
12074                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12075                        }
12076                        // these install state changes will be persisted in the
12077                        // upcoming call to mSettings.writeLPr().
12078                    }
12079                }
12080                // It's implied that when a user requests installation, they want the app to be
12081                // installed and enabled.
12082                int userId = user.getIdentifier();
12083                if (userId != UserHandle.USER_ALL) {
12084                    ps.setInstalled(true, userId);
12085                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12086                }
12087            }
12088            res.name = pkgName;
12089            res.uid = newPackage.applicationInfo.uid;
12090            res.pkg = newPackage;
12091            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12092            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12093            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12094            //to update install status
12095            mSettings.writeLPr();
12096        }
12097    }
12098
12099    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12100        final int installFlags = args.installFlags;
12101        final String installerPackageName = args.installerPackageName;
12102        final String volumeUuid = args.volumeUuid;
12103        final File tmpPackageFile = new File(args.getCodePath());
12104        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12105        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12106                || (args.volumeUuid != null));
12107        boolean replace = false;
12108        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12109        if (args.move != null) {
12110            // moving a complete application; perfom an initial scan on the new install location
12111            scanFlags |= SCAN_INITIAL;
12112        }
12113        // Result object to be returned
12114        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12115
12116        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12117        // Retrieve PackageSettings and parse package
12118        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12119                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12120                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12121        PackageParser pp = new PackageParser();
12122        pp.setSeparateProcesses(mSeparateProcesses);
12123        pp.setDisplayMetrics(mMetrics);
12124
12125        final PackageParser.Package pkg;
12126        try {
12127            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12128        } catch (PackageParserException e) {
12129            res.setError("Failed parse during installPackageLI", e);
12130            return;
12131        }
12132
12133        // Mark that we have an install time CPU ABI override.
12134        pkg.cpuAbiOverride = args.abiOverride;
12135
12136        String pkgName = res.name = pkg.packageName;
12137        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12138            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12139                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12140                return;
12141            }
12142        }
12143
12144        try {
12145            pp.collectCertificates(pkg, parseFlags);
12146            pp.collectManifestDigest(pkg);
12147        } catch (PackageParserException e) {
12148            res.setError("Failed collect during installPackageLI", e);
12149            return;
12150        }
12151
12152        /* If the installer passed in a manifest digest, compare it now. */
12153        if (args.manifestDigest != null) {
12154            if (DEBUG_INSTALL) {
12155                final String parsedManifest = pkg.manifestDigest == null ? "null"
12156                        : pkg.manifestDigest.toString();
12157                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12158                        + parsedManifest);
12159            }
12160
12161            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12162                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12163                return;
12164            }
12165        } else if (DEBUG_INSTALL) {
12166            final String parsedManifest = pkg.manifestDigest == null
12167                    ? "null" : pkg.manifestDigest.toString();
12168            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12169        }
12170
12171        // Get rid of all references to package scan path via parser.
12172        pp = null;
12173        String oldCodePath = null;
12174        boolean systemApp = false;
12175        synchronized (mPackages) {
12176            // Check if installing already existing package
12177            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12178                String oldName = mSettings.mRenamedPackages.get(pkgName);
12179                if (pkg.mOriginalPackages != null
12180                        && pkg.mOriginalPackages.contains(oldName)
12181                        && mPackages.containsKey(oldName)) {
12182                    // This package is derived from an original package,
12183                    // and this device has been updating from that original
12184                    // name.  We must continue using the original name, so
12185                    // rename the new package here.
12186                    pkg.setPackageName(oldName);
12187                    pkgName = pkg.packageName;
12188                    replace = true;
12189                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12190                            + oldName + " pkgName=" + pkgName);
12191                } else if (mPackages.containsKey(pkgName)) {
12192                    // This package, under its official name, already exists
12193                    // on the device; we should replace it.
12194                    replace = true;
12195                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12196                }
12197
12198                // Prevent apps opting out from runtime permissions
12199                if (replace) {
12200                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12201                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12202                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12203                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12204                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12205                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12206                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12207                                        + " doesn't support runtime permissions but the old"
12208                                        + " target SDK " + oldTargetSdk + " does.");
12209                        return;
12210                    }
12211                }
12212            }
12213
12214            PackageSetting ps = mSettings.mPackages.get(pkgName);
12215            if (ps != null) {
12216                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12217
12218                // Quick sanity check that we're signed correctly if updating;
12219                // we'll check this again later when scanning, but we want to
12220                // bail early here before tripping over redefined permissions.
12221                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12222                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12223                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12224                                + pkg.packageName + " upgrade keys do not match the "
12225                                + "previously installed version");
12226                        return;
12227                    }
12228                } else {
12229                    try {
12230                        verifySignaturesLP(ps, pkg);
12231                    } catch (PackageManagerException e) {
12232                        res.setError(e.error, e.getMessage());
12233                        return;
12234                    }
12235                }
12236
12237                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12238                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12239                    systemApp = (ps.pkg.applicationInfo.flags &
12240                            ApplicationInfo.FLAG_SYSTEM) != 0;
12241                }
12242                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12243            }
12244
12245            // Check whether the newly-scanned package wants to define an already-defined perm
12246            int N = pkg.permissions.size();
12247            for (int i = N-1; i >= 0; i--) {
12248                PackageParser.Permission perm = pkg.permissions.get(i);
12249                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12250                if (bp != null) {
12251                    // If the defining package is signed with our cert, it's okay.  This
12252                    // also includes the "updating the same package" case, of course.
12253                    // "updating same package" could also involve key-rotation.
12254                    final boolean sigsOk;
12255                    if (bp.sourcePackage.equals(pkg.packageName)
12256                            && (bp.packageSetting instanceof PackageSetting)
12257                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12258                                    scanFlags))) {
12259                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12260                    } else {
12261                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12262                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12263                    }
12264                    if (!sigsOk) {
12265                        // If the owning package is the system itself, we log but allow
12266                        // install to proceed; we fail the install on all other permission
12267                        // redefinitions.
12268                        if (!bp.sourcePackage.equals("android")) {
12269                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12270                                    + pkg.packageName + " attempting to redeclare permission "
12271                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12272                            res.origPermission = perm.info.name;
12273                            res.origPackage = bp.sourcePackage;
12274                            return;
12275                        } else {
12276                            Slog.w(TAG, "Package " + pkg.packageName
12277                                    + " attempting to redeclare system permission "
12278                                    + perm.info.name + "; ignoring new declaration");
12279                            pkg.permissions.remove(i);
12280                        }
12281                    }
12282                }
12283            }
12284
12285        }
12286
12287        if (systemApp && onExternal) {
12288            // Disable updates to system apps on sdcard
12289            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12290                    "Cannot install updates to system apps on sdcard");
12291            return;
12292        }
12293
12294        if (args.move != null) {
12295            // We did an in-place move, so dex is ready to roll
12296            scanFlags |= SCAN_NO_DEX;
12297            scanFlags |= SCAN_MOVE;
12298
12299            synchronized (mPackages) {
12300                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12301                if (ps == null) {
12302                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12303                            "Missing settings for moved package " + pkgName);
12304                }
12305
12306                // We moved the entire application as-is, so bring over the
12307                // previously derived ABI information.
12308                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12309                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12310            }
12311
12312        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12313            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12314            scanFlags |= SCAN_NO_DEX;
12315
12316            try {
12317                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12318                        true /* extract libs */);
12319            } catch (PackageManagerException pme) {
12320                Slog.e(TAG, "Error deriving application ABI", pme);
12321                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12322                return;
12323            }
12324
12325            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12326            int result = mPackageDexOptimizer
12327                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12328                            false /* defer */, false /* inclDependencies */);
12329            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12330                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12331                return;
12332            }
12333        }
12334
12335        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12336            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12337            return;
12338        }
12339
12340        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12341
12342        if (replace) {
12343            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12344                    installerPackageName, volumeUuid, res);
12345        } else {
12346            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12347                    args.user, installerPackageName, volumeUuid, res);
12348        }
12349        synchronized (mPackages) {
12350            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12351            if (ps != null) {
12352                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12353            }
12354        }
12355    }
12356
12357    private void startIntentFilterVerifications(int userId, boolean replacing,
12358            PackageParser.Package pkg) {
12359        if (mIntentFilterVerifierComponent == null) {
12360            Slog.w(TAG, "No IntentFilter verification will not be done as "
12361                    + "there is no IntentFilterVerifier available!");
12362            return;
12363        }
12364
12365        final int verifierUid = getPackageUid(
12366                mIntentFilterVerifierComponent.getPackageName(),
12367                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12368
12369        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12370        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12371        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12372        mHandler.sendMessage(msg);
12373    }
12374
12375    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12376            PackageParser.Package pkg) {
12377        int size = pkg.activities.size();
12378        if (size == 0) {
12379            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12380                    "No activity, so no need to verify any IntentFilter!");
12381            return;
12382        }
12383
12384        final boolean hasDomainURLs = hasDomainURLs(pkg);
12385        if (!hasDomainURLs) {
12386            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12387                    "No domain URLs, so no need to verify any IntentFilter!");
12388            return;
12389        }
12390
12391        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12392                + " if any IntentFilter from the " + size
12393                + " Activities needs verification ...");
12394
12395        int count = 0;
12396        final String packageName = pkg.packageName;
12397
12398        synchronized (mPackages) {
12399            // If this is a new install and we see that we've already run verification for this
12400            // package, we have nothing to do: it means the state was restored from backup.
12401            if (!replacing) {
12402                IntentFilterVerificationInfo ivi =
12403                        mSettings.getIntentFilterVerificationLPr(packageName);
12404                if (ivi != null) {
12405                    if (DEBUG_DOMAIN_VERIFICATION) {
12406                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12407                                + ivi.getStatusString());
12408                    }
12409                    return;
12410                }
12411            }
12412
12413            // If any filters need to be verified, then all need to be.
12414            boolean needToVerify = false;
12415            for (PackageParser.Activity a : pkg.activities) {
12416                for (ActivityIntentInfo filter : a.intents) {
12417                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12418                        if (DEBUG_DOMAIN_VERIFICATION) {
12419                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12420                        }
12421                        needToVerify = true;
12422                        break;
12423                    }
12424                }
12425            }
12426
12427            if (needToVerify) {
12428                final int verificationId = mIntentFilterVerificationToken++;
12429                for (PackageParser.Activity a : pkg.activities) {
12430                    for (ActivityIntentInfo filter : a.intents) {
12431                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12432                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12433                                    "Verification needed for IntentFilter:" + filter.toString());
12434                            mIntentFilterVerifier.addOneIntentFilterVerification(
12435                                    verifierUid, userId, verificationId, filter, packageName);
12436                            count++;
12437                        }
12438                    }
12439                }
12440            }
12441        }
12442
12443        if (count > 0) {
12444            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12445                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12446                    +  " for userId:" + userId);
12447            mIntentFilterVerifier.startVerifications(userId);
12448        } else {
12449            if (DEBUG_DOMAIN_VERIFICATION) {
12450                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12451            }
12452        }
12453    }
12454
12455    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12456        final ComponentName cn  = filter.activity.getComponentName();
12457        final String packageName = cn.getPackageName();
12458
12459        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12460                packageName);
12461        if (ivi == null) {
12462            return true;
12463        }
12464        int status = ivi.getStatus();
12465        switch (status) {
12466            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12467            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12468                return true;
12469
12470            default:
12471                // Nothing to do
12472                return false;
12473        }
12474    }
12475
12476    private static boolean isMultiArch(PackageSetting ps) {
12477        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12478    }
12479
12480    private static boolean isMultiArch(ApplicationInfo info) {
12481        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12482    }
12483
12484    private static boolean isExternal(PackageParser.Package pkg) {
12485        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12486    }
12487
12488    private static boolean isExternal(PackageSetting ps) {
12489        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12490    }
12491
12492    private static boolean isExternal(ApplicationInfo info) {
12493        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12494    }
12495
12496    private static boolean isSystemApp(PackageParser.Package pkg) {
12497        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12498    }
12499
12500    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12501        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12502    }
12503
12504    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12505        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12506    }
12507
12508    private static boolean isSystemApp(PackageSetting ps) {
12509        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12510    }
12511
12512    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12513        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12514    }
12515
12516    private int packageFlagsToInstallFlags(PackageSetting ps) {
12517        int installFlags = 0;
12518        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12519            // This existing package was an external ASEC install when we have
12520            // the external flag without a UUID
12521            installFlags |= PackageManager.INSTALL_EXTERNAL;
12522        }
12523        if (ps.isForwardLocked()) {
12524            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12525        }
12526        return installFlags;
12527    }
12528
12529    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12530        if (isExternal(pkg)) {
12531            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12532                return mSettings.getExternalVersion();
12533            } else {
12534                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12535            }
12536        } else {
12537            return mSettings.getInternalVersion();
12538        }
12539    }
12540
12541    private void deleteTempPackageFiles() {
12542        final FilenameFilter filter = new FilenameFilter() {
12543            public boolean accept(File dir, String name) {
12544                return name.startsWith("vmdl") && name.endsWith(".tmp");
12545            }
12546        };
12547        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12548            file.delete();
12549        }
12550    }
12551
12552    @Override
12553    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12554            int flags) {
12555        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12556                flags);
12557    }
12558
12559    @Override
12560    public void deletePackage(final String packageName,
12561            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12562        mContext.enforceCallingOrSelfPermission(
12563                android.Manifest.permission.DELETE_PACKAGES, null);
12564        Preconditions.checkNotNull(packageName);
12565        Preconditions.checkNotNull(observer);
12566        final int uid = Binder.getCallingUid();
12567        if (UserHandle.getUserId(uid) != userId) {
12568            mContext.enforceCallingPermission(
12569                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12570                    "deletePackage for user " + userId);
12571        }
12572        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12573            try {
12574                observer.onPackageDeleted(packageName,
12575                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12576            } catch (RemoteException re) {
12577            }
12578            return;
12579        }
12580
12581        boolean uninstallBlocked = false;
12582        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12583            int[] users = sUserManager.getUserIds();
12584            for (int i = 0; i < users.length; ++i) {
12585                if (getBlockUninstallForUser(packageName, users[i])) {
12586                    uninstallBlocked = true;
12587                    break;
12588                }
12589            }
12590        } else {
12591            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12592        }
12593        if (uninstallBlocked) {
12594            try {
12595                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12596                        null);
12597            } catch (RemoteException re) {
12598            }
12599            return;
12600        }
12601
12602        if (DEBUG_REMOVE) {
12603            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12604        }
12605        // Queue up an async operation since the package deletion may take a little while.
12606        mHandler.post(new Runnable() {
12607            public void run() {
12608                mHandler.removeCallbacks(this);
12609                final int returnCode = deletePackageX(packageName, userId, flags);
12610                if (observer != null) {
12611                    try {
12612                        observer.onPackageDeleted(packageName, returnCode, null);
12613                    } catch (RemoteException e) {
12614                        Log.i(TAG, "Observer no longer exists.");
12615                    } //end catch
12616                } //end if
12617            } //end run
12618        });
12619    }
12620
12621    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12622        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12623                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12624        try {
12625            if (dpm != null) {
12626                if (dpm.isDeviceOwner(packageName)) {
12627                    return true;
12628                }
12629                int[] users;
12630                if (userId == UserHandle.USER_ALL) {
12631                    users = sUserManager.getUserIds();
12632                } else {
12633                    users = new int[]{userId};
12634                }
12635                for (int i = 0; i < users.length; ++i) {
12636                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12637                        return true;
12638                    }
12639                }
12640            }
12641        } catch (RemoteException e) {
12642        }
12643        return false;
12644    }
12645
12646    /**
12647     *  This method is an internal method that could be get invoked either
12648     *  to delete an installed package or to clean up a failed installation.
12649     *  After deleting an installed package, a broadcast is sent to notify any
12650     *  listeners that the package has been installed. For cleaning up a failed
12651     *  installation, the broadcast is not necessary since the package's
12652     *  installation wouldn't have sent the initial broadcast either
12653     *  The key steps in deleting a package are
12654     *  deleting the package information in internal structures like mPackages,
12655     *  deleting the packages base directories through installd
12656     *  updating mSettings to reflect current status
12657     *  persisting settings for later use
12658     *  sending a broadcast if necessary
12659     */
12660    private int deletePackageX(String packageName, int userId, int flags) {
12661        final PackageRemovedInfo info = new PackageRemovedInfo();
12662        final boolean res;
12663
12664        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12665                ? UserHandle.ALL : new UserHandle(userId);
12666
12667        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12668            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12669            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12670        }
12671
12672        boolean removedForAllUsers = false;
12673        boolean systemUpdate = false;
12674
12675        // for the uninstall-updates case and restricted profiles, remember the per-
12676        // userhandle installed state
12677        int[] allUsers;
12678        boolean[] perUserInstalled;
12679        synchronized (mPackages) {
12680            PackageSetting ps = mSettings.mPackages.get(packageName);
12681            allUsers = sUserManager.getUserIds();
12682            perUserInstalled = new boolean[allUsers.length];
12683            for (int i = 0; i < allUsers.length; i++) {
12684                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12685            }
12686        }
12687
12688        synchronized (mInstallLock) {
12689            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12690            res = deletePackageLI(packageName, removeForUser,
12691                    true, allUsers, perUserInstalled,
12692                    flags | REMOVE_CHATTY, info, true);
12693            systemUpdate = info.isRemovedPackageSystemUpdate;
12694            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12695                removedForAllUsers = true;
12696            }
12697            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12698                    + " removedForAllUsers=" + removedForAllUsers);
12699        }
12700
12701        if (res) {
12702            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12703
12704            // If the removed package was a system update, the old system package
12705            // was re-enabled; we need to broadcast this information
12706            if (systemUpdate) {
12707                Bundle extras = new Bundle(1);
12708                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12709                        ? info.removedAppId : info.uid);
12710                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12711
12712                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12713                        extras, null, null, null);
12714                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12715                        extras, null, null, null);
12716                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12717                        null, packageName, null, null);
12718            }
12719        }
12720        // Force a gc here.
12721        Runtime.getRuntime().gc();
12722        // Delete the resources here after sending the broadcast to let
12723        // other processes clean up before deleting resources.
12724        if (info.args != null) {
12725            synchronized (mInstallLock) {
12726                info.args.doPostDeleteLI(true);
12727            }
12728        }
12729
12730        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12731    }
12732
12733    class PackageRemovedInfo {
12734        String removedPackage;
12735        int uid = -1;
12736        int removedAppId = -1;
12737        int[] removedUsers = null;
12738        boolean isRemovedPackageSystemUpdate = false;
12739        // Clean up resources deleted packages.
12740        InstallArgs args = null;
12741
12742        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12743            Bundle extras = new Bundle(1);
12744            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12745            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12746            if (replacing) {
12747                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12748            }
12749            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12750            if (removedPackage != null) {
12751                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12752                        extras, null, null, removedUsers);
12753                if (fullRemove && !replacing) {
12754                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12755                            extras, null, null, removedUsers);
12756                }
12757            }
12758            if (removedAppId >= 0) {
12759                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12760                        removedUsers);
12761            }
12762        }
12763    }
12764
12765    /*
12766     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12767     * flag is not set, the data directory is removed as well.
12768     * make sure this flag is set for partially installed apps. If not its meaningless to
12769     * delete a partially installed application.
12770     */
12771    private void removePackageDataLI(PackageSetting ps,
12772            int[] allUserHandles, boolean[] perUserInstalled,
12773            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12774        String packageName = ps.name;
12775        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12776        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12777        // Retrieve object to delete permissions for shared user later on
12778        final PackageSetting deletedPs;
12779        // reader
12780        synchronized (mPackages) {
12781            deletedPs = mSettings.mPackages.get(packageName);
12782            if (outInfo != null) {
12783                outInfo.removedPackage = packageName;
12784                outInfo.removedUsers = deletedPs != null
12785                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12786                        : null;
12787            }
12788        }
12789        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12790            removeDataDirsLI(ps.volumeUuid, packageName);
12791            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12792        }
12793        // writer
12794        synchronized (mPackages) {
12795            if (deletedPs != null) {
12796                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12797                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12798                    clearDefaultBrowserIfNeeded(packageName);
12799                    if (outInfo != null) {
12800                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12801                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12802                    }
12803                    updatePermissionsLPw(deletedPs.name, null, 0);
12804                    if (deletedPs.sharedUser != null) {
12805                        // Remove permissions associated with package. Since runtime
12806                        // permissions are per user we have to kill the removed package
12807                        // or packages running under the shared user of the removed
12808                        // package if revoking the permissions requested only by the removed
12809                        // package is successful and this causes a change in gids.
12810                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12811                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12812                                    userId);
12813                            if (userIdToKill == UserHandle.USER_ALL
12814                                    || userIdToKill >= UserHandle.USER_OWNER) {
12815                                // If gids changed for this user, kill all affected packages.
12816                                mHandler.post(new Runnable() {
12817                                    @Override
12818                                    public void run() {
12819                                        // This has to happen with no lock held.
12820                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12821                                                KILL_APP_REASON_GIDS_CHANGED);
12822                                    }
12823                                });
12824                                break;
12825                            }
12826                        }
12827                    }
12828                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12829                }
12830                // make sure to preserve per-user disabled state if this removal was just
12831                // a downgrade of a system app to the factory package
12832                if (allUserHandles != null && perUserInstalled != null) {
12833                    if (DEBUG_REMOVE) {
12834                        Slog.d(TAG, "Propagating install state across downgrade");
12835                    }
12836                    for (int i = 0; i < allUserHandles.length; i++) {
12837                        if (DEBUG_REMOVE) {
12838                            Slog.d(TAG, "    user " + allUserHandles[i]
12839                                    + " => " + perUserInstalled[i]);
12840                        }
12841                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12842                    }
12843                }
12844            }
12845            // can downgrade to reader
12846            if (writeSettings) {
12847                // Save settings now
12848                mSettings.writeLPr();
12849            }
12850        }
12851        if (outInfo != null) {
12852            // A user ID was deleted here. Go through all users and remove it
12853            // from KeyStore.
12854            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12855        }
12856    }
12857
12858    static boolean locationIsPrivileged(File path) {
12859        try {
12860            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12861                    .getCanonicalPath();
12862            return path.getCanonicalPath().startsWith(privilegedAppDir);
12863        } catch (IOException e) {
12864            Slog.e(TAG, "Unable to access code path " + path);
12865        }
12866        return false;
12867    }
12868
12869    /*
12870     * Tries to delete system package.
12871     */
12872    private boolean deleteSystemPackageLI(PackageSetting newPs,
12873            int[] allUserHandles, boolean[] perUserInstalled,
12874            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12875        final boolean applyUserRestrictions
12876                = (allUserHandles != null) && (perUserInstalled != null);
12877        PackageSetting disabledPs = null;
12878        // Confirm if the system package has been updated
12879        // An updated system app can be deleted. This will also have to restore
12880        // the system pkg from system partition
12881        // reader
12882        synchronized (mPackages) {
12883            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12884        }
12885        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12886                + " disabledPs=" + disabledPs);
12887        if (disabledPs == null) {
12888            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12889            return false;
12890        } else if (DEBUG_REMOVE) {
12891            Slog.d(TAG, "Deleting system pkg from data partition");
12892        }
12893        if (DEBUG_REMOVE) {
12894            if (applyUserRestrictions) {
12895                Slog.d(TAG, "Remembering install states:");
12896                for (int i = 0; i < allUserHandles.length; i++) {
12897                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12898                }
12899            }
12900        }
12901        // Delete the updated package
12902        outInfo.isRemovedPackageSystemUpdate = true;
12903        if (disabledPs.versionCode < newPs.versionCode) {
12904            // Delete data for downgrades
12905            flags &= ~PackageManager.DELETE_KEEP_DATA;
12906        } else {
12907            // Preserve data by setting flag
12908            flags |= PackageManager.DELETE_KEEP_DATA;
12909        }
12910        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12911                allUserHandles, perUserInstalled, outInfo, writeSettings);
12912        if (!ret) {
12913            return false;
12914        }
12915        // writer
12916        synchronized (mPackages) {
12917            // Reinstate the old system package
12918            mSettings.enableSystemPackageLPw(newPs.name);
12919            // Remove any native libraries from the upgraded package.
12920            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12921        }
12922        // Install the system package
12923        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12924        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12925        if (locationIsPrivileged(disabledPs.codePath)) {
12926            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12927        }
12928
12929        final PackageParser.Package newPkg;
12930        try {
12931            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12932        } catch (PackageManagerException e) {
12933            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12934            return false;
12935        }
12936
12937        // writer
12938        synchronized (mPackages) {
12939            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12940
12941            updatePermissionsLPw(newPkg.packageName, newPkg,
12942                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12943
12944            if (applyUserRestrictions) {
12945                if (DEBUG_REMOVE) {
12946                    Slog.d(TAG, "Propagating install state across reinstall");
12947                }
12948                for (int i = 0; i < allUserHandles.length; i++) {
12949                    if (DEBUG_REMOVE) {
12950                        Slog.d(TAG, "    user " + allUserHandles[i]
12951                                + " => " + perUserInstalled[i]);
12952                    }
12953                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12954
12955                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12956                }
12957                // Regardless of writeSettings we need to ensure that this restriction
12958                // state propagation is persisted
12959                mSettings.writeAllUsersPackageRestrictionsLPr();
12960            }
12961            // can downgrade to reader here
12962            if (writeSettings) {
12963                mSettings.writeLPr();
12964            }
12965        }
12966        return true;
12967    }
12968
12969    private boolean deleteInstalledPackageLI(PackageSetting ps,
12970            boolean deleteCodeAndResources, int flags,
12971            int[] allUserHandles, boolean[] perUserInstalled,
12972            PackageRemovedInfo outInfo, boolean writeSettings) {
12973        if (outInfo != null) {
12974            outInfo.uid = ps.appId;
12975        }
12976
12977        // Delete package data from internal structures and also remove data if flag is set
12978        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12979
12980        // Delete application code and resources
12981        if (deleteCodeAndResources && (outInfo != null)) {
12982            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12983                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12984            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12985        }
12986        return true;
12987    }
12988
12989    @Override
12990    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12991            int userId) {
12992        mContext.enforceCallingOrSelfPermission(
12993                android.Manifest.permission.DELETE_PACKAGES, null);
12994        synchronized (mPackages) {
12995            PackageSetting ps = mSettings.mPackages.get(packageName);
12996            if (ps == null) {
12997                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12998                return false;
12999            }
13000            if (!ps.getInstalled(userId)) {
13001                // Can't block uninstall for an app that is not installed or enabled.
13002                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13003                return false;
13004            }
13005            ps.setBlockUninstall(blockUninstall, userId);
13006            mSettings.writePackageRestrictionsLPr(userId);
13007        }
13008        return true;
13009    }
13010
13011    @Override
13012    public boolean getBlockUninstallForUser(String packageName, int userId) {
13013        synchronized (mPackages) {
13014            PackageSetting ps = mSettings.mPackages.get(packageName);
13015            if (ps == null) {
13016                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13017                return false;
13018            }
13019            return ps.getBlockUninstall(userId);
13020        }
13021    }
13022
13023    /*
13024     * This method handles package deletion in general
13025     */
13026    private boolean deletePackageLI(String packageName, UserHandle user,
13027            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13028            int flags, PackageRemovedInfo outInfo,
13029            boolean writeSettings) {
13030        if (packageName == null) {
13031            Slog.w(TAG, "Attempt to delete null packageName.");
13032            return false;
13033        }
13034        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13035        PackageSetting ps;
13036        boolean dataOnly = false;
13037        int removeUser = -1;
13038        int appId = -1;
13039        synchronized (mPackages) {
13040            ps = mSettings.mPackages.get(packageName);
13041            if (ps == null) {
13042                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13043                return false;
13044            }
13045            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13046                    && user.getIdentifier() != UserHandle.USER_ALL) {
13047                // The caller is asking that the package only be deleted for a single
13048                // user.  To do this, we just mark its uninstalled state and delete
13049                // its data.  If this is a system app, we only allow this to happen if
13050                // they have set the special DELETE_SYSTEM_APP which requests different
13051                // semantics than normal for uninstalling system apps.
13052                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13053                ps.setUserState(user.getIdentifier(),
13054                        COMPONENT_ENABLED_STATE_DEFAULT,
13055                        false, //installed
13056                        true,  //stopped
13057                        true,  //notLaunched
13058                        false, //hidden
13059                        null, null, null,
13060                        false, // blockUninstall
13061                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13062                if (!isSystemApp(ps)) {
13063                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13064                        // Other user still have this package installed, so all
13065                        // we need to do is clear this user's data and save that
13066                        // it is uninstalled.
13067                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13068                        removeUser = user.getIdentifier();
13069                        appId = ps.appId;
13070                        scheduleWritePackageRestrictionsLocked(removeUser);
13071                    } else {
13072                        // We need to set it back to 'installed' so the uninstall
13073                        // broadcasts will be sent correctly.
13074                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13075                        ps.setInstalled(true, user.getIdentifier());
13076                    }
13077                } else {
13078                    // This is a system app, so we assume that the
13079                    // other users still have this package installed, so all
13080                    // we need to do is clear this user's data and save that
13081                    // it is uninstalled.
13082                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13083                    removeUser = user.getIdentifier();
13084                    appId = ps.appId;
13085                    scheduleWritePackageRestrictionsLocked(removeUser);
13086                }
13087            }
13088        }
13089
13090        if (removeUser >= 0) {
13091            // From above, we determined that we are deleting this only
13092            // for a single user.  Continue the work here.
13093            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13094            if (outInfo != null) {
13095                outInfo.removedPackage = packageName;
13096                outInfo.removedAppId = appId;
13097                outInfo.removedUsers = new int[] {removeUser};
13098            }
13099            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13100            removeKeystoreDataIfNeeded(removeUser, appId);
13101            schedulePackageCleaning(packageName, removeUser, false);
13102            synchronized (mPackages) {
13103                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13104                    scheduleWritePackageRestrictionsLocked(removeUser);
13105                }
13106                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13107            }
13108            return true;
13109        }
13110
13111        if (dataOnly) {
13112            // Delete application data first
13113            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13114            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13115            return true;
13116        }
13117
13118        boolean ret = false;
13119        if (isSystemApp(ps)) {
13120            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13121            // When an updated system application is deleted we delete the existing resources as well and
13122            // fall back to existing code in system partition
13123            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13124                    flags, outInfo, writeSettings);
13125        } else {
13126            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13127            // Kill application pre-emptively especially for apps on sd.
13128            killApplication(packageName, ps.appId, "uninstall pkg");
13129            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13130                    allUserHandles, perUserInstalled,
13131                    outInfo, writeSettings);
13132        }
13133
13134        return ret;
13135    }
13136
13137    private final class ClearStorageConnection implements ServiceConnection {
13138        IMediaContainerService mContainerService;
13139
13140        @Override
13141        public void onServiceConnected(ComponentName name, IBinder service) {
13142            synchronized (this) {
13143                mContainerService = IMediaContainerService.Stub.asInterface(service);
13144                notifyAll();
13145            }
13146        }
13147
13148        @Override
13149        public void onServiceDisconnected(ComponentName name) {
13150        }
13151    }
13152
13153    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13154        final boolean mounted;
13155        if (Environment.isExternalStorageEmulated()) {
13156            mounted = true;
13157        } else {
13158            final String status = Environment.getExternalStorageState();
13159
13160            mounted = status.equals(Environment.MEDIA_MOUNTED)
13161                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13162        }
13163
13164        if (!mounted) {
13165            return;
13166        }
13167
13168        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13169        int[] users;
13170        if (userId == UserHandle.USER_ALL) {
13171            users = sUserManager.getUserIds();
13172        } else {
13173            users = new int[] { userId };
13174        }
13175        final ClearStorageConnection conn = new ClearStorageConnection();
13176        if (mContext.bindServiceAsUser(
13177                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13178            try {
13179                for (int curUser : users) {
13180                    long timeout = SystemClock.uptimeMillis() + 5000;
13181                    synchronized (conn) {
13182                        long now = SystemClock.uptimeMillis();
13183                        while (conn.mContainerService == null && now < timeout) {
13184                            try {
13185                                conn.wait(timeout - now);
13186                            } catch (InterruptedException e) {
13187                            }
13188                        }
13189                    }
13190                    if (conn.mContainerService == null) {
13191                        return;
13192                    }
13193
13194                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13195                    clearDirectory(conn.mContainerService,
13196                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13197                    if (allData) {
13198                        clearDirectory(conn.mContainerService,
13199                                userEnv.buildExternalStorageAppDataDirs(packageName));
13200                        clearDirectory(conn.mContainerService,
13201                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13202                    }
13203                }
13204            } finally {
13205                mContext.unbindService(conn);
13206            }
13207        }
13208    }
13209
13210    @Override
13211    public void clearApplicationUserData(final String packageName,
13212            final IPackageDataObserver observer, final int userId) {
13213        mContext.enforceCallingOrSelfPermission(
13214                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13215        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13216        // Queue up an async operation since the package deletion may take a little while.
13217        mHandler.post(new Runnable() {
13218            public void run() {
13219                mHandler.removeCallbacks(this);
13220                final boolean succeeded;
13221                synchronized (mInstallLock) {
13222                    succeeded = clearApplicationUserDataLI(packageName, userId);
13223                }
13224                clearExternalStorageDataSync(packageName, userId, true);
13225                if (succeeded) {
13226                    // invoke DeviceStorageMonitor's update method to clear any notifications
13227                    DeviceStorageMonitorInternal
13228                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13229                    if (dsm != null) {
13230                        dsm.checkMemory();
13231                    }
13232                }
13233                if(observer != null) {
13234                    try {
13235                        observer.onRemoveCompleted(packageName, succeeded);
13236                    } catch (RemoteException e) {
13237                        Log.i(TAG, "Observer no longer exists.");
13238                    }
13239                } //end if observer
13240            } //end run
13241        });
13242    }
13243
13244    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13245        if (packageName == null) {
13246            Slog.w(TAG, "Attempt to delete null packageName.");
13247            return false;
13248        }
13249
13250        // Try finding details about the requested package
13251        PackageParser.Package pkg;
13252        synchronized (mPackages) {
13253            pkg = mPackages.get(packageName);
13254            if (pkg == null) {
13255                final PackageSetting ps = mSettings.mPackages.get(packageName);
13256                if (ps != null) {
13257                    pkg = ps.pkg;
13258                }
13259            }
13260
13261            if (pkg == null) {
13262                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13263                return false;
13264            }
13265
13266            PackageSetting ps = (PackageSetting) pkg.mExtras;
13267            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13268        }
13269
13270        // Always delete data directories for package, even if we found no other
13271        // record of app. This helps users recover from UID mismatches without
13272        // resorting to a full data wipe.
13273        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13274        if (retCode < 0) {
13275            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13276            return false;
13277        }
13278
13279        final int appId = pkg.applicationInfo.uid;
13280        removeKeystoreDataIfNeeded(userId, appId);
13281
13282        // Create a native library symlink only if we have native libraries
13283        // and if the native libraries are 32 bit libraries. We do not provide
13284        // this symlink for 64 bit libraries.
13285        if (pkg.applicationInfo.primaryCpuAbi != null &&
13286                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13287            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13288            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13289                    nativeLibPath, userId) < 0) {
13290                Slog.w(TAG, "Failed linking native library dir");
13291                return false;
13292            }
13293        }
13294
13295        return true;
13296    }
13297
13298    /**
13299     * Reverts user permission state changes (permissions and flags) in
13300     * all packages for a given user.
13301     *
13302     * @param userId The device user for which to do a reset.
13303     */
13304    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13305        final int packageCount = mPackages.size();
13306        for (int i = 0; i < packageCount; i++) {
13307            PackageParser.Package pkg = mPackages.valueAt(i);
13308            PackageSetting ps = (PackageSetting) pkg.mExtras;
13309            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13310        }
13311    }
13312
13313    /**
13314     * Reverts user permission state changes (permissions and flags).
13315     *
13316     * @param ps The package for which to reset.
13317     * @param userId The device user for which to do a reset.
13318     */
13319    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13320            final PackageSetting ps, final int userId) {
13321        if (ps.pkg == null) {
13322            return;
13323        }
13324
13325        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13326                | FLAG_PERMISSION_USER_FIXED
13327                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13328
13329        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13330                | FLAG_PERMISSION_POLICY_FIXED;
13331
13332        boolean writeInstallPermissions = false;
13333        boolean writeRuntimePermissions = false;
13334
13335        final int permissionCount = ps.pkg.requestedPermissions.size();
13336        for (int i = 0; i < permissionCount; i++) {
13337            String permission = ps.pkg.requestedPermissions.get(i);
13338
13339            BasePermission bp = mSettings.mPermissions.get(permission);
13340            if (bp == null) {
13341                continue;
13342            }
13343
13344            // If shared user we just reset the state to which only this app contributed.
13345            if (ps.sharedUser != null) {
13346                boolean used = false;
13347                final int packageCount = ps.sharedUser.packages.size();
13348                for (int j = 0; j < packageCount; j++) {
13349                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13350                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13351                            && pkg.pkg.requestedPermissions.contains(permission)) {
13352                        used = true;
13353                        break;
13354                    }
13355                }
13356                if (used) {
13357                    continue;
13358                }
13359            }
13360
13361            PermissionsState permissionsState = ps.getPermissionsState();
13362
13363            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13364
13365            // Always clear the user settable flags.
13366            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13367                    bp.name) != null;
13368            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13369                if (hasInstallState) {
13370                    writeInstallPermissions = true;
13371                } else {
13372                    writeRuntimePermissions = true;
13373                }
13374            }
13375
13376            // Below is only runtime permission handling.
13377            if (!bp.isRuntime()) {
13378                continue;
13379            }
13380
13381            // Never clobber system or policy.
13382            if ((oldFlags & policyOrSystemFlags) != 0) {
13383                continue;
13384            }
13385
13386            // If this permission was granted by default, make sure it is.
13387            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13388                if (permissionsState.grantRuntimePermission(bp, userId)
13389                        != PERMISSION_OPERATION_FAILURE) {
13390                    writeRuntimePermissions = true;
13391                }
13392            } else {
13393                // Otherwise, reset the permission.
13394                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13395                switch (revokeResult) {
13396                    case PERMISSION_OPERATION_SUCCESS: {
13397                        writeRuntimePermissions = true;
13398                    } break;
13399
13400                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13401                        writeRuntimePermissions = true;
13402                        // If gids changed for this user, kill all affected packages.
13403                        mHandler.post(new Runnable() {
13404                            @Override
13405                            public void run() {
13406                                // This has to happen with no lock held.
13407                                killSettingPackagesForUser(ps, userId,
13408                                        KILL_APP_REASON_GIDS_CHANGED);
13409                            }
13410                        });
13411                    } break;
13412                }
13413            }
13414        }
13415
13416        // Synchronously write as we are taking permissions away.
13417        if (writeRuntimePermissions) {
13418            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13419        }
13420
13421        // Synchronously write as we are taking permissions away.
13422        if (writeInstallPermissions) {
13423            mSettings.writeLPr();
13424        }
13425    }
13426
13427    /**
13428     * Remove entries from the keystore daemon. Will only remove it if the
13429     * {@code appId} is valid.
13430     */
13431    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13432        if (appId < 0) {
13433            return;
13434        }
13435
13436        final KeyStore keyStore = KeyStore.getInstance();
13437        if (keyStore != null) {
13438            if (userId == UserHandle.USER_ALL) {
13439                for (final int individual : sUserManager.getUserIds()) {
13440                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13441                }
13442            } else {
13443                keyStore.clearUid(UserHandle.getUid(userId, appId));
13444            }
13445        } else {
13446            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13447        }
13448    }
13449
13450    @Override
13451    public void deleteApplicationCacheFiles(final String packageName,
13452            final IPackageDataObserver observer) {
13453        mContext.enforceCallingOrSelfPermission(
13454                android.Manifest.permission.DELETE_CACHE_FILES, null);
13455        // Queue up an async operation since the package deletion may take a little while.
13456        final int userId = UserHandle.getCallingUserId();
13457        mHandler.post(new Runnable() {
13458            public void run() {
13459                mHandler.removeCallbacks(this);
13460                final boolean succeded;
13461                synchronized (mInstallLock) {
13462                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13463                }
13464                clearExternalStorageDataSync(packageName, userId, false);
13465                if (observer != null) {
13466                    try {
13467                        observer.onRemoveCompleted(packageName, succeded);
13468                    } catch (RemoteException e) {
13469                        Log.i(TAG, "Observer no longer exists.");
13470                    }
13471                } //end if observer
13472            } //end run
13473        });
13474    }
13475
13476    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13477        if (packageName == null) {
13478            Slog.w(TAG, "Attempt to delete null packageName.");
13479            return false;
13480        }
13481        PackageParser.Package p;
13482        synchronized (mPackages) {
13483            p = mPackages.get(packageName);
13484        }
13485        if (p == null) {
13486            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13487            return false;
13488        }
13489        final ApplicationInfo applicationInfo = p.applicationInfo;
13490        if (applicationInfo == null) {
13491            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13492            return false;
13493        }
13494        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13495        if (retCode < 0) {
13496            Slog.w(TAG, "Couldn't remove cache files for package: "
13497                       + packageName + " u" + userId);
13498            return false;
13499        }
13500        return true;
13501    }
13502
13503    @Override
13504    public void getPackageSizeInfo(final String packageName, int userHandle,
13505            final IPackageStatsObserver observer) {
13506        mContext.enforceCallingOrSelfPermission(
13507                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13508        if (packageName == null) {
13509            throw new IllegalArgumentException("Attempt to get size of null packageName");
13510        }
13511
13512        PackageStats stats = new PackageStats(packageName, userHandle);
13513
13514        /*
13515         * Queue up an async operation since the package measurement may take a
13516         * little while.
13517         */
13518        Message msg = mHandler.obtainMessage(INIT_COPY);
13519        msg.obj = new MeasureParams(stats, observer);
13520        mHandler.sendMessage(msg);
13521    }
13522
13523    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13524            PackageStats pStats) {
13525        if (packageName == null) {
13526            Slog.w(TAG, "Attempt to get size of null packageName.");
13527            return false;
13528        }
13529        PackageParser.Package p;
13530        boolean dataOnly = false;
13531        String libDirRoot = null;
13532        String asecPath = null;
13533        PackageSetting ps = null;
13534        synchronized (mPackages) {
13535            p = mPackages.get(packageName);
13536            ps = mSettings.mPackages.get(packageName);
13537            if(p == null) {
13538                dataOnly = true;
13539                if((ps == null) || (ps.pkg == null)) {
13540                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13541                    return false;
13542                }
13543                p = ps.pkg;
13544            }
13545            if (ps != null) {
13546                libDirRoot = ps.legacyNativeLibraryPathString;
13547            }
13548            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13549                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13550                if (secureContainerId != null) {
13551                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13552                }
13553            }
13554        }
13555        String publicSrcDir = null;
13556        if(!dataOnly) {
13557            final ApplicationInfo applicationInfo = p.applicationInfo;
13558            if (applicationInfo == null) {
13559                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13560                return false;
13561            }
13562            if (p.isForwardLocked()) {
13563                publicSrcDir = applicationInfo.getBaseResourcePath();
13564            }
13565        }
13566        // TODO: extend to measure size of split APKs
13567        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13568        // not just the first level.
13569        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13570        // just the primary.
13571        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13572        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13573                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13574        if (res < 0) {
13575            return false;
13576        }
13577
13578        // Fix-up for forward-locked applications in ASEC containers.
13579        if (!isExternal(p)) {
13580            pStats.codeSize += pStats.externalCodeSize;
13581            pStats.externalCodeSize = 0L;
13582        }
13583
13584        return true;
13585    }
13586
13587
13588    @Override
13589    public void addPackageToPreferred(String packageName) {
13590        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13591    }
13592
13593    @Override
13594    public void removePackageFromPreferred(String packageName) {
13595        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13596    }
13597
13598    @Override
13599    public List<PackageInfo> getPreferredPackages(int flags) {
13600        return new ArrayList<PackageInfo>();
13601    }
13602
13603    private int getUidTargetSdkVersionLockedLPr(int uid) {
13604        Object obj = mSettings.getUserIdLPr(uid);
13605        if (obj instanceof SharedUserSetting) {
13606            final SharedUserSetting sus = (SharedUserSetting) obj;
13607            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13608            final Iterator<PackageSetting> it = sus.packages.iterator();
13609            while (it.hasNext()) {
13610                final PackageSetting ps = it.next();
13611                if (ps.pkg != null) {
13612                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13613                    if (v < vers) vers = v;
13614                }
13615            }
13616            return vers;
13617        } else if (obj instanceof PackageSetting) {
13618            final PackageSetting ps = (PackageSetting) obj;
13619            if (ps.pkg != null) {
13620                return ps.pkg.applicationInfo.targetSdkVersion;
13621            }
13622        }
13623        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13624    }
13625
13626    @Override
13627    public void addPreferredActivity(IntentFilter filter, int match,
13628            ComponentName[] set, ComponentName activity, int userId) {
13629        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13630                "Adding preferred");
13631    }
13632
13633    private void addPreferredActivityInternal(IntentFilter filter, int match,
13634            ComponentName[] set, ComponentName activity, boolean always, int userId,
13635            String opname) {
13636        // writer
13637        int callingUid = Binder.getCallingUid();
13638        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13639        if (filter.countActions() == 0) {
13640            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13641            return;
13642        }
13643        synchronized (mPackages) {
13644            if (mContext.checkCallingOrSelfPermission(
13645                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13646                    != PackageManager.PERMISSION_GRANTED) {
13647                if (getUidTargetSdkVersionLockedLPr(callingUid)
13648                        < Build.VERSION_CODES.FROYO) {
13649                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13650                            + callingUid);
13651                    return;
13652                }
13653                mContext.enforceCallingOrSelfPermission(
13654                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13655            }
13656
13657            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13658            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13659                    + userId + ":");
13660            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13661            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13662            scheduleWritePackageRestrictionsLocked(userId);
13663        }
13664    }
13665
13666    @Override
13667    public void replacePreferredActivity(IntentFilter filter, int match,
13668            ComponentName[] set, ComponentName activity, int userId) {
13669        if (filter.countActions() != 1) {
13670            throw new IllegalArgumentException(
13671                    "replacePreferredActivity expects filter to have only 1 action.");
13672        }
13673        if (filter.countDataAuthorities() != 0
13674                || filter.countDataPaths() != 0
13675                || filter.countDataSchemes() > 1
13676                || filter.countDataTypes() != 0) {
13677            throw new IllegalArgumentException(
13678                    "replacePreferredActivity expects filter to have no data authorities, " +
13679                    "paths, or types; and at most one scheme.");
13680        }
13681
13682        final int callingUid = Binder.getCallingUid();
13683        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13684        synchronized (mPackages) {
13685            if (mContext.checkCallingOrSelfPermission(
13686                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13687                    != PackageManager.PERMISSION_GRANTED) {
13688                if (getUidTargetSdkVersionLockedLPr(callingUid)
13689                        < Build.VERSION_CODES.FROYO) {
13690                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13691                            + Binder.getCallingUid());
13692                    return;
13693                }
13694                mContext.enforceCallingOrSelfPermission(
13695                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13696            }
13697
13698            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13699            if (pir != null) {
13700                // Get all of the existing entries that exactly match this filter.
13701                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13702                if (existing != null && existing.size() == 1) {
13703                    PreferredActivity cur = existing.get(0);
13704                    if (DEBUG_PREFERRED) {
13705                        Slog.i(TAG, "Checking replace of preferred:");
13706                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13707                        if (!cur.mPref.mAlways) {
13708                            Slog.i(TAG, "  -- CUR; not mAlways!");
13709                        } else {
13710                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13711                            Slog.i(TAG, "  -- CUR: mSet="
13712                                    + Arrays.toString(cur.mPref.mSetComponents));
13713                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13714                            Slog.i(TAG, "  -- NEW: mMatch="
13715                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13716                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13717                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13718                        }
13719                    }
13720                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13721                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13722                            && cur.mPref.sameSet(set)) {
13723                        // Setting the preferred activity to what it happens to be already
13724                        if (DEBUG_PREFERRED) {
13725                            Slog.i(TAG, "Replacing with same preferred activity "
13726                                    + cur.mPref.mShortComponent + " for user "
13727                                    + userId + ":");
13728                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13729                        }
13730                        return;
13731                    }
13732                }
13733
13734                if (existing != null) {
13735                    if (DEBUG_PREFERRED) {
13736                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13737                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13738                    }
13739                    for (int i = 0; i < existing.size(); i++) {
13740                        PreferredActivity pa = existing.get(i);
13741                        if (DEBUG_PREFERRED) {
13742                            Slog.i(TAG, "Removing existing preferred activity "
13743                                    + pa.mPref.mComponent + ":");
13744                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13745                        }
13746                        pir.removeFilter(pa);
13747                    }
13748                }
13749            }
13750            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13751                    "Replacing preferred");
13752        }
13753    }
13754
13755    @Override
13756    public void clearPackagePreferredActivities(String packageName) {
13757        final int uid = Binder.getCallingUid();
13758        // writer
13759        synchronized (mPackages) {
13760            PackageParser.Package pkg = mPackages.get(packageName);
13761            if (pkg == null || pkg.applicationInfo.uid != uid) {
13762                if (mContext.checkCallingOrSelfPermission(
13763                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13764                        != PackageManager.PERMISSION_GRANTED) {
13765                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13766                            < Build.VERSION_CODES.FROYO) {
13767                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13768                                + Binder.getCallingUid());
13769                        return;
13770                    }
13771                    mContext.enforceCallingOrSelfPermission(
13772                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13773                }
13774            }
13775
13776            int user = UserHandle.getCallingUserId();
13777            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13778                scheduleWritePackageRestrictionsLocked(user);
13779            }
13780        }
13781    }
13782
13783    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13784    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13785        ArrayList<PreferredActivity> removed = null;
13786        boolean changed = false;
13787        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13788            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13789            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13790            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13791                continue;
13792            }
13793            Iterator<PreferredActivity> it = pir.filterIterator();
13794            while (it.hasNext()) {
13795                PreferredActivity pa = it.next();
13796                // Mark entry for removal only if it matches the package name
13797                // and the entry is of type "always".
13798                if (packageName == null ||
13799                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13800                                && pa.mPref.mAlways)) {
13801                    if (removed == null) {
13802                        removed = new ArrayList<PreferredActivity>();
13803                    }
13804                    removed.add(pa);
13805                }
13806            }
13807            if (removed != null) {
13808                for (int j=0; j<removed.size(); j++) {
13809                    PreferredActivity pa = removed.get(j);
13810                    pir.removeFilter(pa);
13811                }
13812                changed = true;
13813            }
13814        }
13815        return changed;
13816    }
13817
13818    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13819    private void clearIntentFilterVerificationsLPw(int userId) {
13820        final int packageCount = mPackages.size();
13821        for (int i = 0; i < packageCount; i++) {
13822            PackageParser.Package pkg = mPackages.valueAt(i);
13823            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13824        }
13825    }
13826
13827    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13828    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13829        if (userId == UserHandle.USER_ALL) {
13830            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13831                    sUserManager.getUserIds())) {
13832                for (int oneUserId : sUserManager.getUserIds()) {
13833                    scheduleWritePackageRestrictionsLocked(oneUserId);
13834                }
13835            }
13836        } else {
13837            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13838                scheduleWritePackageRestrictionsLocked(userId);
13839            }
13840        }
13841    }
13842
13843    void clearDefaultBrowserIfNeeded(String packageName) {
13844        for (int oneUserId : sUserManager.getUserIds()) {
13845            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13846            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13847            if (packageName.equals(defaultBrowserPackageName)) {
13848                setDefaultBrowserPackageName(null, oneUserId);
13849            }
13850        }
13851    }
13852
13853    @Override
13854    public void resetApplicationPreferences(int userId) {
13855        mContext.enforceCallingOrSelfPermission(
13856                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13857        // writer
13858        synchronized (mPackages) {
13859            final long identity = Binder.clearCallingIdentity();
13860            try {
13861                clearPackagePreferredActivitiesLPw(null, userId);
13862                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13863                // TODO: We have to reset the default SMS and Phone. This requires
13864                // significant refactoring to keep all default apps in the package
13865                // manager (cleaner but more work) or have the services provide
13866                // callbacks to the package manager to request a default app reset.
13867                applyFactoryDefaultBrowserLPw(userId);
13868                clearIntentFilterVerificationsLPw(userId);
13869                primeDomainVerificationsLPw(userId);
13870                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13871                scheduleWritePackageRestrictionsLocked(userId);
13872            } finally {
13873                Binder.restoreCallingIdentity(identity);
13874            }
13875        }
13876    }
13877
13878    @Override
13879    public int getPreferredActivities(List<IntentFilter> outFilters,
13880            List<ComponentName> outActivities, String packageName) {
13881
13882        int num = 0;
13883        final int userId = UserHandle.getCallingUserId();
13884        // reader
13885        synchronized (mPackages) {
13886            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13887            if (pir != null) {
13888                final Iterator<PreferredActivity> it = pir.filterIterator();
13889                while (it.hasNext()) {
13890                    final PreferredActivity pa = it.next();
13891                    if (packageName == null
13892                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13893                                    && pa.mPref.mAlways)) {
13894                        if (outFilters != null) {
13895                            outFilters.add(new IntentFilter(pa));
13896                        }
13897                        if (outActivities != null) {
13898                            outActivities.add(pa.mPref.mComponent);
13899                        }
13900                    }
13901                }
13902            }
13903        }
13904
13905        return num;
13906    }
13907
13908    @Override
13909    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13910            int userId) {
13911        int callingUid = Binder.getCallingUid();
13912        if (callingUid != Process.SYSTEM_UID) {
13913            throw new SecurityException(
13914                    "addPersistentPreferredActivity can only be run by the system");
13915        }
13916        if (filter.countActions() == 0) {
13917            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13918            return;
13919        }
13920        synchronized (mPackages) {
13921            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13922                    " :");
13923            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13924            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13925                    new PersistentPreferredActivity(filter, activity));
13926            scheduleWritePackageRestrictionsLocked(userId);
13927        }
13928    }
13929
13930    @Override
13931    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13932        int callingUid = Binder.getCallingUid();
13933        if (callingUid != Process.SYSTEM_UID) {
13934            throw new SecurityException(
13935                    "clearPackagePersistentPreferredActivities can only be run by the system");
13936        }
13937        ArrayList<PersistentPreferredActivity> removed = null;
13938        boolean changed = false;
13939        synchronized (mPackages) {
13940            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13941                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13942                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13943                        .valueAt(i);
13944                if (userId != thisUserId) {
13945                    continue;
13946                }
13947                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13948                while (it.hasNext()) {
13949                    PersistentPreferredActivity ppa = it.next();
13950                    // Mark entry for removal only if it matches the package name.
13951                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13952                        if (removed == null) {
13953                            removed = new ArrayList<PersistentPreferredActivity>();
13954                        }
13955                        removed.add(ppa);
13956                    }
13957                }
13958                if (removed != null) {
13959                    for (int j=0; j<removed.size(); j++) {
13960                        PersistentPreferredActivity ppa = removed.get(j);
13961                        ppir.removeFilter(ppa);
13962                    }
13963                    changed = true;
13964                }
13965            }
13966
13967            if (changed) {
13968                scheduleWritePackageRestrictionsLocked(userId);
13969            }
13970        }
13971    }
13972
13973    /**
13974     * Common machinery for picking apart a restored XML blob and passing
13975     * it to a caller-supplied functor to be applied to the running system.
13976     */
13977    private void restoreFromXml(XmlPullParser parser, int userId,
13978            String expectedStartTag, BlobXmlRestorer functor)
13979            throws IOException, XmlPullParserException {
13980        int type;
13981        while ((type = parser.next()) != XmlPullParser.START_TAG
13982                && type != XmlPullParser.END_DOCUMENT) {
13983        }
13984        if (type != XmlPullParser.START_TAG) {
13985            // oops didn't find a start tag?!
13986            if (DEBUG_BACKUP) {
13987                Slog.e(TAG, "Didn't find start tag during restore");
13988            }
13989            return;
13990        }
13991
13992        // this is supposed to be TAG_PREFERRED_BACKUP
13993        if (!expectedStartTag.equals(parser.getName())) {
13994            if (DEBUG_BACKUP) {
13995                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13996            }
13997            return;
13998        }
13999
14000        // skip interfering stuff, then we're aligned with the backing implementation
14001        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14002        functor.apply(parser, userId);
14003    }
14004
14005    private interface BlobXmlRestorer {
14006        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14007    }
14008
14009    /**
14010     * Non-Binder method, support for the backup/restore mechanism: write the
14011     * full set of preferred activities in its canonical XML format.  Returns the
14012     * XML output as a byte array, or null if there is none.
14013     */
14014    @Override
14015    public byte[] getPreferredActivityBackup(int userId) {
14016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14017            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14018        }
14019
14020        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14021        try {
14022            final XmlSerializer serializer = new FastXmlSerializer();
14023            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14024            serializer.startDocument(null, true);
14025            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14026
14027            synchronized (mPackages) {
14028                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14029            }
14030
14031            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14032            serializer.endDocument();
14033            serializer.flush();
14034        } catch (Exception e) {
14035            if (DEBUG_BACKUP) {
14036                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14037            }
14038            return null;
14039        }
14040
14041        return dataStream.toByteArray();
14042    }
14043
14044    @Override
14045    public void restorePreferredActivities(byte[] backup, int userId) {
14046        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14047            throw new SecurityException("Only the system may call restorePreferredActivities()");
14048        }
14049
14050        try {
14051            final XmlPullParser parser = Xml.newPullParser();
14052            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14053            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14054                    new BlobXmlRestorer() {
14055                        @Override
14056                        public void apply(XmlPullParser parser, int userId)
14057                                throws XmlPullParserException, IOException {
14058                            synchronized (mPackages) {
14059                                mSettings.readPreferredActivitiesLPw(parser, userId);
14060                            }
14061                        }
14062                    } );
14063        } catch (Exception e) {
14064            if (DEBUG_BACKUP) {
14065                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14066            }
14067        }
14068    }
14069
14070    /**
14071     * Non-Binder method, support for the backup/restore mechanism: write the
14072     * default browser (etc) settings in its canonical XML format.  Returns the default
14073     * browser XML representation as a byte array, or null if there is none.
14074     */
14075    @Override
14076    public byte[] getDefaultAppsBackup(int userId) {
14077        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14078            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14079        }
14080
14081        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14082        try {
14083            final XmlSerializer serializer = new FastXmlSerializer();
14084            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14085            serializer.startDocument(null, true);
14086            serializer.startTag(null, TAG_DEFAULT_APPS);
14087
14088            synchronized (mPackages) {
14089                mSettings.writeDefaultAppsLPr(serializer, userId);
14090            }
14091
14092            serializer.endTag(null, TAG_DEFAULT_APPS);
14093            serializer.endDocument();
14094            serializer.flush();
14095        } catch (Exception e) {
14096            if (DEBUG_BACKUP) {
14097                Slog.e(TAG, "Unable to write default apps for backup", e);
14098            }
14099            return null;
14100        }
14101
14102        return dataStream.toByteArray();
14103    }
14104
14105    @Override
14106    public void restoreDefaultApps(byte[] backup, int userId) {
14107        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14108            throw new SecurityException("Only the system may call restoreDefaultApps()");
14109        }
14110
14111        try {
14112            final XmlPullParser parser = Xml.newPullParser();
14113            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14114            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14115                    new BlobXmlRestorer() {
14116                        @Override
14117                        public void apply(XmlPullParser parser, int userId)
14118                                throws XmlPullParserException, IOException {
14119                            synchronized (mPackages) {
14120                                mSettings.readDefaultAppsLPw(parser, userId);
14121                            }
14122                        }
14123                    } );
14124        } catch (Exception e) {
14125            if (DEBUG_BACKUP) {
14126                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14127            }
14128        }
14129    }
14130
14131    @Override
14132    public byte[] getIntentFilterVerificationBackup(int userId) {
14133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14134            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14135        }
14136
14137        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14138        try {
14139            final XmlSerializer serializer = new FastXmlSerializer();
14140            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14141            serializer.startDocument(null, true);
14142            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14143
14144            synchronized (mPackages) {
14145                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14146            }
14147
14148            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14149            serializer.endDocument();
14150            serializer.flush();
14151        } catch (Exception e) {
14152            if (DEBUG_BACKUP) {
14153                Slog.e(TAG, "Unable to write default apps for backup", e);
14154            }
14155            return null;
14156        }
14157
14158        return dataStream.toByteArray();
14159    }
14160
14161    @Override
14162    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14164            throw new SecurityException("Only the system may call restorePreferredActivities()");
14165        }
14166
14167        try {
14168            final XmlPullParser parser = Xml.newPullParser();
14169            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14170            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14171                    new BlobXmlRestorer() {
14172                        @Override
14173                        public void apply(XmlPullParser parser, int userId)
14174                                throws XmlPullParserException, IOException {
14175                            synchronized (mPackages) {
14176                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14177                                mSettings.writeLPr();
14178                            }
14179                        }
14180                    } );
14181        } catch (Exception e) {
14182            if (DEBUG_BACKUP) {
14183                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14184            }
14185        }
14186    }
14187
14188    @Override
14189    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14190            int sourceUserId, int targetUserId, int flags) {
14191        mContext.enforceCallingOrSelfPermission(
14192                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14193        int callingUid = Binder.getCallingUid();
14194        enforceOwnerRights(ownerPackage, callingUid);
14195        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14196        if (intentFilter.countActions() == 0) {
14197            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14198            return;
14199        }
14200        synchronized (mPackages) {
14201            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14202                    ownerPackage, targetUserId, flags);
14203            CrossProfileIntentResolver resolver =
14204                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14205            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14206            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14207            if (existing != null) {
14208                int size = existing.size();
14209                for (int i = 0; i < size; i++) {
14210                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14211                        return;
14212                    }
14213                }
14214            }
14215            resolver.addFilter(newFilter);
14216            scheduleWritePackageRestrictionsLocked(sourceUserId);
14217        }
14218    }
14219
14220    @Override
14221    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14222        mContext.enforceCallingOrSelfPermission(
14223                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14224        int callingUid = Binder.getCallingUid();
14225        enforceOwnerRights(ownerPackage, callingUid);
14226        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14227        synchronized (mPackages) {
14228            CrossProfileIntentResolver resolver =
14229                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14230            ArraySet<CrossProfileIntentFilter> set =
14231                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14232            for (CrossProfileIntentFilter filter : set) {
14233                if (filter.getOwnerPackage().equals(ownerPackage)) {
14234                    resolver.removeFilter(filter);
14235                }
14236            }
14237            scheduleWritePackageRestrictionsLocked(sourceUserId);
14238        }
14239    }
14240
14241    // Enforcing that callingUid is owning pkg on userId
14242    private void enforceOwnerRights(String pkg, int callingUid) {
14243        // The system owns everything.
14244        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14245            return;
14246        }
14247        int callingUserId = UserHandle.getUserId(callingUid);
14248        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14249        if (pi == null) {
14250            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14251                    + callingUserId);
14252        }
14253        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14254            throw new SecurityException("Calling uid " + callingUid
14255                    + " does not own package " + pkg);
14256        }
14257    }
14258
14259    @Override
14260    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14261        Intent intent = new Intent(Intent.ACTION_MAIN);
14262        intent.addCategory(Intent.CATEGORY_HOME);
14263
14264        final int callingUserId = UserHandle.getCallingUserId();
14265        List<ResolveInfo> list = queryIntentActivities(intent, null,
14266                PackageManager.GET_META_DATA, callingUserId);
14267        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14268                true, false, false, callingUserId);
14269
14270        allHomeCandidates.clear();
14271        if (list != null) {
14272            for (ResolveInfo ri : list) {
14273                allHomeCandidates.add(ri);
14274            }
14275        }
14276        return (preferred == null || preferred.activityInfo == null)
14277                ? null
14278                : new ComponentName(preferred.activityInfo.packageName,
14279                        preferred.activityInfo.name);
14280    }
14281
14282    @Override
14283    public void setApplicationEnabledSetting(String appPackageName,
14284            int newState, int flags, int userId, String callingPackage) {
14285        if (!sUserManager.exists(userId)) return;
14286        if (callingPackage == null) {
14287            callingPackage = Integer.toString(Binder.getCallingUid());
14288        }
14289        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14290    }
14291
14292    @Override
14293    public void setComponentEnabledSetting(ComponentName componentName,
14294            int newState, int flags, int userId) {
14295        if (!sUserManager.exists(userId)) return;
14296        setEnabledSetting(componentName.getPackageName(),
14297                componentName.getClassName(), newState, flags, userId, null);
14298    }
14299
14300    private void setEnabledSetting(final String packageName, String className, int newState,
14301            final int flags, int userId, String callingPackage) {
14302        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14303              || newState == COMPONENT_ENABLED_STATE_ENABLED
14304              || newState == COMPONENT_ENABLED_STATE_DISABLED
14305              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14306              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14307            throw new IllegalArgumentException("Invalid new component state: "
14308                    + newState);
14309        }
14310        PackageSetting pkgSetting;
14311        final int uid = Binder.getCallingUid();
14312        final int permission = mContext.checkCallingOrSelfPermission(
14313                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14314        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14315        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14316        boolean sendNow = false;
14317        boolean isApp = (className == null);
14318        String componentName = isApp ? packageName : className;
14319        int packageUid = -1;
14320        ArrayList<String> components;
14321
14322        // writer
14323        synchronized (mPackages) {
14324            pkgSetting = mSettings.mPackages.get(packageName);
14325            if (pkgSetting == null) {
14326                if (className == null) {
14327                    throw new IllegalArgumentException(
14328                            "Unknown package: " + packageName);
14329                }
14330                throw new IllegalArgumentException(
14331                        "Unknown component: " + packageName
14332                        + "/" + className);
14333            }
14334            // Allow root and verify that userId is not being specified by a different user
14335            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14336                throw new SecurityException(
14337                        "Permission Denial: attempt to change component state from pid="
14338                        + Binder.getCallingPid()
14339                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14340            }
14341            if (className == null) {
14342                // We're dealing with an application/package level state change
14343                if (pkgSetting.getEnabled(userId) == newState) {
14344                    // Nothing to do
14345                    return;
14346                }
14347                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14348                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14349                    // Don't care about who enables an app.
14350                    callingPackage = null;
14351                }
14352                pkgSetting.setEnabled(newState, userId, callingPackage);
14353                // pkgSetting.pkg.mSetEnabled = newState;
14354            } else {
14355                // We're dealing with a component level state change
14356                // First, verify that this is a valid class name.
14357                PackageParser.Package pkg = pkgSetting.pkg;
14358                if (pkg == null || !pkg.hasComponentClassName(className)) {
14359                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14360                        throw new IllegalArgumentException("Component class " + className
14361                                + " does not exist in " + packageName);
14362                    } else {
14363                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14364                                + className + " does not exist in " + packageName);
14365                    }
14366                }
14367                switch (newState) {
14368                case COMPONENT_ENABLED_STATE_ENABLED:
14369                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14370                        return;
14371                    }
14372                    break;
14373                case COMPONENT_ENABLED_STATE_DISABLED:
14374                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14375                        return;
14376                    }
14377                    break;
14378                case COMPONENT_ENABLED_STATE_DEFAULT:
14379                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14380                        return;
14381                    }
14382                    break;
14383                default:
14384                    Slog.e(TAG, "Invalid new component state: " + newState);
14385                    return;
14386                }
14387            }
14388            scheduleWritePackageRestrictionsLocked(userId);
14389            components = mPendingBroadcasts.get(userId, packageName);
14390            final boolean newPackage = components == null;
14391            if (newPackage) {
14392                components = new ArrayList<String>();
14393            }
14394            if (!components.contains(componentName)) {
14395                components.add(componentName);
14396            }
14397            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14398                sendNow = true;
14399                // Purge entry from pending broadcast list if another one exists already
14400                // since we are sending one right away.
14401                mPendingBroadcasts.remove(userId, packageName);
14402            } else {
14403                if (newPackage) {
14404                    mPendingBroadcasts.put(userId, packageName, components);
14405                }
14406                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14407                    // Schedule a message
14408                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14409                }
14410            }
14411        }
14412
14413        long callingId = Binder.clearCallingIdentity();
14414        try {
14415            if (sendNow) {
14416                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14417                sendPackageChangedBroadcast(packageName,
14418                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14419            }
14420        } finally {
14421            Binder.restoreCallingIdentity(callingId);
14422        }
14423    }
14424
14425    private void sendPackageChangedBroadcast(String packageName,
14426            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14427        if (DEBUG_INSTALL)
14428            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14429                    + componentNames);
14430        Bundle extras = new Bundle(4);
14431        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14432        String nameList[] = new String[componentNames.size()];
14433        componentNames.toArray(nameList);
14434        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14435        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14436        extras.putInt(Intent.EXTRA_UID, packageUid);
14437        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14438                new int[] {UserHandle.getUserId(packageUid)});
14439    }
14440
14441    @Override
14442    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14443        if (!sUserManager.exists(userId)) return;
14444        final int uid = Binder.getCallingUid();
14445        final int permission = mContext.checkCallingOrSelfPermission(
14446                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14447        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14448        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14449        // writer
14450        synchronized (mPackages) {
14451            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14452                    allowedByPermission, uid, userId)) {
14453                scheduleWritePackageRestrictionsLocked(userId);
14454            }
14455        }
14456    }
14457
14458    @Override
14459    public String getInstallerPackageName(String packageName) {
14460        // reader
14461        synchronized (mPackages) {
14462            return mSettings.getInstallerPackageNameLPr(packageName);
14463        }
14464    }
14465
14466    @Override
14467    public int getApplicationEnabledSetting(String packageName, int userId) {
14468        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14469        int uid = Binder.getCallingUid();
14470        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14471        // reader
14472        synchronized (mPackages) {
14473            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14474        }
14475    }
14476
14477    @Override
14478    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14479        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14480        int uid = Binder.getCallingUid();
14481        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14482        // reader
14483        synchronized (mPackages) {
14484            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14485        }
14486    }
14487
14488    @Override
14489    public void enterSafeMode() {
14490        enforceSystemOrRoot("Only the system can request entering safe mode");
14491
14492        if (!mSystemReady) {
14493            mSafeMode = true;
14494        }
14495    }
14496
14497    @Override
14498    public void systemReady() {
14499        mSystemReady = true;
14500
14501        // Read the compatibilty setting when the system is ready.
14502        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14503                mContext.getContentResolver(),
14504                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14505        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14506        if (DEBUG_SETTINGS) {
14507            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14508        }
14509
14510        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14511
14512        synchronized (mPackages) {
14513            // Verify that all of the preferred activity components actually
14514            // exist.  It is possible for applications to be updated and at
14515            // that point remove a previously declared activity component that
14516            // had been set as a preferred activity.  We try to clean this up
14517            // the next time we encounter that preferred activity, but it is
14518            // possible for the user flow to never be able to return to that
14519            // situation so here we do a sanity check to make sure we haven't
14520            // left any junk around.
14521            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14522            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14523                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14524                removed.clear();
14525                for (PreferredActivity pa : pir.filterSet()) {
14526                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14527                        removed.add(pa);
14528                    }
14529                }
14530                if (removed.size() > 0) {
14531                    for (int r=0; r<removed.size(); r++) {
14532                        PreferredActivity pa = removed.get(r);
14533                        Slog.w(TAG, "Removing dangling preferred activity: "
14534                                + pa.mPref.mComponent);
14535                        pir.removeFilter(pa);
14536                    }
14537                    mSettings.writePackageRestrictionsLPr(
14538                            mSettings.mPreferredActivities.keyAt(i));
14539                }
14540            }
14541
14542            for (int userId : UserManagerService.getInstance().getUserIds()) {
14543                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14544                    grantPermissionsUserIds = ArrayUtils.appendInt(
14545                            grantPermissionsUserIds, userId);
14546                }
14547            }
14548        }
14549        sUserManager.systemReady();
14550
14551        // If we upgraded grant all default permissions before kicking off.
14552        for (int userId : grantPermissionsUserIds) {
14553            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14554        }
14555
14556        // Kick off any messages waiting for system ready
14557        if (mPostSystemReadyMessages != null) {
14558            for (Message msg : mPostSystemReadyMessages) {
14559                msg.sendToTarget();
14560            }
14561            mPostSystemReadyMessages = null;
14562        }
14563
14564        // Watch for external volumes that come and go over time
14565        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14566        storage.registerListener(mStorageListener);
14567
14568        mInstallerService.systemReady();
14569        mPackageDexOptimizer.systemReady();
14570
14571        MountServiceInternal mountServiceInternal = LocalServices.getService(
14572                MountServiceInternal.class);
14573        mountServiceInternal.addExternalStoragePolicy(
14574                new MountServiceInternal.ExternalStorageMountPolicy() {
14575            @Override
14576            public int getMountMode(int uid, String packageName) {
14577                if (Process.isIsolated(uid)) {
14578                    return Zygote.MOUNT_EXTERNAL_NONE;
14579                }
14580                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14581                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14582                }
14583                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14584                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14585                }
14586                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14587                    return Zygote.MOUNT_EXTERNAL_READ;
14588                }
14589                return Zygote.MOUNT_EXTERNAL_WRITE;
14590            }
14591
14592            @Override
14593            public boolean hasExternalStorage(int uid, String packageName) {
14594                return true;
14595            }
14596        });
14597    }
14598
14599    @Override
14600    public boolean isSafeMode() {
14601        return mSafeMode;
14602    }
14603
14604    @Override
14605    public boolean hasSystemUidErrors() {
14606        return mHasSystemUidErrors;
14607    }
14608
14609    static String arrayToString(int[] array) {
14610        StringBuffer buf = new StringBuffer(128);
14611        buf.append('[');
14612        if (array != null) {
14613            for (int i=0; i<array.length; i++) {
14614                if (i > 0) buf.append(", ");
14615                buf.append(array[i]);
14616            }
14617        }
14618        buf.append(']');
14619        return buf.toString();
14620    }
14621
14622    static class DumpState {
14623        public static final int DUMP_LIBS = 1 << 0;
14624        public static final int DUMP_FEATURES = 1 << 1;
14625        public static final int DUMP_RESOLVERS = 1 << 2;
14626        public static final int DUMP_PERMISSIONS = 1 << 3;
14627        public static final int DUMP_PACKAGES = 1 << 4;
14628        public static final int DUMP_SHARED_USERS = 1 << 5;
14629        public static final int DUMP_MESSAGES = 1 << 6;
14630        public static final int DUMP_PROVIDERS = 1 << 7;
14631        public static final int DUMP_VERIFIERS = 1 << 8;
14632        public static final int DUMP_PREFERRED = 1 << 9;
14633        public static final int DUMP_PREFERRED_XML = 1 << 10;
14634        public static final int DUMP_KEYSETS = 1 << 11;
14635        public static final int DUMP_VERSION = 1 << 12;
14636        public static final int DUMP_INSTALLS = 1 << 13;
14637        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14638        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14639
14640        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14641
14642        private int mTypes;
14643
14644        private int mOptions;
14645
14646        private boolean mTitlePrinted;
14647
14648        private SharedUserSetting mSharedUser;
14649
14650        public boolean isDumping(int type) {
14651            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14652                return true;
14653            }
14654
14655            return (mTypes & type) != 0;
14656        }
14657
14658        public void setDump(int type) {
14659            mTypes |= type;
14660        }
14661
14662        public boolean isOptionEnabled(int option) {
14663            return (mOptions & option) != 0;
14664        }
14665
14666        public void setOptionEnabled(int option) {
14667            mOptions |= option;
14668        }
14669
14670        public boolean onTitlePrinted() {
14671            final boolean printed = mTitlePrinted;
14672            mTitlePrinted = true;
14673            return printed;
14674        }
14675
14676        public boolean getTitlePrinted() {
14677            return mTitlePrinted;
14678        }
14679
14680        public void setTitlePrinted(boolean enabled) {
14681            mTitlePrinted = enabled;
14682        }
14683
14684        public SharedUserSetting getSharedUser() {
14685            return mSharedUser;
14686        }
14687
14688        public void setSharedUser(SharedUserSetting user) {
14689            mSharedUser = user;
14690        }
14691    }
14692
14693    @Override
14694    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14695        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14696                != PackageManager.PERMISSION_GRANTED) {
14697            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14698                    + Binder.getCallingPid()
14699                    + ", uid=" + Binder.getCallingUid()
14700                    + " without permission "
14701                    + android.Manifest.permission.DUMP);
14702            return;
14703        }
14704
14705        DumpState dumpState = new DumpState();
14706        boolean fullPreferred = false;
14707        boolean checkin = false;
14708
14709        String packageName = null;
14710        ArraySet<String> permissionNames = null;
14711
14712        int opti = 0;
14713        while (opti < args.length) {
14714            String opt = args[opti];
14715            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14716                break;
14717            }
14718            opti++;
14719
14720            if ("-a".equals(opt)) {
14721                // Right now we only know how to print all.
14722            } else if ("-h".equals(opt)) {
14723                pw.println("Package manager dump options:");
14724                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14725                pw.println("    --checkin: dump for a checkin");
14726                pw.println("    -f: print details of intent filters");
14727                pw.println("    -h: print this help");
14728                pw.println("  cmd may be one of:");
14729                pw.println("    l[ibraries]: list known shared libraries");
14730                pw.println("    f[ibraries]: list device features");
14731                pw.println("    k[eysets]: print known keysets");
14732                pw.println("    r[esolvers]: dump intent resolvers");
14733                pw.println("    perm[issions]: dump permissions");
14734                pw.println("    permission [name ...]: dump declaration and use of given permission");
14735                pw.println("    pref[erred]: print preferred package settings");
14736                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14737                pw.println("    prov[iders]: dump content providers");
14738                pw.println("    p[ackages]: dump installed packages");
14739                pw.println("    s[hared-users]: dump shared user IDs");
14740                pw.println("    m[essages]: print collected runtime messages");
14741                pw.println("    v[erifiers]: print package verifier info");
14742                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14743                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14744                pw.println("    version: print database version info");
14745                pw.println("    write: write current settings now");
14746                pw.println("    installs: details about install sessions");
14747                pw.println("    <package.name>: info about given package");
14748                return;
14749            } else if ("--checkin".equals(opt)) {
14750                checkin = true;
14751            } else if ("-f".equals(opt)) {
14752                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14753            } else {
14754                pw.println("Unknown argument: " + opt + "; use -h for help");
14755            }
14756        }
14757
14758        // Is the caller requesting to dump a particular piece of data?
14759        if (opti < args.length) {
14760            String cmd = args[opti];
14761            opti++;
14762            // Is this a package name?
14763            if ("android".equals(cmd) || cmd.contains(".")) {
14764                packageName = cmd;
14765                // When dumping a single package, we always dump all of its
14766                // filter information since the amount of data will be reasonable.
14767                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14768            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14769                dumpState.setDump(DumpState.DUMP_LIBS);
14770            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14771                dumpState.setDump(DumpState.DUMP_FEATURES);
14772            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14773                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14774            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14775                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14776            } else if ("permission".equals(cmd)) {
14777                if (opti >= args.length) {
14778                    pw.println("Error: permission requires permission name");
14779                    return;
14780                }
14781                permissionNames = new ArraySet<>();
14782                while (opti < args.length) {
14783                    permissionNames.add(args[opti]);
14784                    opti++;
14785                }
14786                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14787                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14788            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14789                dumpState.setDump(DumpState.DUMP_PREFERRED);
14790            } else if ("preferred-xml".equals(cmd)) {
14791                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14792                if (opti < args.length && "--full".equals(args[opti])) {
14793                    fullPreferred = true;
14794                    opti++;
14795                }
14796            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14797                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14798            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14799                dumpState.setDump(DumpState.DUMP_PACKAGES);
14800            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14801                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14802            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14803                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14804            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14805                dumpState.setDump(DumpState.DUMP_MESSAGES);
14806            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14807                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14808            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14809                    || "intent-filter-verifiers".equals(cmd)) {
14810                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14811            } else if ("version".equals(cmd)) {
14812                dumpState.setDump(DumpState.DUMP_VERSION);
14813            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14814                dumpState.setDump(DumpState.DUMP_KEYSETS);
14815            } else if ("installs".equals(cmd)) {
14816                dumpState.setDump(DumpState.DUMP_INSTALLS);
14817            } else if ("write".equals(cmd)) {
14818                synchronized (mPackages) {
14819                    mSettings.writeLPr();
14820                    pw.println("Settings written.");
14821                    return;
14822                }
14823            }
14824        }
14825
14826        if (checkin) {
14827            pw.println("vers,1");
14828        }
14829
14830        // reader
14831        synchronized (mPackages) {
14832            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14833                if (!checkin) {
14834                    if (dumpState.onTitlePrinted())
14835                        pw.println();
14836                    pw.println("Database versions:");
14837                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14838                }
14839            }
14840
14841            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14842                if (!checkin) {
14843                    if (dumpState.onTitlePrinted())
14844                        pw.println();
14845                    pw.println("Verifiers:");
14846                    pw.print("  Required: ");
14847                    pw.print(mRequiredVerifierPackage);
14848                    pw.print(" (uid=");
14849                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14850                    pw.println(")");
14851                } else if (mRequiredVerifierPackage != null) {
14852                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14853                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14854                }
14855            }
14856
14857            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14858                    packageName == null) {
14859                if (mIntentFilterVerifierComponent != null) {
14860                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14861                    if (!checkin) {
14862                        if (dumpState.onTitlePrinted())
14863                            pw.println();
14864                        pw.println("Intent Filter Verifier:");
14865                        pw.print("  Using: ");
14866                        pw.print(verifierPackageName);
14867                        pw.print(" (uid=");
14868                        pw.print(getPackageUid(verifierPackageName, 0));
14869                        pw.println(")");
14870                    } else if (verifierPackageName != null) {
14871                        pw.print("ifv,"); pw.print(verifierPackageName);
14872                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14873                    }
14874                } else {
14875                    pw.println();
14876                    pw.println("No Intent Filter Verifier available!");
14877                }
14878            }
14879
14880            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14881                boolean printedHeader = false;
14882                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14883                while (it.hasNext()) {
14884                    String name = it.next();
14885                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14886                    if (!checkin) {
14887                        if (!printedHeader) {
14888                            if (dumpState.onTitlePrinted())
14889                                pw.println();
14890                            pw.println("Libraries:");
14891                            printedHeader = true;
14892                        }
14893                        pw.print("  ");
14894                    } else {
14895                        pw.print("lib,");
14896                    }
14897                    pw.print(name);
14898                    if (!checkin) {
14899                        pw.print(" -> ");
14900                    }
14901                    if (ent.path != null) {
14902                        if (!checkin) {
14903                            pw.print("(jar) ");
14904                            pw.print(ent.path);
14905                        } else {
14906                            pw.print(",jar,");
14907                            pw.print(ent.path);
14908                        }
14909                    } else {
14910                        if (!checkin) {
14911                            pw.print("(apk) ");
14912                            pw.print(ent.apk);
14913                        } else {
14914                            pw.print(",apk,");
14915                            pw.print(ent.apk);
14916                        }
14917                    }
14918                    pw.println();
14919                }
14920            }
14921
14922            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14923                if (dumpState.onTitlePrinted())
14924                    pw.println();
14925                if (!checkin) {
14926                    pw.println("Features:");
14927                }
14928                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14929                while (it.hasNext()) {
14930                    String name = it.next();
14931                    if (!checkin) {
14932                        pw.print("  ");
14933                    } else {
14934                        pw.print("feat,");
14935                    }
14936                    pw.println(name);
14937                }
14938            }
14939
14940            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14941                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14942                        : "Activity Resolver Table:", "  ", packageName,
14943                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14944                    dumpState.setTitlePrinted(true);
14945                }
14946                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14947                        : "Receiver Resolver Table:", "  ", packageName,
14948                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14949                    dumpState.setTitlePrinted(true);
14950                }
14951                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14952                        : "Service Resolver Table:", "  ", packageName,
14953                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14954                    dumpState.setTitlePrinted(true);
14955                }
14956                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14957                        : "Provider Resolver Table:", "  ", packageName,
14958                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14959                    dumpState.setTitlePrinted(true);
14960                }
14961            }
14962
14963            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14964                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14965                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14966                    int user = mSettings.mPreferredActivities.keyAt(i);
14967                    if (pir.dump(pw,
14968                            dumpState.getTitlePrinted()
14969                                ? "\nPreferred Activities User " + user + ":"
14970                                : "Preferred Activities User " + user + ":", "  ",
14971                            packageName, true, false)) {
14972                        dumpState.setTitlePrinted(true);
14973                    }
14974                }
14975            }
14976
14977            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14978                pw.flush();
14979                FileOutputStream fout = new FileOutputStream(fd);
14980                BufferedOutputStream str = new BufferedOutputStream(fout);
14981                XmlSerializer serializer = new FastXmlSerializer();
14982                try {
14983                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14984                    serializer.startDocument(null, true);
14985                    serializer.setFeature(
14986                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14987                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14988                    serializer.endDocument();
14989                    serializer.flush();
14990                } catch (IllegalArgumentException e) {
14991                    pw.println("Failed writing: " + e);
14992                } catch (IllegalStateException e) {
14993                    pw.println("Failed writing: " + e);
14994                } catch (IOException e) {
14995                    pw.println("Failed writing: " + e);
14996                }
14997            }
14998
14999            if (!checkin
15000                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15001                    && packageName == null) {
15002                pw.println();
15003                int count = mSettings.mPackages.size();
15004                if (count == 0) {
15005                    pw.println("No applications!");
15006                    pw.println();
15007                } else {
15008                    final String prefix = "  ";
15009                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15010                    if (allPackageSettings.size() == 0) {
15011                        pw.println("No domain preferred apps!");
15012                        pw.println();
15013                    } else {
15014                        pw.println("App verification status:");
15015                        pw.println();
15016                        count = 0;
15017                        for (PackageSetting ps : allPackageSettings) {
15018                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15019                            if (ivi == null || ivi.getPackageName() == null) continue;
15020                            pw.println(prefix + "Package: " + ivi.getPackageName());
15021                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15022                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15023                            pw.println();
15024                            count++;
15025                        }
15026                        if (count == 0) {
15027                            pw.println(prefix + "No app verification established.");
15028                            pw.println();
15029                        }
15030                        for (int userId : sUserManager.getUserIds()) {
15031                            pw.println("App linkages for user " + userId + ":");
15032                            pw.println();
15033                            count = 0;
15034                            for (PackageSetting ps : allPackageSettings) {
15035                                final long status = ps.getDomainVerificationStatusForUser(userId);
15036                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15037                                    continue;
15038                                }
15039                                pw.println(prefix + "Package: " + ps.name);
15040                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15041                                String statusStr = IntentFilterVerificationInfo.
15042                                        getStatusStringFromValue(status);
15043                                pw.println(prefix + "Status:  " + statusStr);
15044                                pw.println();
15045                                count++;
15046                            }
15047                            if (count == 0) {
15048                                pw.println(prefix + "No configured app linkages.");
15049                                pw.println();
15050                            }
15051                        }
15052                    }
15053                }
15054            }
15055
15056            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15057                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15058                if (packageName == null && permissionNames == null) {
15059                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15060                        if (iperm == 0) {
15061                            if (dumpState.onTitlePrinted())
15062                                pw.println();
15063                            pw.println("AppOp Permissions:");
15064                        }
15065                        pw.print("  AppOp Permission ");
15066                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15067                        pw.println(":");
15068                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15069                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15070                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15071                        }
15072                    }
15073                }
15074            }
15075
15076            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15077                boolean printedSomething = false;
15078                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15079                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15080                        continue;
15081                    }
15082                    if (!printedSomething) {
15083                        if (dumpState.onTitlePrinted())
15084                            pw.println();
15085                        pw.println("Registered ContentProviders:");
15086                        printedSomething = true;
15087                    }
15088                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15089                    pw.print("    "); pw.println(p.toString());
15090                }
15091                printedSomething = false;
15092                for (Map.Entry<String, PackageParser.Provider> entry :
15093                        mProvidersByAuthority.entrySet()) {
15094                    PackageParser.Provider p = entry.getValue();
15095                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15096                        continue;
15097                    }
15098                    if (!printedSomething) {
15099                        if (dumpState.onTitlePrinted())
15100                            pw.println();
15101                        pw.println("ContentProvider Authorities:");
15102                        printedSomething = true;
15103                    }
15104                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15105                    pw.print("    "); pw.println(p.toString());
15106                    if (p.info != null && p.info.applicationInfo != null) {
15107                        final String appInfo = p.info.applicationInfo.toString();
15108                        pw.print("      applicationInfo="); pw.println(appInfo);
15109                    }
15110                }
15111            }
15112
15113            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15114                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15115            }
15116
15117            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15118                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15119            }
15120
15121            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15122                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15123            }
15124
15125            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15126                // XXX should handle packageName != null by dumping only install data that
15127                // the given package is involved with.
15128                if (dumpState.onTitlePrinted()) pw.println();
15129                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15130            }
15131
15132            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15133                if (dumpState.onTitlePrinted()) pw.println();
15134                mSettings.dumpReadMessagesLPr(pw, dumpState);
15135
15136                pw.println();
15137                pw.println("Package warning messages:");
15138                BufferedReader in = null;
15139                String line = null;
15140                try {
15141                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15142                    while ((line = in.readLine()) != null) {
15143                        if (line.contains("ignored: updated version")) continue;
15144                        pw.println(line);
15145                    }
15146                } catch (IOException ignored) {
15147                } finally {
15148                    IoUtils.closeQuietly(in);
15149                }
15150            }
15151
15152            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15153                BufferedReader in = null;
15154                String line = null;
15155                try {
15156                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15157                    while ((line = in.readLine()) != null) {
15158                        if (line.contains("ignored: updated version")) continue;
15159                        pw.print("msg,");
15160                        pw.println(line);
15161                    }
15162                } catch (IOException ignored) {
15163                } finally {
15164                    IoUtils.closeQuietly(in);
15165                }
15166            }
15167        }
15168    }
15169
15170    private String dumpDomainString(String packageName) {
15171        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15172        List<IntentFilter> filters = getAllIntentFilters(packageName);
15173
15174        ArraySet<String> result = new ArraySet<>();
15175        if (iviList.size() > 0) {
15176            for (IntentFilterVerificationInfo ivi : iviList) {
15177                for (String host : ivi.getDomains()) {
15178                    result.add(host);
15179                }
15180            }
15181        }
15182        if (filters != null && filters.size() > 0) {
15183            for (IntentFilter filter : filters) {
15184                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15185                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15186                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15187                    result.addAll(filter.getHostsList());
15188                }
15189            }
15190        }
15191
15192        StringBuilder sb = new StringBuilder(result.size() * 16);
15193        for (String domain : result) {
15194            if (sb.length() > 0) sb.append(" ");
15195            sb.append(domain);
15196        }
15197        return sb.toString();
15198    }
15199
15200    // ------- apps on sdcard specific code -------
15201    static final boolean DEBUG_SD_INSTALL = false;
15202
15203    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15204
15205    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15206
15207    private boolean mMediaMounted = false;
15208
15209    static String getEncryptKey() {
15210        try {
15211            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15212                    SD_ENCRYPTION_KEYSTORE_NAME);
15213            if (sdEncKey == null) {
15214                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15215                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15216                if (sdEncKey == null) {
15217                    Slog.e(TAG, "Failed to create encryption keys");
15218                    return null;
15219                }
15220            }
15221            return sdEncKey;
15222        } catch (NoSuchAlgorithmException nsae) {
15223            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15224            return null;
15225        } catch (IOException ioe) {
15226            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15227            return null;
15228        }
15229    }
15230
15231    /*
15232     * Update media status on PackageManager.
15233     */
15234    @Override
15235    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15236        int callingUid = Binder.getCallingUid();
15237        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15238            throw new SecurityException("Media status can only be updated by the system");
15239        }
15240        // reader; this apparently protects mMediaMounted, but should probably
15241        // be a different lock in that case.
15242        synchronized (mPackages) {
15243            Log.i(TAG, "Updating external media status from "
15244                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15245                    + (mediaStatus ? "mounted" : "unmounted"));
15246            if (DEBUG_SD_INSTALL)
15247                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15248                        + ", mMediaMounted=" + mMediaMounted);
15249            if (mediaStatus == mMediaMounted) {
15250                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15251                        : 0, -1);
15252                mHandler.sendMessage(msg);
15253                return;
15254            }
15255            mMediaMounted = mediaStatus;
15256        }
15257        // Queue up an async operation since the package installation may take a
15258        // little while.
15259        mHandler.post(new Runnable() {
15260            public void run() {
15261                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15262            }
15263        });
15264    }
15265
15266    /**
15267     * Called by MountService when the initial ASECs to scan are available.
15268     * Should block until all the ASEC containers are finished being scanned.
15269     */
15270    public void scanAvailableAsecs() {
15271        updateExternalMediaStatusInner(true, false, false);
15272        if (mShouldRestoreconData) {
15273            SELinuxMMAC.setRestoreconDone();
15274            mShouldRestoreconData = false;
15275        }
15276    }
15277
15278    /*
15279     * Collect information of applications on external media, map them against
15280     * existing containers and update information based on current mount status.
15281     * Please note that we always have to report status if reportStatus has been
15282     * set to true especially when unloading packages.
15283     */
15284    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15285            boolean externalStorage) {
15286        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15287        int[] uidArr = EmptyArray.INT;
15288
15289        final String[] list = PackageHelper.getSecureContainerList();
15290        if (ArrayUtils.isEmpty(list)) {
15291            Log.i(TAG, "No secure containers found");
15292        } else {
15293            // Process list of secure containers and categorize them
15294            // as active or stale based on their package internal state.
15295
15296            // reader
15297            synchronized (mPackages) {
15298                for (String cid : list) {
15299                    // Leave stages untouched for now; installer service owns them
15300                    if (PackageInstallerService.isStageName(cid)) continue;
15301
15302                    if (DEBUG_SD_INSTALL)
15303                        Log.i(TAG, "Processing container " + cid);
15304                    String pkgName = getAsecPackageName(cid);
15305                    if (pkgName == null) {
15306                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15307                        continue;
15308                    }
15309                    if (DEBUG_SD_INSTALL)
15310                        Log.i(TAG, "Looking for pkg : " + pkgName);
15311
15312                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15313                    if (ps == null) {
15314                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15315                        continue;
15316                    }
15317
15318                    /*
15319                     * Skip packages that are not external if we're unmounting
15320                     * external storage.
15321                     */
15322                    if (externalStorage && !isMounted && !isExternal(ps)) {
15323                        continue;
15324                    }
15325
15326                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15327                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15328                    // The package status is changed only if the code path
15329                    // matches between settings and the container id.
15330                    if (ps.codePathString != null
15331                            && ps.codePathString.startsWith(args.getCodePath())) {
15332                        if (DEBUG_SD_INSTALL) {
15333                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15334                                    + " at code path: " + ps.codePathString);
15335                        }
15336
15337                        // We do have a valid package installed on sdcard
15338                        processCids.put(args, ps.codePathString);
15339                        final int uid = ps.appId;
15340                        if (uid != -1) {
15341                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15342                        }
15343                    } else {
15344                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15345                                + ps.codePathString);
15346                    }
15347                }
15348            }
15349
15350            Arrays.sort(uidArr);
15351        }
15352
15353        // Process packages with valid entries.
15354        if (isMounted) {
15355            if (DEBUG_SD_INSTALL)
15356                Log.i(TAG, "Loading packages");
15357            loadMediaPackages(processCids, uidArr);
15358            startCleaningPackages();
15359            mInstallerService.onSecureContainersAvailable();
15360        } else {
15361            if (DEBUG_SD_INSTALL)
15362                Log.i(TAG, "Unloading packages");
15363            unloadMediaPackages(processCids, uidArr, reportStatus);
15364        }
15365    }
15366
15367    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15368            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15369        final int size = infos.size();
15370        final String[] packageNames = new String[size];
15371        final int[] packageUids = new int[size];
15372        for (int i = 0; i < size; i++) {
15373            final ApplicationInfo info = infos.get(i);
15374            packageNames[i] = info.packageName;
15375            packageUids[i] = info.uid;
15376        }
15377        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15378                finishedReceiver);
15379    }
15380
15381    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15382            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15383        sendResourcesChangedBroadcast(mediaStatus, replacing,
15384                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15385    }
15386
15387    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15388            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15389        int size = pkgList.length;
15390        if (size > 0) {
15391            // Send broadcasts here
15392            Bundle extras = new Bundle();
15393            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15394            if (uidArr != null) {
15395                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15396            }
15397            if (replacing) {
15398                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15399            }
15400            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15401                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15402            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15403        }
15404    }
15405
15406   /*
15407     * Look at potentially valid container ids from processCids If package
15408     * information doesn't match the one on record or package scanning fails,
15409     * the cid is added to list of removeCids. We currently don't delete stale
15410     * containers.
15411     */
15412    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15413        ArrayList<String> pkgList = new ArrayList<String>();
15414        Set<AsecInstallArgs> keys = processCids.keySet();
15415
15416        for (AsecInstallArgs args : keys) {
15417            String codePath = processCids.get(args);
15418            if (DEBUG_SD_INSTALL)
15419                Log.i(TAG, "Loading container : " + args.cid);
15420            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15421            try {
15422                // Make sure there are no container errors first.
15423                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15424                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15425                            + " when installing from sdcard");
15426                    continue;
15427                }
15428                // Check code path here.
15429                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15430                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15431                            + " does not match one in settings " + codePath);
15432                    continue;
15433                }
15434                // Parse package
15435                int parseFlags = mDefParseFlags;
15436                if (args.isExternalAsec()) {
15437                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15438                }
15439                if (args.isFwdLocked()) {
15440                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15441                }
15442
15443                synchronized (mInstallLock) {
15444                    PackageParser.Package pkg = null;
15445                    try {
15446                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15447                    } catch (PackageManagerException e) {
15448                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15449                    }
15450                    // Scan the package
15451                    if (pkg != null) {
15452                        /*
15453                         * TODO why is the lock being held? doPostInstall is
15454                         * called in other places without the lock. This needs
15455                         * to be straightened out.
15456                         */
15457                        // writer
15458                        synchronized (mPackages) {
15459                            retCode = PackageManager.INSTALL_SUCCEEDED;
15460                            pkgList.add(pkg.packageName);
15461                            // Post process args
15462                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15463                                    pkg.applicationInfo.uid);
15464                        }
15465                    } else {
15466                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15467                    }
15468                }
15469
15470            } finally {
15471                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15472                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15473                }
15474            }
15475        }
15476        // writer
15477        synchronized (mPackages) {
15478            // If the platform SDK has changed since the last time we booted,
15479            // we need to re-grant app permission to catch any new ones that
15480            // appear. This is really a hack, and means that apps can in some
15481            // cases get permissions that the user didn't initially explicitly
15482            // allow... it would be nice to have some better way to handle
15483            // this situation.
15484            final VersionInfo ver = mSettings.getExternalVersion();
15485
15486            int updateFlags = UPDATE_PERMISSIONS_ALL;
15487            if (ver.sdkVersion != mSdkVersion) {
15488                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15489                        + mSdkVersion + "; regranting permissions for external");
15490                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15491            }
15492            updatePermissionsLPw(null, null, updateFlags);
15493
15494            // Yay, everything is now upgraded
15495            ver.forceCurrent();
15496
15497            // can downgrade to reader
15498            // Persist settings
15499            mSettings.writeLPr();
15500        }
15501        // Send a broadcast to let everyone know we are done processing
15502        if (pkgList.size() > 0) {
15503            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15504        }
15505    }
15506
15507   /*
15508     * Utility method to unload a list of specified containers
15509     */
15510    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15511        // Just unmount all valid containers.
15512        for (AsecInstallArgs arg : cidArgs) {
15513            synchronized (mInstallLock) {
15514                arg.doPostDeleteLI(false);
15515           }
15516       }
15517   }
15518
15519    /*
15520     * Unload packages mounted on external media. This involves deleting package
15521     * data from internal structures, sending broadcasts about diabled packages,
15522     * gc'ing to free up references, unmounting all secure containers
15523     * corresponding to packages on external media, and posting a
15524     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15525     * that we always have to post this message if status has been requested no
15526     * matter what.
15527     */
15528    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15529            final boolean reportStatus) {
15530        if (DEBUG_SD_INSTALL)
15531            Log.i(TAG, "unloading media packages");
15532        ArrayList<String> pkgList = new ArrayList<String>();
15533        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15534        final Set<AsecInstallArgs> keys = processCids.keySet();
15535        for (AsecInstallArgs args : keys) {
15536            String pkgName = args.getPackageName();
15537            if (DEBUG_SD_INSTALL)
15538                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15539            // Delete package internally
15540            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15541            synchronized (mInstallLock) {
15542                boolean res = deletePackageLI(pkgName, null, false, null, null,
15543                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15544                if (res) {
15545                    pkgList.add(pkgName);
15546                } else {
15547                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15548                    failedList.add(args);
15549                }
15550            }
15551        }
15552
15553        // reader
15554        synchronized (mPackages) {
15555            // We didn't update the settings after removing each package;
15556            // write them now for all packages.
15557            mSettings.writeLPr();
15558        }
15559
15560        // We have to absolutely send UPDATED_MEDIA_STATUS only
15561        // after confirming that all the receivers processed the ordered
15562        // broadcast when packages get disabled, force a gc to clean things up.
15563        // and unload all the containers.
15564        if (pkgList.size() > 0) {
15565            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15566                    new IIntentReceiver.Stub() {
15567                public void performReceive(Intent intent, int resultCode, String data,
15568                        Bundle extras, boolean ordered, boolean sticky,
15569                        int sendingUser) throws RemoteException {
15570                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15571                            reportStatus ? 1 : 0, 1, keys);
15572                    mHandler.sendMessage(msg);
15573                }
15574            });
15575        } else {
15576            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15577                    keys);
15578            mHandler.sendMessage(msg);
15579        }
15580    }
15581
15582    private void loadPrivatePackages(VolumeInfo vol) {
15583        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15584        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15585        synchronized (mInstallLock) {
15586        synchronized (mPackages) {
15587            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15588            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15589            for (PackageSetting ps : packages) {
15590                final PackageParser.Package pkg;
15591                try {
15592                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15593                    loaded.add(pkg.applicationInfo);
15594                } catch (PackageManagerException e) {
15595                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15596                }
15597
15598                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15599                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15600                }
15601            }
15602
15603            int updateFlags = UPDATE_PERMISSIONS_ALL;
15604            if (ver.sdkVersion != mSdkVersion) {
15605                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15606                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15607                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15608            }
15609            updatePermissionsLPw(null, null, updateFlags);
15610
15611            // Yay, everything is now upgraded
15612            ver.forceCurrent();
15613
15614            mSettings.writeLPr();
15615        }
15616        }
15617
15618        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15619        sendResourcesChangedBroadcast(true, false, loaded, null);
15620    }
15621
15622    private void unloadPrivatePackages(VolumeInfo vol) {
15623        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15624        synchronized (mInstallLock) {
15625        synchronized (mPackages) {
15626            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15627            for (PackageSetting ps : packages) {
15628                if (ps.pkg == null) continue;
15629
15630                final ApplicationInfo info = ps.pkg.applicationInfo;
15631                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15632                if (deletePackageLI(ps.name, null, false, null, null,
15633                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15634                    unloaded.add(info);
15635                } else {
15636                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15637                }
15638            }
15639
15640            mSettings.writeLPr();
15641        }
15642        }
15643
15644        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15645        sendResourcesChangedBroadcast(false, false, unloaded, null);
15646    }
15647
15648    /**
15649     * Examine all users present on given mounted volume, and destroy data
15650     * belonging to users that are no longer valid, or whose user ID has been
15651     * recycled.
15652     */
15653    private void reconcileUsers(String volumeUuid) {
15654        final File[] files = FileUtils
15655                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15656        for (File file : files) {
15657            if (!file.isDirectory()) continue;
15658
15659            final int userId;
15660            final UserInfo info;
15661            try {
15662                userId = Integer.parseInt(file.getName());
15663                info = sUserManager.getUserInfo(userId);
15664            } catch (NumberFormatException e) {
15665                Slog.w(TAG, "Invalid user directory " + file);
15666                continue;
15667            }
15668
15669            boolean destroyUser = false;
15670            if (info == null) {
15671                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15672                        + " because no matching user was found");
15673                destroyUser = true;
15674            } else {
15675                try {
15676                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15677                } catch (IOException e) {
15678                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15679                            + " because we failed to enforce serial number: " + e);
15680                    destroyUser = true;
15681                }
15682            }
15683
15684            if (destroyUser) {
15685                synchronized (mInstallLock) {
15686                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15687                }
15688            }
15689        }
15690
15691        final UserManager um = mContext.getSystemService(UserManager.class);
15692        for (UserInfo user : um.getUsers()) {
15693            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15694            if (userDir.exists()) continue;
15695
15696            try {
15697                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15698                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15699            } catch (IOException e) {
15700                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15701            }
15702        }
15703    }
15704
15705    /**
15706     * Examine all apps present on given mounted volume, and destroy apps that
15707     * aren't expected, either due to uninstallation or reinstallation on
15708     * another volume.
15709     */
15710    private void reconcileApps(String volumeUuid) {
15711        final File[] files = FileUtils
15712                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15713        for (File file : files) {
15714            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15715                    && !PackageInstallerService.isStageName(file.getName());
15716            if (!isPackage) {
15717                // Ignore entries which are not packages
15718                continue;
15719            }
15720
15721            boolean destroyApp = false;
15722            String packageName = null;
15723            try {
15724                final PackageLite pkg = PackageParser.parsePackageLite(file,
15725                        PackageParser.PARSE_MUST_BE_APK);
15726                packageName = pkg.packageName;
15727
15728                synchronized (mPackages) {
15729                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15730                    if (ps == null) {
15731                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15732                                + volumeUuid + " because we found no install record");
15733                        destroyApp = true;
15734                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15735                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15736                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15737                        destroyApp = true;
15738                    }
15739                }
15740
15741            } catch (PackageParserException e) {
15742                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15743                destroyApp = true;
15744            }
15745
15746            if (destroyApp) {
15747                synchronized (mInstallLock) {
15748                    if (packageName != null) {
15749                        removeDataDirsLI(volumeUuid, packageName);
15750                    }
15751                    if (file.isDirectory()) {
15752                        mInstaller.rmPackageDir(file.getAbsolutePath());
15753                    } else {
15754                        file.delete();
15755                    }
15756                }
15757            }
15758        }
15759    }
15760
15761    private void unfreezePackage(String packageName) {
15762        synchronized (mPackages) {
15763            final PackageSetting ps = mSettings.mPackages.get(packageName);
15764            if (ps != null) {
15765                ps.frozen = false;
15766            }
15767        }
15768    }
15769
15770    @Override
15771    public int movePackage(final String packageName, final String volumeUuid) {
15772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15773
15774        final int moveId = mNextMoveId.getAndIncrement();
15775        try {
15776            movePackageInternal(packageName, volumeUuid, moveId);
15777        } catch (PackageManagerException e) {
15778            Slog.w(TAG, "Failed to move " + packageName, e);
15779            mMoveCallbacks.notifyStatusChanged(moveId,
15780                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15781        }
15782        return moveId;
15783    }
15784
15785    private void movePackageInternal(final String packageName, final String volumeUuid,
15786            final int moveId) throws PackageManagerException {
15787        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15788        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15789        final PackageManager pm = mContext.getPackageManager();
15790
15791        final boolean currentAsec;
15792        final String currentVolumeUuid;
15793        final File codeFile;
15794        final String installerPackageName;
15795        final String packageAbiOverride;
15796        final int appId;
15797        final String seinfo;
15798        final String label;
15799
15800        // reader
15801        synchronized (mPackages) {
15802            final PackageParser.Package pkg = mPackages.get(packageName);
15803            final PackageSetting ps = mSettings.mPackages.get(packageName);
15804            if (pkg == null || ps == null) {
15805                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15806            }
15807
15808            if (pkg.applicationInfo.isSystemApp()) {
15809                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15810                        "Cannot move system application");
15811            }
15812
15813            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15814                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15815                        "Package already moved to " + volumeUuid);
15816            }
15817
15818            final File probe = new File(pkg.codePath);
15819            final File probeOat = new File(probe, "oat");
15820            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15821                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15822                        "Move only supported for modern cluster style installs");
15823            }
15824
15825            if (ps.frozen) {
15826                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15827                        "Failed to move already frozen package");
15828            }
15829            ps.frozen = true;
15830
15831            currentAsec = pkg.applicationInfo.isForwardLocked()
15832                    || pkg.applicationInfo.isExternalAsec();
15833            currentVolumeUuid = ps.volumeUuid;
15834            codeFile = new File(pkg.codePath);
15835            installerPackageName = ps.installerPackageName;
15836            packageAbiOverride = ps.cpuAbiOverrideString;
15837            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15838            seinfo = pkg.applicationInfo.seinfo;
15839            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15840        }
15841
15842        // Now that we're guarded by frozen state, kill app during move
15843        final long token = Binder.clearCallingIdentity();
15844        try {
15845            killApplication(packageName, appId, "move pkg");
15846        } finally {
15847            Binder.restoreCallingIdentity(token);
15848        }
15849
15850        final Bundle extras = new Bundle();
15851        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15852        extras.putString(Intent.EXTRA_TITLE, label);
15853        mMoveCallbacks.notifyCreated(moveId, extras);
15854
15855        int installFlags;
15856        final boolean moveCompleteApp;
15857        final File measurePath;
15858
15859        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15860            installFlags = INSTALL_INTERNAL;
15861            moveCompleteApp = !currentAsec;
15862            measurePath = Environment.getDataAppDirectory(volumeUuid);
15863        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15864            installFlags = INSTALL_EXTERNAL;
15865            moveCompleteApp = false;
15866            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15867        } else {
15868            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15869            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15870                    || !volume.isMountedWritable()) {
15871                unfreezePackage(packageName);
15872                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15873                        "Move location not mounted private volume");
15874            }
15875
15876            Preconditions.checkState(!currentAsec);
15877
15878            installFlags = INSTALL_INTERNAL;
15879            moveCompleteApp = true;
15880            measurePath = Environment.getDataAppDirectory(volumeUuid);
15881        }
15882
15883        final PackageStats stats = new PackageStats(null, -1);
15884        synchronized (mInstaller) {
15885            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15886                unfreezePackage(packageName);
15887                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15888                        "Failed to measure package size");
15889            }
15890        }
15891
15892        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15893                + stats.dataSize);
15894
15895        final long startFreeBytes = measurePath.getFreeSpace();
15896        final long sizeBytes;
15897        if (moveCompleteApp) {
15898            sizeBytes = stats.codeSize + stats.dataSize;
15899        } else {
15900            sizeBytes = stats.codeSize;
15901        }
15902
15903        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15904            unfreezePackage(packageName);
15905            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15906                    "Not enough free space to move");
15907        }
15908
15909        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15910
15911        final CountDownLatch installedLatch = new CountDownLatch(1);
15912        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15913            @Override
15914            public void onUserActionRequired(Intent intent) throws RemoteException {
15915                throw new IllegalStateException();
15916            }
15917
15918            @Override
15919            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15920                    Bundle extras) throws RemoteException {
15921                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15922                        + PackageManager.installStatusToString(returnCode, msg));
15923
15924                installedLatch.countDown();
15925
15926                // Regardless of success or failure of the move operation,
15927                // always unfreeze the package
15928                unfreezePackage(packageName);
15929
15930                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15931                switch (status) {
15932                    case PackageInstaller.STATUS_SUCCESS:
15933                        mMoveCallbacks.notifyStatusChanged(moveId,
15934                                PackageManager.MOVE_SUCCEEDED);
15935                        break;
15936                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15937                        mMoveCallbacks.notifyStatusChanged(moveId,
15938                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15939                        break;
15940                    default:
15941                        mMoveCallbacks.notifyStatusChanged(moveId,
15942                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15943                        break;
15944                }
15945            }
15946        };
15947
15948        final MoveInfo move;
15949        if (moveCompleteApp) {
15950            // Kick off a thread to report progress estimates
15951            new Thread() {
15952                @Override
15953                public void run() {
15954                    while (true) {
15955                        try {
15956                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15957                                break;
15958                            }
15959                        } catch (InterruptedException ignored) {
15960                        }
15961
15962                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15963                        final int progress = 10 + (int) MathUtils.constrain(
15964                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15965                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15966                    }
15967                }
15968            }.start();
15969
15970            final String dataAppName = codeFile.getName();
15971            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15972                    dataAppName, appId, seinfo);
15973        } else {
15974            move = null;
15975        }
15976
15977        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15978
15979        final Message msg = mHandler.obtainMessage(INIT_COPY);
15980        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15981        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15982                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15983        mHandler.sendMessage(msg);
15984    }
15985
15986    @Override
15987    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15988        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15989
15990        final int realMoveId = mNextMoveId.getAndIncrement();
15991        final Bundle extras = new Bundle();
15992        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15993        mMoveCallbacks.notifyCreated(realMoveId, extras);
15994
15995        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15996            @Override
15997            public void onCreated(int moveId, Bundle extras) {
15998                // Ignored
15999            }
16000
16001            @Override
16002            public void onStatusChanged(int moveId, int status, long estMillis) {
16003                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16004            }
16005        };
16006
16007        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16008        storage.setPrimaryStorageUuid(volumeUuid, callback);
16009        return realMoveId;
16010    }
16011
16012    @Override
16013    public int getMoveStatus(int moveId) {
16014        mContext.enforceCallingOrSelfPermission(
16015                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16016        return mMoveCallbacks.mLastStatus.get(moveId);
16017    }
16018
16019    @Override
16020    public void registerMoveCallback(IPackageMoveObserver callback) {
16021        mContext.enforceCallingOrSelfPermission(
16022                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16023        mMoveCallbacks.register(callback);
16024    }
16025
16026    @Override
16027    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16028        mContext.enforceCallingOrSelfPermission(
16029                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16030        mMoveCallbacks.unregister(callback);
16031    }
16032
16033    @Override
16034    public boolean setInstallLocation(int loc) {
16035        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16036                null);
16037        if (getInstallLocation() == loc) {
16038            return true;
16039        }
16040        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16041                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16042            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16043                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16044            return true;
16045        }
16046        return false;
16047   }
16048
16049    @Override
16050    public int getInstallLocation() {
16051        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16052                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16053                PackageHelper.APP_INSTALL_AUTO);
16054    }
16055
16056    /** Called by UserManagerService */
16057    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16058        mDirtyUsers.remove(userHandle);
16059        mSettings.removeUserLPw(userHandle);
16060        mPendingBroadcasts.remove(userHandle);
16061        if (mInstaller != null) {
16062            // Technically, we shouldn't be doing this with the package lock
16063            // held.  However, this is very rare, and there is already so much
16064            // other disk I/O going on, that we'll let it slide for now.
16065            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16066            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16067                final String volumeUuid = vol.getFsUuid();
16068                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16069                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16070            }
16071        }
16072        mUserNeedsBadging.delete(userHandle);
16073        removeUnusedPackagesLILPw(userManager, userHandle);
16074    }
16075
16076    /**
16077     * We're removing userHandle and would like to remove any downloaded packages
16078     * that are no longer in use by any other user.
16079     * @param userHandle the user being removed
16080     */
16081    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16082        final boolean DEBUG_CLEAN_APKS = false;
16083        int [] users = userManager.getUserIdsLPr();
16084        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16085        while (psit.hasNext()) {
16086            PackageSetting ps = psit.next();
16087            if (ps.pkg == null) {
16088                continue;
16089            }
16090            final String packageName = ps.pkg.packageName;
16091            // Skip over if system app
16092            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16093                continue;
16094            }
16095            if (DEBUG_CLEAN_APKS) {
16096                Slog.i(TAG, "Checking package " + packageName);
16097            }
16098            boolean keep = false;
16099            for (int i = 0; i < users.length; i++) {
16100                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16101                    keep = true;
16102                    if (DEBUG_CLEAN_APKS) {
16103                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16104                                + users[i]);
16105                    }
16106                    break;
16107                }
16108            }
16109            if (!keep) {
16110                if (DEBUG_CLEAN_APKS) {
16111                    Slog.i(TAG, "  Removing package " + packageName);
16112                }
16113                mHandler.post(new Runnable() {
16114                    public void run() {
16115                        deletePackageX(packageName, userHandle, 0);
16116                    } //end run
16117                });
16118            }
16119        }
16120    }
16121
16122    /** Called by UserManagerService */
16123    void createNewUserLILPw(int userHandle) {
16124        if (mInstaller != null) {
16125            mInstaller.createUserConfig(userHandle);
16126            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16127            applyFactoryDefaultBrowserLPw(userHandle);
16128            primeDomainVerificationsLPw(userHandle);
16129        }
16130    }
16131
16132    void newUserCreated(final int userHandle) {
16133        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16134    }
16135
16136    @Override
16137    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16138        mContext.enforceCallingOrSelfPermission(
16139                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16140                "Only package verification agents can read the verifier device identity");
16141
16142        synchronized (mPackages) {
16143            return mSettings.getVerifierDeviceIdentityLPw();
16144        }
16145    }
16146
16147    @Override
16148    public void setPermissionEnforced(String permission, boolean enforced) {
16149        // TODO: Now that we no longer change GID for storage, this should to away.
16150        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16151                "setPermissionEnforced");
16152        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16153            synchronized (mPackages) {
16154                if (mSettings.mReadExternalStorageEnforced == null
16155                        || mSettings.mReadExternalStorageEnforced != enforced) {
16156                    mSettings.mReadExternalStorageEnforced = enforced;
16157                    mSettings.writeLPr();
16158                }
16159            }
16160            // kill any non-foreground processes so we restart them and
16161            // grant/revoke the GID.
16162            final IActivityManager am = ActivityManagerNative.getDefault();
16163            if (am != null) {
16164                final long token = Binder.clearCallingIdentity();
16165                try {
16166                    am.killProcessesBelowForeground("setPermissionEnforcement");
16167                } catch (RemoteException e) {
16168                } finally {
16169                    Binder.restoreCallingIdentity(token);
16170                }
16171            }
16172        } else {
16173            throw new IllegalArgumentException("No selective enforcement for " + permission);
16174        }
16175    }
16176
16177    @Override
16178    @Deprecated
16179    public boolean isPermissionEnforced(String permission) {
16180        return true;
16181    }
16182
16183    @Override
16184    public boolean isStorageLow() {
16185        final long token = Binder.clearCallingIdentity();
16186        try {
16187            final DeviceStorageMonitorInternal
16188                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16189            if (dsm != null) {
16190                return dsm.isMemoryLow();
16191            } else {
16192                return false;
16193            }
16194        } finally {
16195            Binder.restoreCallingIdentity(token);
16196        }
16197    }
16198
16199    @Override
16200    public IPackageInstaller getPackageInstaller() {
16201        return mInstallerService;
16202    }
16203
16204    private boolean userNeedsBadging(int userId) {
16205        int index = mUserNeedsBadging.indexOfKey(userId);
16206        if (index < 0) {
16207            final UserInfo userInfo;
16208            final long token = Binder.clearCallingIdentity();
16209            try {
16210                userInfo = sUserManager.getUserInfo(userId);
16211            } finally {
16212                Binder.restoreCallingIdentity(token);
16213            }
16214            final boolean b;
16215            if (userInfo != null && userInfo.isManagedProfile()) {
16216                b = true;
16217            } else {
16218                b = false;
16219            }
16220            mUserNeedsBadging.put(userId, b);
16221            return b;
16222        }
16223        return mUserNeedsBadging.valueAt(index);
16224    }
16225
16226    @Override
16227    public KeySet getKeySetByAlias(String packageName, String alias) {
16228        if (packageName == null || alias == null) {
16229            return null;
16230        }
16231        synchronized(mPackages) {
16232            final PackageParser.Package pkg = mPackages.get(packageName);
16233            if (pkg == null) {
16234                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16235                throw new IllegalArgumentException("Unknown package: " + packageName);
16236            }
16237            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16238            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16239        }
16240    }
16241
16242    @Override
16243    public KeySet getSigningKeySet(String packageName) {
16244        if (packageName == null) {
16245            return null;
16246        }
16247        synchronized(mPackages) {
16248            final PackageParser.Package pkg = mPackages.get(packageName);
16249            if (pkg == null) {
16250                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16251                throw new IllegalArgumentException("Unknown package: " + packageName);
16252            }
16253            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16254                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16255                throw new SecurityException("May not access signing KeySet of other apps.");
16256            }
16257            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16258            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16259        }
16260    }
16261
16262    @Override
16263    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16264        if (packageName == null || ks == null) {
16265            return false;
16266        }
16267        synchronized(mPackages) {
16268            final PackageParser.Package pkg = mPackages.get(packageName);
16269            if (pkg == null) {
16270                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16271                throw new IllegalArgumentException("Unknown package: " + packageName);
16272            }
16273            IBinder ksh = ks.getToken();
16274            if (ksh instanceof KeySetHandle) {
16275                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16276                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16277            }
16278            return false;
16279        }
16280    }
16281
16282    @Override
16283    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16284        if (packageName == null || ks == null) {
16285            return false;
16286        }
16287        synchronized(mPackages) {
16288            final PackageParser.Package pkg = mPackages.get(packageName);
16289            if (pkg == null) {
16290                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16291                throw new IllegalArgumentException("Unknown package: " + packageName);
16292            }
16293            IBinder ksh = ks.getToken();
16294            if (ksh instanceof KeySetHandle) {
16295                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16296                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16297            }
16298            return false;
16299        }
16300    }
16301
16302    public void getUsageStatsIfNoPackageUsageInfo() {
16303        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16304            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16305            if (usm == null) {
16306                throw new IllegalStateException("UsageStatsManager must be initialized");
16307            }
16308            long now = System.currentTimeMillis();
16309            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16310            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16311                String packageName = entry.getKey();
16312                PackageParser.Package pkg = mPackages.get(packageName);
16313                if (pkg == null) {
16314                    continue;
16315                }
16316                UsageStats usage = entry.getValue();
16317                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16318                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16319            }
16320        }
16321    }
16322
16323    /**
16324     * Check and throw if the given before/after packages would be considered a
16325     * downgrade.
16326     */
16327    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16328            throws PackageManagerException {
16329        if (after.versionCode < before.mVersionCode) {
16330            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16331                    "Update version code " + after.versionCode + " is older than current "
16332                    + before.mVersionCode);
16333        } else if (after.versionCode == before.mVersionCode) {
16334            if (after.baseRevisionCode < before.baseRevisionCode) {
16335                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16336                        "Update base revision code " + after.baseRevisionCode
16337                        + " is older than current " + before.baseRevisionCode);
16338            }
16339
16340            if (!ArrayUtils.isEmpty(after.splitNames)) {
16341                for (int i = 0; i < after.splitNames.length; i++) {
16342                    final String splitName = after.splitNames[i];
16343                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16344                    if (j != -1) {
16345                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16346                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16347                                    "Update split " + splitName + " revision code "
16348                                    + after.splitRevisionCodes[i] + " is older than current "
16349                                    + before.splitRevisionCodes[j]);
16350                        }
16351                    }
16352                }
16353            }
16354        }
16355    }
16356
16357    private static class MoveCallbacks extends Handler {
16358        private static final int MSG_CREATED = 1;
16359        private static final int MSG_STATUS_CHANGED = 2;
16360
16361        private final RemoteCallbackList<IPackageMoveObserver>
16362                mCallbacks = new RemoteCallbackList<>();
16363
16364        private final SparseIntArray mLastStatus = new SparseIntArray();
16365
16366        public MoveCallbacks(Looper looper) {
16367            super(looper);
16368        }
16369
16370        public void register(IPackageMoveObserver callback) {
16371            mCallbacks.register(callback);
16372        }
16373
16374        public void unregister(IPackageMoveObserver callback) {
16375            mCallbacks.unregister(callback);
16376        }
16377
16378        @Override
16379        public void handleMessage(Message msg) {
16380            final SomeArgs args = (SomeArgs) msg.obj;
16381            final int n = mCallbacks.beginBroadcast();
16382            for (int i = 0; i < n; i++) {
16383                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16384                try {
16385                    invokeCallback(callback, msg.what, args);
16386                } catch (RemoteException ignored) {
16387                }
16388            }
16389            mCallbacks.finishBroadcast();
16390            args.recycle();
16391        }
16392
16393        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16394                throws RemoteException {
16395            switch (what) {
16396                case MSG_CREATED: {
16397                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16398                    break;
16399                }
16400                case MSG_STATUS_CHANGED: {
16401                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16402                    break;
16403                }
16404            }
16405        }
16406
16407        private void notifyCreated(int moveId, Bundle extras) {
16408            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16409
16410            final SomeArgs args = SomeArgs.obtain();
16411            args.argi1 = moveId;
16412            args.arg2 = extras;
16413            obtainMessage(MSG_CREATED, args).sendToTarget();
16414        }
16415
16416        private void notifyStatusChanged(int moveId, int status) {
16417            notifyStatusChanged(moveId, status, -1);
16418        }
16419
16420        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16421            Slog.v(TAG, "Move " + moveId + " status " + status);
16422
16423            final SomeArgs args = SomeArgs.obtain();
16424            args.argi1 = moveId;
16425            args.argi2 = status;
16426            args.arg3 = estMillis;
16427            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16428
16429            synchronized (mLastStatus) {
16430                mLastStatus.put(moveId, status);
16431            }
16432        }
16433    }
16434
16435    private final class OnPermissionChangeListeners extends Handler {
16436        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16437
16438        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16439                new RemoteCallbackList<>();
16440
16441        public OnPermissionChangeListeners(Looper looper) {
16442            super(looper);
16443        }
16444
16445        @Override
16446        public void handleMessage(Message msg) {
16447            switch (msg.what) {
16448                case MSG_ON_PERMISSIONS_CHANGED: {
16449                    final int uid = msg.arg1;
16450                    handleOnPermissionsChanged(uid);
16451                } break;
16452            }
16453        }
16454
16455        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16456            mPermissionListeners.register(listener);
16457
16458        }
16459
16460        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16461            mPermissionListeners.unregister(listener);
16462        }
16463
16464        public void onPermissionsChanged(int uid) {
16465            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16466                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16467            }
16468        }
16469
16470        private void handleOnPermissionsChanged(int uid) {
16471            final int count = mPermissionListeners.beginBroadcast();
16472            try {
16473                for (int i = 0; i < count; i++) {
16474                    IOnPermissionsChangeListener callback = mPermissionListeners
16475                            .getBroadcastItem(i);
16476                    try {
16477                        callback.onPermissionsChanged(uid);
16478                    } catch (RemoteException e) {
16479                        Log.e(TAG, "Permission listener is dead", e);
16480                    }
16481                }
16482            } finally {
16483                mPermissionListeners.finishBroadcast();
16484            }
16485        }
16486    }
16487
16488    private class PackageManagerInternalImpl extends PackageManagerInternal {
16489        @Override
16490        public void setLocationPackagesProvider(PackagesProvider provider) {
16491            synchronized (mPackages) {
16492                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16493            }
16494        }
16495
16496        @Override
16497        public void setImePackagesProvider(PackagesProvider provider) {
16498            synchronized (mPackages) {
16499                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16500            }
16501        }
16502
16503        @Override
16504        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16505            synchronized (mPackages) {
16506                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16507            }
16508        }
16509
16510        @Override
16511        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16512            synchronized (mPackages) {
16513                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16514            }
16515        }
16516
16517        @Override
16518        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16519            synchronized (mPackages) {
16520                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16521            }
16522        }
16523
16524        @Override
16525        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16526            synchronized (mPackages) {
16527                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16528            }
16529        }
16530
16531        @Override
16532        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16533            synchronized (mPackages) {
16534                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16535            }
16536        }
16537
16538        @Override
16539        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16540            synchronized (mPackages) {
16541                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16542                        packageName, userId);
16543            }
16544        }
16545
16546        @Override
16547        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16548            synchronized (mPackages) {
16549                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16550                        packageName, userId);
16551            }
16552        }
16553        @Override
16554        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16555            synchronized (mPackages) {
16556                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16557                        packageName, userId);
16558            }
16559        }
16560    }
16561
16562    @Override
16563    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16564        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16565        synchronized (mPackages) {
16566            final long identity = Binder.clearCallingIdentity();
16567            try {
16568                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16569                        packageNames, userId);
16570            } finally {
16571                Binder.restoreCallingIdentity(identity);
16572            }
16573        }
16574    }
16575
16576    private static void enforceSystemOrPhoneCaller(String tag) {
16577        int callingUid = Binder.getCallingUid();
16578        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16579            throw new SecurityException(
16580                    "Cannot call " + tag + " from UID " + callingUid);
16581        }
16582    }
16583}
16584