PackageManagerService.java revision 98a70b9d358d04bff2cdf7d6df99abf235d87027
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                return true;
9603            }
9604        } finally {
9605            Binder.restoreCallingIdentity(callingId);
9606        }
9607        return false;
9608    }
9609
9610    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9611            int userId) {
9612        final PackageRemovedInfo info = new PackageRemovedInfo();
9613        info.removedPackage = packageName;
9614        info.removedUsers = new int[] {userId};
9615        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9616        info.sendBroadcast(false, false, false);
9617    }
9618
9619    /**
9620     * Returns true if application is not found or there was an error. Otherwise it returns
9621     * the hidden state of the package for the given user.
9622     */
9623    @Override
9624    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9625        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9626        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9627                false, "getApplicationHidden for user " + userId);
9628        PackageSetting pkgSetting;
9629        long callingId = Binder.clearCallingIdentity();
9630        try {
9631            // writer
9632            synchronized (mPackages) {
9633                pkgSetting = mSettings.mPackages.get(packageName);
9634                if (pkgSetting == null) {
9635                    return true;
9636                }
9637                return pkgSetting.getHidden(userId);
9638            }
9639        } finally {
9640            Binder.restoreCallingIdentity(callingId);
9641        }
9642    }
9643
9644    /**
9645     * @hide
9646     */
9647    @Override
9648    public int installExistingPackageAsUser(String packageName, int userId) {
9649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9650                null);
9651        PackageSetting pkgSetting;
9652        final int uid = Binder.getCallingUid();
9653        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9654                + userId);
9655        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9656            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9657        }
9658
9659        long callingId = Binder.clearCallingIdentity();
9660        try {
9661            boolean sendAdded = false;
9662
9663            // writer
9664            synchronized (mPackages) {
9665                pkgSetting = mSettings.mPackages.get(packageName);
9666                if (pkgSetting == null) {
9667                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9668                }
9669                if (!pkgSetting.getInstalled(userId)) {
9670                    pkgSetting.setInstalled(true, userId);
9671                    pkgSetting.setHidden(false, userId);
9672                    mSettings.writePackageRestrictionsLPr(userId);
9673                    sendAdded = true;
9674                }
9675            }
9676
9677            if (sendAdded) {
9678                sendPackageAddedForUser(packageName, pkgSetting, userId);
9679            }
9680        } finally {
9681            Binder.restoreCallingIdentity(callingId);
9682        }
9683
9684        return PackageManager.INSTALL_SUCCEEDED;
9685    }
9686
9687    boolean isUserRestricted(int userId, String restrictionKey) {
9688        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9689        if (restrictions.getBoolean(restrictionKey, false)) {
9690            Log.w(TAG, "User is restricted: " + restrictionKey);
9691            return true;
9692        }
9693        return false;
9694    }
9695
9696    @Override
9697    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9698        mContext.enforceCallingOrSelfPermission(
9699                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9700                "Only package verification agents can verify applications");
9701
9702        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9703        final PackageVerificationResponse response = new PackageVerificationResponse(
9704                verificationCode, Binder.getCallingUid());
9705        msg.arg1 = id;
9706        msg.obj = response;
9707        mHandler.sendMessage(msg);
9708    }
9709
9710    @Override
9711    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9712            long millisecondsToDelay) {
9713        mContext.enforceCallingOrSelfPermission(
9714                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9715                "Only package verification agents can extend verification timeouts");
9716
9717        final PackageVerificationState state = mPendingVerification.get(id);
9718        final PackageVerificationResponse response = new PackageVerificationResponse(
9719                verificationCodeAtTimeout, Binder.getCallingUid());
9720
9721        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9722            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9723        }
9724        if (millisecondsToDelay < 0) {
9725            millisecondsToDelay = 0;
9726        }
9727        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9728                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9729            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9730        }
9731
9732        if ((state != null) && !state.timeoutExtended()) {
9733            state.extendTimeout();
9734
9735            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9736            msg.arg1 = id;
9737            msg.obj = response;
9738            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9739        }
9740    }
9741
9742    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9743            int verificationCode, UserHandle user) {
9744        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9745        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9746        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9747        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9748        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9749
9750        mContext.sendBroadcastAsUser(intent, user,
9751                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9752    }
9753
9754    private ComponentName matchComponentForVerifier(String packageName,
9755            List<ResolveInfo> receivers) {
9756        ActivityInfo targetReceiver = null;
9757
9758        final int NR = receivers.size();
9759        for (int i = 0; i < NR; i++) {
9760            final ResolveInfo info = receivers.get(i);
9761            if (info.activityInfo == null) {
9762                continue;
9763            }
9764
9765            if (packageName.equals(info.activityInfo.packageName)) {
9766                targetReceiver = info.activityInfo;
9767                break;
9768            }
9769        }
9770
9771        if (targetReceiver == null) {
9772            return null;
9773        }
9774
9775        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9776    }
9777
9778    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9779            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9780        if (pkgInfo.verifiers.length == 0) {
9781            return null;
9782        }
9783
9784        final int N = pkgInfo.verifiers.length;
9785        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9786        for (int i = 0; i < N; i++) {
9787            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9788
9789            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9790                    receivers);
9791            if (comp == null) {
9792                continue;
9793            }
9794
9795            final int verifierUid = getUidForVerifier(verifierInfo);
9796            if (verifierUid == -1) {
9797                continue;
9798            }
9799
9800            if (DEBUG_VERIFY) {
9801                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9802                        + " with the correct signature");
9803            }
9804            sufficientVerifiers.add(comp);
9805            verificationState.addSufficientVerifier(verifierUid);
9806        }
9807
9808        return sufficientVerifiers;
9809    }
9810
9811    private int getUidForVerifier(VerifierInfo verifierInfo) {
9812        synchronized (mPackages) {
9813            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9814            if (pkg == null) {
9815                return -1;
9816            } else if (pkg.mSignatures.length != 1) {
9817                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9818                        + " has more than one signature; ignoring");
9819                return -1;
9820            }
9821
9822            /*
9823             * If the public key of the package's signature does not match
9824             * our expected public key, then this is a different package and
9825             * we should skip.
9826             */
9827
9828            final byte[] expectedPublicKey;
9829            try {
9830                final Signature verifierSig = pkg.mSignatures[0];
9831                final PublicKey publicKey = verifierSig.getPublicKey();
9832                expectedPublicKey = publicKey.getEncoded();
9833            } catch (CertificateException e) {
9834                return -1;
9835            }
9836
9837            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9838
9839            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9840                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9841                        + " does not have the expected public key; ignoring");
9842                return -1;
9843            }
9844
9845            return pkg.applicationInfo.uid;
9846        }
9847    }
9848
9849    @Override
9850    public void finishPackageInstall(int token) {
9851        enforceSystemOrRoot("Only the system is allowed to finish installs");
9852
9853        if (DEBUG_INSTALL) {
9854            Slog.v(TAG, "BM finishing package install for " + token);
9855        }
9856
9857        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9858        mHandler.sendMessage(msg);
9859    }
9860
9861    /**
9862     * Get the verification agent timeout.
9863     *
9864     * @return verification timeout in milliseconds
9865     */
9866    private long getVerificationTimeout() {
9867        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9868                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9869                DEFAULT_VERIFICATION_TIMEOUT);
9870    }
9871
9872    /**
9873     * Get the default verification agent response code.
9874     *
9875     * @return default verification response code
9876     */
9877    private int getDefaultVerificationResponse() {
9878        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9879                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9880                DEFAULT_VERIFICATION_RESPONSE);
9881    }
9882
9883    /**
9884     * Check whether or not package verification has been enabled.
9885     *
9886     * @return true if verification should be performed
9887     */
9888    private boolean isVerificationEnabled(int userId, int installFlags) {
9889        if (!DEFAULT_VERIFY_ENABLE) {
9890            return false;
9891        }
9892
9893        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9894
9895        // Check if installing from ADB
9896        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9897            // Do not run verification in a test harness environment
9898            if (ActivityManager.isRunningInTestHarness()) {
9899                return false;
9900            }
9901            if (ensureVerifyAppsEnabled) {
9902                return true;
9903            }
9904            // Check if the developer does not want package verification for ADB installs
9905            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9906                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9907                return false;
9908            }
9909        }
9910
9911        if (ensureVerifyAppsEnabled) {
9912            return true;
9913        }
9914
9915        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9916                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9917    }
9918
9919    @Override
9920    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9921            throws RemoteException {
9922        mContext.enforceCallingOrSelfPermission(
9923                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9924                "Only intentfilter verification agents can verify applications");
9925
9926        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9927        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9928                Binder.getCallingUid(), verificationCode, failedDomains);
9929        msg.arg1 = id;
9930        msg.obj = response;
9931        mHandler.sendMessage(msg);
9932    }
9933
9934    @Override
9935    public int getIntentVerificationStatus(String packageName, int userId) {
9936        synchronized (mPackages) {
9937            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9938        }
9939    }
9940
9941    @Override
9942    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9943        mContext.enforceCallingOrSelfPermission(
9944                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9945
9946        boolean result = false;
9947        synchronized (mPackages) {
9948            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9949        }
9950        if (result) {
9951            scheduleWritePackageRestrictionsLocked(userId);
9952        }
9953        return result;
9954    }
9955
9956    @Override
9957    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9958        synchronized (mPackages) {
9959            return mSettings.getIntentFilterVerificationsLPr(packageName);
9960        }
9961    }
9962
9963    @Override
9964    public List<IntentFilter> getAllIntentFilters(String packageName) {
9965        if (TextUtils.isEmpty(packageName)) {
9966            return Collections.<IntentFilter>emptyList();
9967        }
9968        synchronized (mPackages) {
9969            PackageParser.Package pkg = mPackages.get(packageName);
9970            if (pkg == null || pkg.activities == null) {
9971                return Collections.<IntentFilter>emptyList();
9972            }
9973            final int count = pkg.activities.size();
9974            ArrayList<IntentFilter> result = new ArrayList<>();
9975            for (int n=0; n<count; n++) {
9976                PackageParser.Activity activity = pkg.activities.get(n);
9977                if (activity.intents != null || activity.intents.size() > 0) {
9978                    result.addAll(activity.intents);
9979                }
9980            }
9981            return result;
9982        }
9983    }
9984
9985    @Override
9986    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9987        mContext.enforceCallingOrSelfPermission(
9988                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9989
9990        synchronized (mPackages) {
9991            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9992            if (packageName != null) {
9993                result |= updateIntentVerificationStatus(packageName,
9994                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9995                        userId);
9996                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9997                        packageName, userId);
9998            }
9999            return result;
10000        }
10001    }
10002
10003    @Override
10004    public String getDefaultBrowserPackageName(int userId) {
10005        synchronized (mPackages) {
10006            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10007        }
10008    }
10009
10010    /**
10011     * Get the "allow unknown sources" setting.
10012     *
10013     * @return the current "allow unknown sources" setting
10014     */
10015    private int getUnknownSourcesSettings() {
10016        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10017                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10018                -1);
10019    }
10020
10021    @Override
10022    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10023        final int uid = Binder.getCallingUid();
10024        // writer
10025        synchronized (mPackages) {
10026            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10027            if (targetPackageSetting == null) {
10028                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10029            }
10030
10031            PackageSetting installerPackageSetting;
10032            if (installerPackageName != null) {
10033                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10034                if (installerPackageSetting == null) {
10035                    throw new IllegalArgumentException("Unknown installer package: "
10036                            + installerPackageName);
10037                }
10038            } else {
10039                installerPackageSetting = null;
10040            }
10041
10042            Signature[] callerSignature;
10043            Object obj = mSettings.getUserIdLPr(uid);
10044            if (obj != null) {
10045                if (obj instanceof SharedUserSetting) {
10046                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10047                } else if (obj instanceof PackageSetting) {
10048                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10049                } else {
10050                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10051                }
10052            } else {
10053                throw new SecurityException("Unknown calling uid " + uid);
10054            }
10055
10056            // Verify: can't set installerPackageName to a package that is
10057            // not signed with the same cert as the caller.
10058            if (installerPackageSetting != null) {
10059                if (compareSignatures(callerSignature,
10060                        installerPackageSetting.signatures.mSignatures)
10061                        != PackageManager.SIGNATURE_MATCH) {
10062                    throw new SecurityException(
10063                            "Caller does not have same cert as new installer package "
10064                            + installerPackageName);
10065                }
10066            }
10067
10068            // Verify: if target already has an installer package, it must
10069            // be signed with the same cert as the caller.
10070            if (targetPackageSetting.installerPackageName != null) {
10071                PackageSetting setting = mSettings.mPackages.get(
10072                        targetPackageSetting.installerPackageName);
10073                // If the currently set package isn't valid, then it's always
10074                // okay to change it.
10075                if (setting != null) {
10076                    if (compareSignatures(callerSignature,
10077                            setting.signatures.mSignatures)
10078                            != PackageManager.SIGNATURE_MATCH) {
10079                        throw new SecurityException(
10080                                "Caller does not have same cert as old installer package "
10081                                + targetPackageSetting.installerPackageName);
10082                    }
10083                }
10084            }
10085
10086            // Okay!
10087            targetPackageSetting.installerPackageName = installerPackageName;
10088            scheduleWriteSettingsLocked();
10089        }
10090    }
10091
10092    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10093        // Queue up an async operation since the package installation may take a little while.
10094        mHandler.post(new Runnable() {
10095            public void run() {
10096                mHandler.removeCallbacks(this);
10097                 // Result object to be returned
10098                PackageInstalledInfo res = new PackageInstalledInfo();
10099                res.returnCode = currentStatus;
10100                res.uid = -1;
10101                res.pkg = null;
10102                res.removedInfo = new PackageRemovedInfo();
10103                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10104                    args.doPreInstall(res.returnCode);
10105                    synchronized (mInstallLock) {
10106                        installPackageLI(args, res);
10107                    }
10108                    args.doPostInstall(res.returnCode, res.uid);
10109                }
10110
10111                // A restore should be performed at this point if (a) the install
10112                // succeeded, (b) the operation is not an update, and (c) the new
10113                // package has not opted out of backup participation.
10114                final boolean update = res.removedInfo.removedPackage != null;
10115                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10116                boolean doRestore = !update
10117                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10118
10119                // Set up the post-install work request bookkeeping.  This will be used
10120                // and cleaned up by the post-install event handling regardless of whether
10121                // there's a restore pass performed.  Token values are >= 1.
10122                int token;
10123                if (mNextInstallToken < 0) mNextInstallToken = 1;
10124                token = mNextInstallToken++;
10125
10126                PostInstallData data = new PostInstallData(args, res);
10127                mRunningInstalls.put(token, data);
10128                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10129
10130                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10131                    // Pass responsibility to the Backup Manager.  It will perform a
10132                    // restore if appropriate, then pass responsibility back to the
10133                    // Package Manager to run the post-install observer callbacks
10134                    // and broadcasts.
10135                    IBackupManager bm = IBackupManager.Stub.asInterface(
10136                            ServiceManager.getService(Context.BACKUP_SERVICE));
10137                    if (bm != null) {
10138                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10139                                + " to BM for possible restore");
10140                        try {
10141                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10142                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10143                            } else {
10144                                doRestore = false;
10145                            }
10146                        } catch (RemoteException e) {
10147                            // can't happen; the backup manager is local
10148                        } catch (Exception e) {
10149                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10150                            doRestore = false;
10151                        }
10152                    } else {
10153                        Slog.e(TAG, "Backup Manager not found!");
10154                        doRestore = false;
10155                    }
10156                }
10157
10158                if (!doRestore) {
10159                    // No restore possible, or the Backup Manager was mysteriously not
10160                    // available -- just fire the post-install work request directly.
10161                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10162                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10163                    mHandler.sendMessage(msg);
10164                }
10165            }
10166        });
10167    }
10168
10169    private abstract class HandlerParams {
10170        private static final int MAX_RETRIES = 4;
10171
10172        /**
10173         * Number of times startCopy() has been attempted and had a non-fatal
10174         * error.
10175         */
10176        private int mRetries = 0;
10177
10178        /** User handle for the user requesting the information or installation. */
10179        private final UserHandle mUser;
10180
10181        HandlerParams(UserHandle user) {
10182            mUser = user;
10183        }
10184
10185        UserHandle getUser() {
10186            return mUser;
10187        }
10188
10189        final boolean startCopy() {
10190            boolean res;
10191            try {
10192                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10193
10194                if (++mRetries > MAX_RETRIES) {
10195                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10196                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10197                    handleServiceError();
10198                    return false;
10199                } else {
10200                    handleStartCopy();
10201                    res = true;
10202                }
10203            } catch (RemoteException e) {
10204                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10205                mHandler.sendEmptyMessage(MCS_RECONNECT);
10206                res = false;
10207            }
10208            handleReturnCode();
10209            return res;
10210        }
10211
10212        final void serviceError() {
10213            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10214            handleServiceError();
10215            handleReturnCode();
10216        }
10217
10218        abstract void handleStartCopy() throws RemoteException;
10219        abstract void handleServiceError();
10220        abstract void handleReturnCode();
10221    }
10222
10223    class MeasureParams extends HandlerParams {
10224        private final PackageStats mStats;
10225        private boolean mSuccess;
10226
10227        private final IPackageStatsObserver mObserver;
10228
10229        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10230            super(new UserHandle(stats.userHandle));
10231            mObserver = observer;
10232            mStats = stats;
10233        }
10234
10235        @Override
10236        public String toString() {
10237            return "MeasureParams{"
10238                + Integer.toHexString(System.identityHashCode(this))
10239                + " " + mStats.packageName + "}";
10240        }
10241
10242        @Override
10243        void handleStartCopy() throws RemoteException {
10244            synchronized (mInstallLock) {
10245                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10246            }
10247
10248            if (mSuccess) {
10249                final boolean mounted;
10250                if (Environment.isExternalStorageEmulated()) {
10251                    mounted = true;
10252                } else {
10253                    final String status = Environment.getExternalStorageState();
10254                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10255                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10256                }
10257
10258                if (mounted) {
10259                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10260
10261                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10262                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10263
10264                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10265                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10266
10267                    // Always subtract cache size, since it's a subdirectory
10268                    mStats.externalDataSize -= mStats.externalCacheSize;
10269
10270                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10271                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10272
10273                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10274                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10275                }
10276            }
10277        }
10278
10279        @Override
10280        void handleReturnCode() {
10281            if (mObserver != null) {
10282                try {
10283                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10284                } catch (RemoteException e) {
10285                    Slog.i(TAG, "Observer no longer exists.");
10286                }
10287            }
10288        }
10289
10290        @Override
10291        void handleServiceError() {
10292            Slog.e(TAG, "Could not measure application " + mStats.packageName
10293                            + " external storage");
10294        }
10295    }
10296
10297    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10298            throws RemoteException {
10299        long result = 0;
10300        for (File path : paths) {
10301            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10302        }
10303        return result;
10304    }
10305
10306    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10307        for (File path : paths) {
10308            try {
10309                mcs.clearDirectory(path.getAbsolutePath());
10310            } catch (RemoteException e) {
10311            }
10312        }
10313    }
10314
10315    static class OriginInfo {
10316        /**
10317         * Location where install is coming from, before it has been
10318         * copied/renamed into place. This could be a single monolithic APK
10319         * file, or a cluster directory. This location may be untrusted.
10320         */
10321        final File file;
10322        final String cid;
10323
10324        /**
10325         * Flag indicating that {@link #file} or {@link #cid} has already been
10326         * staged, meaning downstream users don't need to defensively copy the
10327         * contents.
10328         */
10329        final boolean staged;
10330
10331        /**
10332         * Flag indicating that {@link #file} or {@link #cid} is an already
10333         * installed app that is being moved.
10334         */
10335        final boolean existing;
10336
10337        final String resolvedPath;
10338        final File resolvedFile;
10339
10340        static OriginInfo fromNothing() {
10341            return new OriginInfo(null, null, false, false);
10342        }
10343
10344        static OriginInfo fromUntrustedFile(File file) {
10345            return new OriginInfo(file, null, false, false);
10346        }
10347
10348        static OriginInfo fromExistingFile(File file) {
10349            return new OriginInfo(file, null, false, true);
10350        }
10351
10352        static OriginInfo fromStagedFile(File file) {
10353            return new OriginInfo(file, null, true, false);
10354        }
10355
10356        static OriginInfo fromStagedContainer(String cid) {
10357            return new OriginInfo(null, cid, true, false);
10358        }
10359
10360        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10361            this.file = file;
10362            this.cid = cid;
10363            this.staged = staged;
10364            this.existing = existing;
10365
10366            if (cid != null) {
10367                resolvedPath = PackageHelper.getSdDir(cid);
10368                resolvedFile = new File(resolvedPath);
10369            } else if (file != null) {
10370                resolvedPath = file.getAbsolutePath();
10371                resolvedFile = file;
10372            } else {
10373                resolvedPath = null;
10374                resolvedFile = null;
10375            }
10376        }
10377    }
10378
10379    class MoveInfo {
10380        final int moveId;
10381        final String fromUuid;
10382        final String toUuid;
10383        final String packageName;
10384        final String dataAppName;
10385        final int appId;
10386        final String seinfo;
10387
10388        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10389                String dataAppName, int appId, String seinfo) {
10390            this.moveId = moveId;
10391            this.fromUuid = fromUuid;
10392            this.toUuid = toUuid;
10393            this.packageName = packageName;
10394            this.dataAppName = dataAppName;
10395            this.appId = appId;
10396            this.seinfo = seinfo;
10397        }
10398    }
10399
10400    class InstallParams extends HandlerParams {
10401        final OriginInfo origin;
10402        final MoveInfo move;
10403        final IPackageInstallObserver2 observer;
10404        int installFlags;
10405        final String installerPackageName;
10406        final String volumeUuid;
10407        final VerificationParams verificationParams;
10408        private InstallArgs mArgs;
10409        private int mRet;
10410        final String packageAbiOverride;
10411        final String[] grantedRuntimePermissions;
10412
10413
10414        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10415                int installFlags, String installerPackageName, String volumeUuid,
10416                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10417                String[] grantedPermissions) {
10418            super(user);
10419            this.origin = origin;
10420            this.move = move;
10421            this.observer = observer;
10422            this.installFlags = installFlags;
10423            this.installerPackageName = installerPackageName;
10424            this.volumeUuid = volumeUuid;
10425            this.verificationParams = verificationParams;
10426            this.packageAbiOverride = packageAbiOverride;
10427            this.grantedRuntimePermissions = grantedPermissions;
10428        }
10429
10430        @Override
10431        public String toString() {
10432            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10433                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10434        }
10435
10436        public ManifestDigest getManifestDigest() {
10437            if (verificationParams == null) {
10438                return null;
10439            }
10440            return verificationParams.getManifestDigest();
10441        }
10442
10443        private int installLocationPolicy(PackageInfoLite pkgLite) {
10444            String packageName = pkgLite.packageName;
10445            int installLocation = pkgLite.installLocation;
10446            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10447            // reader
10448            synchronized (mPackages) {
10449                PackageParser.Package pkg = mPackages.get(packageName);
10450                if (pkg != null) {
10451                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10452                        // Check for downgrading.
10453                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10454                            try {
10455                                checkDowngrade(pkg, pkgLite);
10456                            } catch (PackageManagerException e) {
10457                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10458                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10459                            }
10460                        }
10461                        // Check for updated system application.
10462                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10463                            if (onSd) {
10464                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10465                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10466                            }
10467                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10468                        } else {
10469                            if (onSd) {
10470                                // Install flag overrides everything.
10471                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10472                            }
10473                            // If current upgrade specifies particular preference
10474                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10475                                // Application explicitly specified internal.
10476                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10477                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10478                                // App explictly prefers external. Let policy decide
10479                            } else {
10480                                // Prefer previous location
10481                                if (isExternal(pkg)) {
10482                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10483                                }
10484                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10485                            }
10486                        }
10487                    } else {
10488                        // Invalid install. Return error code
10489                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10490                    }
10491                }
10492            }
10493            // All the special cases have been taken care of.
10494            // Return result based on recommended install location.
10495            if (onSd) {
10496                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10497            }
10498            return pkgLite.recommendedInstallLocation;
10499        }
10500
10501        /*
10502         * Invoke remote method to get package information and install
10503         * location values. Override install location based on default
10504         * policy if needed and then create install arguments based
10505         * on the install location.
10506         */
10507        public void handleStartCopy() throws RemoteException {
10508            int ret = PackageManager.INSTALL_SUCCEEDED;
10509
10510            // If we're already staged, we've firmly committed to an install location
10511            if (origin.staged) {
10512                if (origin.file != null) {
10513                    installFlags |= PackageManager.INSTALL_INTERNAL;
10514                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10515                } else if (origin.cid != null) {
10516                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10517                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10518                } else {
10519                    throw new IllegalStateException("Invalid stage location");
10520                }
10521            }
10522
10523            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10524            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10525
10526            PackageInfoLite pkgLite = null;
10527
10528            if (onInt && onSd) {
10529                // Check if both bits are set.
10530                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10531                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10532            } else {
10533                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10534                        packageAbiOverride);
10535
10536                /*
10537                 * If we have too little free space, try to free cache
10538                 * before giving up.
10539                 */
10540                if (!origin.staged && pkgLite.recommendedInstallLocation
10541                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10542                    // TODO: focus freeing disk space on the target device
10543                    final StorageManager storage = StorageManager.from(mContext);
10544                    final long lowThreshold = storage.getStorageLowBytes(
10545                            Environment.getDataDirectory());
10546
10547                    final long sizeBytes = mContainerService.calculateInstalledSize(
10548                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10549
10550                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10551                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10552                                installFlags, packageAbiOverride);
10553                    }
10554
10555                    /*
10556                     * The cache free must have deleted the file we
10557                     * downloaded to install.
10558                     *
10559                     * TODO: fix the "freeCache" call to not delete
10560                     *       the file we care about.
10561                     */
10562                    if (pkgLite.recommendedInstallLocation
10563                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10564                        pkgLite.recommendedInstallLocation
10565                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10566                    }
10567                }
10568            }
10569
10570            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10571                int loc = pkgLite.recommendedInstallLocation;
10572                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10573                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10574                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10575                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10576                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10577                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10578                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10579                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10580                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10581                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10582                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10583                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10584                } else {
10585                    // Override with defaults if needed.
10586                    loc = installLocationPolicy(pkgLite);
10587                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10588                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10589                    } else if (!onSd && !onInt) {
10590                        // Override install location with flags
10591                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10592                            // Set the flag to install on external media.
10593                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10594                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10595                        } else {
10596                            // Make sure the flag for installing on external
10597                            // media is unset
10598                            installFlags |= PackageManager.INSTALL_INTERNAL;
10599                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10600                        }
10601                    }
10602                }
10603            }
10604
10605            final InstallArgs args = createInstallArgs(this);
10606            mArgs = args;
10607
10608            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10609                 /*
10610                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10611                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10612                 */
10613                int userIdentifier = getUser().getIdentifier();
10614                if (userIdentifier == UserHandle.USER_ALL
10615                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10616                    userIdentifier = UserHandle.USER_OWNER;
10617                }
10618
10619                /*
10620                 * Determine if we have any installed package verifiers. If we
10621                 * do, then we'll defer to them to verify the packages.
10622                 */
10623                final int requiredUid = mRequiredVerifierPackage == null ? -1
10624                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10625                if (!origin.existing && requiredUid != -1
10626                        && isVerificationEnabled(userIdentifier, installFlags)) {
10627                    final Intent verification = new Intent(
10628                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10629                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10630                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10631                            PACKAGE_MIME_TYPE);
10632                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10633
10634                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10635                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10636                            0 /* TODO: Which userId? */);
10637
10638                    if (DEBUG_VERIFY) {
10639                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10640                                + verification.toString() + " with " + pkgLite.verifiers.length
10641                                + " optional verifiers");
10642                    }
10643
10644                    final int verificationId = mPendingVerificationToken++;
10645
10646                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10647
10648                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10649                            installerPackageName);
10650
10651                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10652                            installFlags);
10653
10654                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10655                            pkgLite.packageName);
10656
10657                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10658                            pkgLite.versionCode);
10659
10660                    if (verificationParams != null) {
10661                        if (verificationParams.getVerificationURI() != null) {
10662                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10663                                 verificationParams.getVerificationURI());
10664                        }
10665                        if (verificationParams.getOriginatingURI() != null) {
10666                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10667                                  verificationParams.getOriginatingURI());
10668                        }
10669                        if (verificationParams.getReferrer() != null) {
10670                            verification.putExtra(Intent.EXTRA_REFERRER,
10671                                  verificationParams.getReferrer());
10672                        }
10673                        if (verificationParams.getOriginatingUid() >= 0) {
10674                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10675                                  verificationParams.getOriginatingUid());
10676                        }
10677                        if (verificationParams.getInstallerUid() >= 0) {
10678                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10679                                  verificationParams.getInstallerUid());
10680                        }
10681                    }
10682
10683                    final PackageVerificationState verificationState = new PackageVerificationState(
10684                            requiredUid, args);
10685
10686                    mPendingVerification.append(verificationId, verificationState);
10687
10688                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10689                            receivers, verificationState);
10690
10691                    // Apps installed for "all" users use the device owner to verify the app
10692                    UserHandle verifierUser = getUser();
10693                    if (verifierUser == UserHandle.ALL) {
10694                        verifierUser = UserHandle.OWNER;
10695                    }
10696
10697                    /*
10698                     * If any sufficient verifiers were listed in the package
10699                     * manifest, attempt to ask them.
10700                     */
10701                    if (sufficientVerifiers != null) {
10702                        final int N = sufficientVerifiers.size();
10703                        if (N == 0) {
10704                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10705                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10706                        } else {
10707                            for (int i = 0; i < N; i++) {
10708                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10709
10710                                final Intent sufficientIntent = new Intent(verification);
10711                                sufficientIntent.setComponent(verifierComponent);
10712                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10713                            }
10714                        }
10715                    }
10716
10717                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10718                            mRequiredVerifierPackage, receivers);
10719                    if (ret == PackageManager.INSTALL_SUCCEEDED
10720                            && mRequiredVerifierPackage != null) {
10721                        /*
10722                         * Send the intent to the required verification agent,
10723                         * but only start the verification timeout after the
10724                         * target BroadcastReceivers have run.
10725                         */
10726                        verification.setComponent(requiredVerifierComponent);
10727                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10728                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10729                                new BroadcastReceiver() {
10730                                    @Override
10731                                    public void onReceive(Context context, Intent intent) {
10732                                        final Message msg = mHandler
10733                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10734                                        msg.arg1 = verificationId;
10735                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10736                                    }
10737                                }, null, 0, null, null);
10738
10739                        /*
10740                         * We don't want the copy to proceed until verification
10741                         * succeeds, so null out this field.
10742                         */
10743                        mArgs = null;
10744                    }
10745                } else {
10746                    /*
10747                     * No package verification is enabled, so immediately start
10748                     * the remote call to initiate copy using temporary file.
10749                     */
10750                    ret = args.copyApk(mContainerService, true);
10751                }
10752            }
10753
10754            mRet = ret;
10755        }
10756
10757        @Override
10758        void handleReturnCode() {
10759            // If mArgs is null, then MCS couldn't be reached. When it
10760            // reconnects, it will try again to install. At that point, this
10761            // will succeed.
10762            if (mArgs != null) {
10763                processPendingInstall(mArgs, mRet);
10764            }
10765        }
10766
10767        @Override
10768        void handleServiceError() {
10769            mArgs = createInstallArgs(this);
10770            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10771        }
10772
10773        public boolean isForwardLocked() {
10774            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10775        }
10776    }
10777
10778    /**
10779     * Used during creation of InstallArgs
10780     *
10781     * @param installFlags package installation flags
10782     * @return true if should be installed on external storage
10783     */
10784    private static boolean installOnExternalAsec(int installFlags) {
10785        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10786            return false;
10787        }
10788        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10789            return true;
10790        }
10791        return false;
10792    }
10793
10794    /**
10795     * Used during creation of InstallArgs
10796     *
10797     * @param installFlags package installation flags
10798     * @return true if should be installed as forward locked
10799     */
10800    private static boolean installForwardLocked(int installFlags) {
10801        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10802    }
10803
10804    private InstallArgs createInstallArgs(InstallParams params) {
10805        if (params.move != null) {
10806            return new MoveInstallArgs(params);
10807        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10808            return new AsecInstallArgs(params);
10809        } else {
10810            return new FileInstallArgs(params);
10811        }
10812    }
10813
10814    /**
10815     * Create args that describe an existing installed package. Typically used
10816     * when cleaning up old installs, or used as a move source.
10817     */
10818    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10819            String resourcePath, String[] instructionSets) {
10820        final boolean isInAsec;
10821        if (installOnExternalAsec(installFlags)) {
10822            /* Apps on SD card are always in ASEC containers. */
10823            isInAsec = true;
10824        } else if (installForwardLocked(installFlags)
10825                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10826            /*
10827             * Forward-locked apps are only in ASEC containers if they're the
10828             * new style
10829             */
10830            isInAsec = true;
10831        } else {
10832            isInAsec = false;
10833        }
10834
10835        if (isInAsec) {
10836            return new AsecInstallArgs(codePath, instructionSets,
10837                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10838        } else {
10839            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10840        }
10841    }
10842
10843    static abstract class InstallArgs {
10844        /** @see InstallParams#origin */
10845        final OriginInfo origin;
10846        /** @see InstallParams#move */
10847        final MoveInfo move;
10848
10849        final IPackageInstallObserver2 observer;
10850        // Always refers to PackageManager flags only
10851        final int installFlags;
10852        final String installerPackageName;
10853        final String volumeUuid;
10854        final ManifestDigest manifestDigest;
10855        final UserHandle user;
10856        final String abiOverride;
10857        final String[] installGrantPermissions;
10858
10859        // The list of instruction sets supported by this app. This is currently
10860        // only used during the rmdex() phase to clean up resources. We can get rid of this
10861        // if we move dex files under the common app path.
10862        /* nullable */ String[] instructionSets;
10863
10864        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10865                int installFlags, String installerPackageName, String volumeUuid,
10866                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10867                String abiOverride, String[] installGrantPermissions) {
10868            this.origin = origin;
10869            this.move = move;
10870            this.installFlags = installFlags;
10871            this.observer = observer;
10872            this.installerPackageName = installerPackageName;
10873            this.volumeUuid = volumeUuid;
10874            this.manifestDigest = manifestDigest;
10875            this.user = user;
10876            this.instructionSets = instructionSets;
10877            this.abiOverride = abiOverride;
10878            this.installGrantPermissions = installGrantPermissions;
10879        }
10880
10881        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10882        abstract int doPreInstall(int status);
10883
10884        /**
10885         * Rename package into final resting place. All paths on the given
10886         * scanned package should be updated to reflect the rename.
10887         */
10888        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10889        abstract int doPostInstall(int status, int uid);
10890
10891        /** @see PackageSettingBase#codePathString */
10892        abstract String getCodePath();
10893        /** @see PackageSettingBase#resourcePathString */
10894        abstract String getResourcePath();
10895
10896        // Need installer lock especially for dex file removal.
10897        abstract void cleanUpResourcesLI();
10898        abstract boolean doPostDeleteLI(boolean delete);
10899
10900        /**
10901         * Called before the source arguments are copied. This is used mostly
10902         * for MoveParams when it needs to read the source file to put it in the
10903         * destination.
10904         */
10905        int doPreCopy() {
10906            return PackageManager.INSTALL_SUCCEEDED;
10907        }
10908
10909        /**
10910         * Called after the source arguments are copied. This is used mostly for
10911         * MoveParams when it needs to read the source file to put it in the
10912         * destination.
10913         *
10914         * @return
10915         */
10916        int doPostCopy(int uid) {
10917            return PackageManager.INSTALL_SUCCEEDED;
10918        }
10919
10920        protected boolean isFwdLocked() {
10921            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10922        }
10923
10924        protected boolean isExternalAsec() {
10925            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10926        }
10927
10928        UserHandle getUser() {
10929            return user;
10930        }
10931    }
10932
10933    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10934        if (!allCodePaths.isEmpty()) {
10935            if (instructionSets == null) {
10936                throw new IllegalStateException("instructionSet == null");
10937            }
10938            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10939            for (String codePath : allCodePaths) {
10940                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10941                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10942                    if (retCode < 0) {
10943                        Slog.w(TAG, "Couldn't remove dex file for package: "
10944                                + " at location " + codePath + ", retcode=" + retCode);
10945                        // we don't consider this to be a failure of the core package deletion
10946                    }
10947                }
10948            }
10949        }
10950    }
10951
10952    /**
10953     * Logic to handle installation of non-ASEC applications, including copying
10954     * and renaming logic.
10955     */
10956    class FileInstallArgs extends InstallArgs {
10957        private File codeFile;
10958        private File resourceFile;
10959
10960        // Example topology:
10961        // /data/app/com.example/base.apk
10962        // /data/app/com.example/split_foo.apk
10963        // /data/app/com.example/lib/arm/libfoo.so
10964        // /data/app/com.example/lib/arm64/libfoo.so
10965        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10966
10967        /** New install */
10968        FileInstallArgs(InstallParams params) {
10969            super(params.origin, params.move, params.observer, params.installFlags,
10970                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10971                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10972                    params.grantedRuntimePermissions);
10973            if (isFwdLocked()) {
10974                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10975            }
10976        }
10977
10978        /** Existing install */
10979        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10980            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10981                    null, null);
10982            this.codeFile = (codePath != null) ? new File(codePath) : null;
10983            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10984        }
10985
10986        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10987            if (origin.staged) {
10988                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10989                codeFile = origin.file;
10990                resourceFile = origin.file;
10991                return PackageManager.INSTALL_SUCCEEDED;
10992            }
10993
10994            try {
10995                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10996                codeFile = tempDir;
10997                resourceFile = tempDir;
10998            } catch (IOException e) {
10999                Slog.w(TAG, "Failed to create copy file: " + e);
11000                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11001            }
11002
11003            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11004                @Override
11005                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11006                    if (!FileUtils.isValidExtFilename(name)) {
11007                        throw new IllegalArgumentException("Invalid filename: " + name);
11008                    }
11009                    try {
11010                        final File file = new File(codeFile, name);
11011                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11012                                O_RDWR | O_CREAT, 0644);
11013                        Os.chmod(file.getAbsolutePath(), 0644);
11014                        return new ParcelFileDescriptor(fd);
11015                    } catch (ErrnoException e) {
11016                        throw new RemoteException("Failed to open: " + e.getMessage());
11017                    }
11018                }
11019            };
11020
11021            int ret = PackageManager.INSTALL_SUCCEEDED;
11022            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11023            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11024                Slog.e(TAG, "Failed to copy package");
11025                return ret;
11026            }
11027
11028            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11029            NativeLibraryHelper.Handle handle = null;
11030            try {
11031                handle = NativeLibraryHelper.Handle.create(codeFile);
11032                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11033                        abiOverride);
11034            } catch (IOException e) {
11035                Slog.e(TAG, "Copying native libraries failed", e);
11036                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11037            } finally {
11038                IoUtils.closeQuietly(handle);
11039            }
11040
11041            return ret;
11042        }
11043
11044        int doPreInstall(int status) {
11045            if (status != PackageManager.INSTALL_SUCCEEDED) {
11046                cleanUp();
11047            }
11048            return status;
11049        }
11050
11051        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11052            if (status != PackageManager.INSTALL_SUCCEEDED) {
11053                cleanUp();
11054                return false;
11055            }
11056
11057            final File targetDir = codeFile.getParentFile();
11058            final File beforeCodeFile = codeFile;
11059            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11060
11061            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11062            try {
11063                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11064            } catch (ErrnoException e) {
11065                Slog.w(TAG, "Failed to rename", e);
11066                return false;
11067            }
11068
11069            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11070                Slog.w(TAG, "Failed to restorecon");
11071                return false;
11072            }
11073
11074            // Reflect the rename internally
11075            codeFile = afterCodeFile;
11076            resourceFile = afterCodeFile;
11077
11078            // Reflect the rename in scanned details
11079            pkg.codePath = afterCodeFile.getAbsolutePath();
11080            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11081                    pkg.baseCodePath);
11082            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11083                    pkg.splitCodePaths);
11084
11085            // Reflect the rename in app info
11086            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11087            pkg.applicationInfo.setCodePath(pkg.codePath);
11088            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11089            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11090            pkg.applicationInfo.setResourcePath(pkg.codePath);
11091            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11092            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11093
11094            return true;
11095        }
11096
11097        int doPostInstall(int status, int uid) {
11098            if (status != PackageManager.INSTALL_SUCCEEDED) {
11099                cleanUp();
11100            }
11101            return status;
11102        }
11103
11104        @Override
11105        String getCodePath() {
11106            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11107        }
11108
11109        @Override
11110        String getResourcePath() {
11111            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11112        }
11113
11114        private boolean cleanUp() {
11115            if (codeFile == null || !codeFile.exists()) {
11116                return false;
11117            }
11118
11119            if (codeFile.isDirectory()) {
11120                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11121            } else {
11122                codeFile.delete();
11123            }
11124
11125            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11126                resourceFile.delete();
11127            }
11128
11129            return true;
11130        }
11131
11132        void cleanUpResourcesLI() {
11133            // Try enumerating all code paths before deleting
11134            List<String> allCodePaths = Collections.EMPTY_LIST;
11135            if (codeFile != null && codeFile.exists()) {
11136                try {
11137                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11138                    allCodePaths = pkg.getAllCodePaths();
11139                } catch (PackageParserException e) {
11140                    // Ignored; we tried our best
11141                }
11142            }
11143
11144            cleanUp();
11145            removeDexFiles(allCodePaths, instructionSets);
11146        }
11147
11148        boolean doPostDeleteLI(boolean delete) {
11149            // XXX err, shouldn't we respect the delete flag?
11150            cleanUpResourcesLI();
11151            return true;
11152        }
11153    }
11154
11155    private boolean isAsecExternal(String cid) {
11156        final String asecPath = PackageHelper.getSdFilesystem(cid);
11157        return !asecPath.startsWith(mAsecInternalPath);
11158    }
11159
11160    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11161            PackageManagerException {
11162        if (copyRet < 0) {
11163            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11164                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11165                throw new PackageManagerException(copyRet, message);
11166            }
11167        }
11168    }
11169
11170    /**
11171     * Extract the MountService "container ID" from the full code path of an
11172     * .apk.
11173     */
11174    static String cidFromCodePath(String fullCodePath) {
11175        int eidx = fullCodePath.lastIndexOf("/");
11176        String subStr1 = fullCodePath.substring(0, eidx);
11177        int sidx = subStr1.lastIndexOf("/");
11178        return subStr1.substring(sidx+1, eidx);
11179    }
11180
11181    /**
11182     * Logic to handle installation of ASEC applications, including copying and
11183     * renaming logic.
11184     */
11185    class AsecInstallArgs extends InstallArgs {
11186        static final String RES_FILE_NAME = "pkg.apk";
11187        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11188
11189        String cid;
11190        String packagePath;
11191        String resourcePath;
11192
11193        /** New install */
11194        AsecInstallArgs(InstallParams params) {
11195            super(params.origin, params.move, params.observer, params.installFlags,
11196                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11197                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11198                    params.grantedRuntimePermissions);
11199        }
11200
11201        /** Existing install */
11202        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11203                        boolean isExternal, boolean isForwardLocked) {
11204            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11205                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11206                    instructionSets, null, null);
11207            // Hackily pretend we're still looking at a full code path
11208            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11209                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11210            }
11211
11212            // Extract cid from fullCodePath
11213            int eidx = fullCodePath.lastIndexOf("/");
11214            String subStr1 = fullCodePath.substring(0, eidx);
11215            int sidx = subStr1.lastIndexOf("/");
11216            cid = subStr1.substring(sidx+1, eidx);
11217            setMountPath(subStr1);
11218        }
11219
11220        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11221            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11222                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11223                    instructionSets, null, null);
11224            this.cid = cid;
11225            setMountPath(PackageHelper.getSdDir(cid));
11226        }
11227
11228        void createCopyFile() {
11229            cid = mInstallerService.allocateExternalStageCidLegacy();
11230        }
11231
11232        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11233            if (origin.staged) {
11234                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11235                cid = origin.cid;
11236                setMountPath(PackageHelper.getSdDir(cid));
11237                return PackageManager.INSTALL_SUCCEEDED;
11238            }
11239
11240            if (temp) {
11241                createCopyFile();
11242            } else {
11243                /*
11244                 * Pre-emptively destroy the container since it's destroyed if
11245                 * copying fails due to it existing anyway.
11246                 */
11247                PackageHelper.destroySdDir(cid);
11248            }
11249
11250            final String newMountPath = imcs.copyPackageToContainer(
11251                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11252                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11253
11254            if (newMountPath != null) {
11255                setMountPath(newMountPath);
11256                return PackageManager.INSTALL_SUCCEEDED;
11257            } else {
11258                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11259            }
11260        }
11261
11262        @Override
11263        String getCodePath() {
11264            return packagePath;
11265        }
11266
11267        @Override
11268        String getResourcePath() {
11269            return resourcePath;
11270        }
11271
11272        int doPreInstall(int status) {
11273            if (status != PackageManager.INSTALL_SUCCEEDED) {
11274                // Destroy container
11275                PackageHelper.destroySdDir(cid);
11276            } else {
11277                boolean mounted = PackageHelper.isContainerMounted(cid);
11278                if (!mounted) {
11279                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11280                            Process.SYSTEM_UID);
11281                    if (newMountPath != null) {
11282                        setMountPath(newMountPath);
11283                    } else {
11284                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11285                    }
11286                }
11287            }
11288            return status;
11289        }
11290
11291        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11292            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11293            String newMountPath = null;
11294            if (PackageHelper.isContainerMounted(cid)) {
11295                // Unmount the container
11296                if (!PackageHelper.unMountSdDir(cid)) {
11297                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11298                    return false;
11299                }
11300            }
11301            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11302                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11303                        " which might be stale. Will try to clean up.");
11304                // Clean up the stale container and proceed to recreate.
11305                if (!PackageHelper.destroySdDir(newCacheId)) {
11306                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11307                    return false;
11308                }
11309                // Successfully cleaned up stale container. Try to rename again.
11310                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11311                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11312                            + " inspite of cleaning it up.");
11313                    return false;
11314                }
11315            }
11316            if (!PackageHelper.isContainerMounted(newCacheId)) {
11317                Slog.w(TAG, "Mounting container " + newCacheId);
11318                newMountPath = PackageHelper.mountSdDir(newCacheId,
11319                        getEncryptKey(), Process.SYSTEM_UID);
11320            } else {
11321                newMountPath = PackageHelper.getSdDir(newCacheId);
11322            }
11323            if (newMountPath == null) {
11324                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11325                return false;
11326            }
11327            Log.i(TAG, "Succesfully renamed " + cid +
11328                    " to " + newCacheId +
11329                    " at new path: " + newMountPath);
11330            cid = newCacheId;
11331
11332            final File beforeCodeFile = new File(packagePath);
11333            setMountPath(newMountPath);
11334            final File afterCodeFile = new File(packagePath);
11335
11336            // Reflect the rename in scanned details
11337            pkg.codePath = afterCodeFile.getAbsolutePath();
11338            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11339                    pkg.baseCodePath);
11340            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11341                    pkg.splitCodePaths);
11342
11343            // Reflect the rename in app info
11344            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11345            pkg.applicationInfo.setCodePath(pkg.codePath);
11346            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11347            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11348            pkg.applicationInfo.setResourcePath(pkg.codePath);
11349            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11350            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11351
11352            return true;
11353        }
11354
11355        private void setMountPath(String mountPath) {
11356            final File mountFile = new File(mountPath);
11357
11358            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11359            if (monolithicFile.exists()) {
11360                packagePath = monolithicFile.getAbsolutePath();
11361                if (isFwdLocked()) {
11362                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11363                } else {
11364                    resourcePath = packagePath;
11365                }
11366            } else {
11367                packagePath = mountFile.getAbsolutePath();
11368                resourcePath = packagePath;
11369            }
11370        }
11371
11372        int doPostInstall(int status, int uid) {
11373            if (status != PackageManager.INSTALL_SUCCEEDED) {
11374                cleanUp();
11375            } else {
11376                final int groupOwner;
11377                final String protectedFile;
11378                if (isFwdLocked()) {
11379                    groupOwner = UserHandle.getSharedAppGid(uid);
11380                    protectedFile = RES_FILE_NAME;
11381                } else {
11382                    groupOwner = -1;
11383                    protectedFile = null;
11384                }
11385
11386                if (uid < Process.FIRST_APPLICATION_UID
11387                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11388                    Slog.e(TAG, "Failed to finalize " + cid);
11389                    PackageHelper.destroySdDir(cid);
11390                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11391                }
11392
11393                boolean mounted = PackageHelper.isContainerMounted(cid);
11394                if (!mounted) {
11395                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11396                }
11397            }
11398            return status;
11399        }
11400
11401        private void cleanUp() {
11402            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11403
11404            // Destroy secure container
11405            PackageHelper.destroySdDir(cid);
11406        }
11407
11408        private List<String> getAllCodePaths() {
11409            final File codeFile = new File(getCodePath());
11410            if (codeFile != null && codeFile.exists()) {
11411                try {
11412                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11413                    return pkg.getAllCodePaths();
11414                } catch (PackageParserException e) {
11415                    // Ignored; we tried our best
11416                }
11417            }
11418            return Collections.EMPTY_LIST;
11419        }
11420
11421        void cleanUpResourcesLI() {
11422            // Enumerate all code paths before deleting
11423            cleanUpResourcesLI(getAllCodePaths());
11424        }
11425
11426        private void cleanUpResourcesLI(List<String> allCodePaths) {
11427            cleanUp();
11428            removeDexFiles(allCodePaths, instructionSets);
11429        }
11430
11431        String getPackageName() {
11432            return getAsecPackageName(cid);
11433        }
11434
11435        boolean doPostDeleteLI(boolean delete) {
11436            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11437            final List<String> allCodePaths = getAllCodePaths();
11438            boolean mounted = PackageHelper.isContainerMounted(cid);
11439            if (mounted) {
11440                // Unmount first
11441                if (PackageHelper.unMountSdDir(cid)) {
11442                    mounted = false;
11443                }
11444            }
11445            if (!mounted && delete) {
11446                cleanUpResourcesLI(allCodePaths);
11447            }
11448            return !mounted;
11449        }
11450
11451        @Override
11452        int doPreCopy() {
11453            if (isFwdLocked()) {
11454                if (!PackageHelper.fixSdPermissions(cid,
11455                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11456                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11457                }
11458            }
11459
11460            return PackageManager.INSTALL_SUCCEEDED;
11461        }
11462
11463        @Override
11464        int doPostCopy(int uid) {
11465            if (isFwdLocked()) {
11466                if (uid < Process.FIRST_APPLICATION_UID
11467                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11468                                RES_FILE_NAME)) {
11469                    Slog.e(TAG, "Failed to finalize " + cid);
11470                    PackageHelper.destroySdDir(cid);
11471                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11472                }
11473            }
11474
11475            return PackageManager.INSTALL_SUCCEEDED;
11476        }
11477    }
11478
11479    /**
11480     * Logic to handle movement of existing installed applications.
11481     */
11482    class MoveInstallArgs extends InstallArgs {
11483        private File codeFile;
11484        private File resourceFile;
11485
11486        /** New install */
11487        MoveInstallArgs(InstallParams params) {
11488            super(params.origin, params.move, params.observer, params.installFlags,
11489                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11490                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11491                    params.grantedRuntimePermissions);
11492        }
11493
11494        int copyApk(IMediaContainerService imcs, boolean temp) {
11495            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11496                    + move.fromUuid + " to " + move.toUuid);
11497            synchronized (mInstaller) {
11498                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11499                        move.dataAppName, move.appId, move.seinfo) != 0) {
11500                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11501                }
11502            }
11503
11504            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11505            resourceFile = codeFile;
11506            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11507
11508            return PackageManager.INSTALL_SUCCEEDED;
11509        }
11510
11511        int doPreInstall(int status) {
11512            if (status != PackageManager.INSTALL_SUCCEEDED) {
11513                cleanUp(move.toUuid);
11514            }
11515            return status;
11516        }
11517
11518        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11519            if (status != PackageManager.INSTALL_SUCCEEDED) {
11520                cleanUp(move.toUuid);
11521                return false;
11522            }
11523
11524            // Reflect the move in app info
11525            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11526            pkg.applicationInfo.setCodePath(pkg.codePath);
11527            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11528            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11529            pkg.applicationInfo.setResourcePath(pkg.codePath);
11530            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11531            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11532
11533            return true;
11534        }
11535
11536        int doPostInstall(int status, int uid) {
11537            if (status == PackageManager.INSTALL_SUCCEEDED) {
11538                cleanUp(move.fromUuid);
11539            } else {
11540                cleanUp(move.toUuid);
11541            }
11542            return status;
11543        }
11544
11545        @Override
11546        String getCodePath() {
11547            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11548        }
11549
11550        @Override
11551        String getResourcePath() {
11552            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11553        }
11554
11555        private boolean cleanUp(String volumeUuid) {
11556            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11557                    move.dataAppName);
11558            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11559            synchronized (mInstallLock) {
11560                // Clean up both app data and code
11561                removeDataDirsLI(volumeUuid, move.packageName);
11562                if (codeFile.isDirectory()) {
11563                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11564                } else {
11565                    codeFile.delete();
11566                }
11567            }
11568            return true;
11569        }
11570
11571        void cleanUpResourcesLI() {
11572            throw new UnsupportedOperationException();
11573        }
11574
11575        boolean doPostDeleteLI(boolean delete) {
11576            throw new UnsupportedOperationException();
11577        }
11578    }
11579
11580    static String getAsecPackageName(String packageCid) {
11581        int idx = packageCid.lastIndexOf("-");
11582        if (idx == -1) {
11583            return packageCid;
11584        }
11585        return packageCid.substring(0, idx);
11586    }
11587
11588    // Utility method used to create code paths based on package name and available index.
11589    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11590        String idxStr = "";
11591        int idx = 1;
11592        // Fall back to default value of idx=1 if prefix is not
11593        // part of oldCodePath
11594        if (oldCodePath != null) {
11595            String subStr = oldCodePath;
11596            // Drop the suffix right away
11597            if (suffix != null && subStr.endsWith(suffix)) {
11598                subStr = subStr.substring(0, subStr.length() - suffix.length());
11599            }
11600            // If oldCodePath already contains prefix find out the
11601            // ending index to either increment or decrement.
11602            int sidx = subStr.lastIndexOf(prefix);
11603            if (sidx != -1) {
11604                subStr = subStr.substring(sidx + prefix.length());
11605                if (subStr != null) {
11606                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11607                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11608                    }
11609                    try {
11610                        idx = Integer.parseInt(subStr);
11611                        if (idx <= 1) {
11612                            idx++;
11613                        } else {
11614                            idx--;
11615                        }
11616                    } catch(NumberFormatException e) {
11617                    }
11618                }
11619            }
11620        }
11621        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11622        return prefix + idxStr;
11623    }
11624
11625    private File getNextCodePath(File targetDir, String packageName) {
11626        int suffix = 1;
11627        File result;
11628        do {
11629            result = new File(targetDir, packageName + "-" + suffix);
11630            suffix++;
11631        } while (result.exists());
11632        return result;
11633    }
11634
11635    // Utility method that returns the relative package path with respect
11636    // to the installation directory. Like say for /data/data/com.test-1.apk
11637    // string com.test-1 is returned.
11638    static String deriveCodePathName(String codePath) {
11639        if (codePath == null) {
11640            return null;
11641        }
11642        final File codeFile = new File(codePath);
11643        final String name = codeFile.getName();
11644        if (codeFile.isDirectory()) {
11645            return name;
11646        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11647            final int lastDot = name.lastIndexOf('.');
11648            return name.substring(0, lastDot);
11649        } else {
11650            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11651            return null;
11652        }
11653    }
11654
11655    class PackageInstalledInfo {
11656        String name;
11657        int uid;
11658        // The set of users that originally had this package installed.
11659        int[] origUsers;
11660        // The set of users that now have this package installed.
11661        int[] newUsers;
11662        PackageParser.Package pkg;
11663        int returnCode;
11664        String returnMsg;
11665        PackageRemovedInfo removedInfo;
11666
11667        public void setError(int code, String msg) {
11668            returnCode = code;
11669            returnMsg = msg;
11670            Slog.w(TAG, msg);
11671        }
11672
11673        public void setError(String msg, PackageParserException e) {
11674            returnCode = e.error;
11675            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11676            Slog.w(TAG, msg, e);
11677        }
11678
11679        public void setError(String msg, PackageManagerException e) {
11680            returnCode = e.error;
11681            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11682            Slog.w(TAG, msg, e);
11683        }
11684
11685        // In some error cases we want to convey more info back to the observer
11686        String origPackage;
11687        String origPermission;
11688    }
11689
11690    /*
11691     * Install a non-existing package.
11692     */
11693    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11694            UserHandle user, String installerPackageName, String volumeUuid,
11695            PackageInstalledInfo res) {
11696        // Remember this for later, in case we need to rollback this install
11697        String pkgName = pkg.packageName;
11698
11699        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11700        final boolean dataDirExists = Environment
11701                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11702        synchronized(mPackages) {
11703            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11704                // A package with the same name is already installed, though
11705                // it has been renamed to an older name.  The package we
11706                // are trying to install should be installed as an update to
11707                // the existing one, but that has not been requested, so bail.
11708                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11709                        + " without first uninstalling package running as "
11710                        + mSettings.mRenamedPackages.get(pkgName));
11711                return;
11712            }
11713            if (mPackages.containsKey(pkgName)) {
11714                // Don't allow installation over an existing package with the same name.
11715                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11716                        + " without first uninstalling.");
11717                return;
11718            }
11719        }
11720
11721        try {
11722            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11723                    System.currentTimeMillis(), user);
11724
11725            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11726            // delete the partially installed application. the data directory will have to be
11727            // restored if it was already existing
11728            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11729                // remove package from internal structures.  Note that we want deletePackageX to
11730                // delete the package data and cache directories that it created in
11731                // scanPackageLocked, unless those directories existed before we even tried to
11732                // install.
11733                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11734                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11735                                res.removedInfo, true);
11736            }
11737
11738        } catch (PackageManagerException e) {
11739            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11740        }
11741    }
11742
11743    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11744        // Can't rotate keys during boot or if sharedUser.
11745        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11746                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11747            return false;
11748        }
11749        // app is using upgradeKeySets; make sure all are valid
11750        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11751        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11752        for (int i = 0; i < upgradeKeySets.length; i++) {
11753            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11754                Slog.wtf(TAG, "Package "
11755                         + (oldPs.name != null ? oldPs.name : "<null>")
11756                         + " contains upgrade-key-set reference to unknown key-set: "
11757                         + upgradeKeySets[i]
11758                         + " reverting to signatures check.");
11759                return false;
11760            }
11761        }
11762        return true;
11763    }
11764
11765    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11766        // Upgrade keysets are being used.  Determine if new package has a superset of the
11767        // required keys.
11768        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11769        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11770        for (int i = 0; i < upgradeKeySets.length; i++) {
11771            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11772            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11773                return true;
11774            }
11775        }
11776        return false;
11777    }
11778
11779    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11780            UserHandle user, String installerPackageName, String volumeUuid,
11781            PackageInstalledInfo res) {
11782        final PackageParser.Package oldPackage;
11783        final String pkgName = pkg.packageName;
11784        final int[] allUsers;
11785        final boolean[] perUserInstalled;
11786
11787        // First find the old package info and check signatures
11788        synchronized(mPackages) {
11789            oldPackage = mPackages.get(pkgName);
11790            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11791            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11792            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11793                if(!checkUpgradeKeySetLP(ps, pkg)) {
11794                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11795                            "New package not signed by keys specified by upgrade-keysets: "
11796                            + pkgName);
11797                    return;
11798                }
11799            } else {
11800                // default to original signature matching
11801                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11802                    != PackageManager.SIGNATURE_MATCH) {
11803                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11804                            "New package has a different signature: " + pkgName);
11805                    return;
11806                }
11807            }
11808
11809            // In case of rollback, remember per-user/profile install state
11810            allUsers = sUserManager.getUserIds();
11811            perUserInstalled = new boolean[allUsers.length];
11812            for (int i = 0; i < allUsers.length; i++) {
11813                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11814            }
11815        }
11816
11817        boolean sysPkg = (isSystemApp(oldPackage));
11818        if (sysPkg) {
11819            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11820                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11821        } else {
11822            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11823                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11824        }
11825    }
11826
11827    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11828            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11829            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11830            String volumeUuid, PackageInstalledInfo res) {
11831        String pkgName = deletedPackage.packageName;
11832        boolean deletedPkg = true;
11833        boolean updatedSettings = false;
11834
11835        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11836                + deletedPackage);
11837        long origUpdateTime;
11838        if (pkg.mExtras != null) {
11839            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11840        } else {
11841            origUpdateTime = 0;
11842        }
11843
11844        // First delete the existing package while retaining the data directory
11845        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11846                res.removedInfo, true)) {
11847            // If the existing package wasn't successfully deleted
11848            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11849            deletedPkg = false;
11850        } else {
11851            // Successfully deleted the old package; proceed with replace.
11852
11853            // If deleted package lived in a container, give users a chance to
11854            // relinquish resources before killing.
11855            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11856                if (DEBUG_INSTALL) {
11857                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11858                }
11859                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11860                final ArrayList<String> pkgList = new ArrayList<String>(1);
11861                pkgList.add(deletedPackage.applicationInfo.packageName);
11862                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11863            }
11864
11865            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11866            try {
11867                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11868                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11869                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11870                        perUserInstalled, res, user);
11871                updatedSettings = true;
11872            } catch (PackageManagerException e) {
11873                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11874            }
11875        }
11876
11877        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11878            // remove package from internal structures.  Note that we want deletePackageX to
11879            // delete the package data and cache directories that it created in
11880            // scanPackageLocked, unless those directories existed before we even tried to
11881            // install.
11882            if(updatedSettings) {
11883                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11884                deletePackageLI(
11885                        pkgName, null, true, allUsers, perUserInstalled,
11886                        PackageManager.DELETE_KEEP_DATA,
11887                                res.removedInfo, true);
11888            }
11889            // Since we failed to install the new package we need to restore the old
11890            // package that we deleted.
11891            if (deletedPkg) {
11892                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11893                File restoreFile = new File(deletedPackage.codePath);
11894                // Parse old package
11895                boolean oldExternal = isExternal(deletedPackage);
11896                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11897                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11898                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11899                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11900                try {
11901                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11902                } catch (PackageManagerException e) {
11903                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11904                            + e.getMessage());
11905                    return;
11906                }
11907                // Restore of old package succeeded. Update permissions.
11908                // writer
11909                synchronized (mPackages) {
11910                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11911                            UPDATE_PERMISSIONS_ALL);
11912                    // can downgrade to reader
11913                    mSettings.writeLPr();
11914                }
11915                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11916            }
11917        }
11918    }
11919
11920    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11921            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11922            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11923            String volumeUuid, PackageInstalledInfo res) {
11924        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11925                + ", old=" + deletedPackage);
11926        boolean disabledSystem = false;
11927        boolean updatedSettings = false;
11928        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11929        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11930                != 0) {
11931            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11932        }
11933        String packageName = deletedPackage.packageName;
11934        if (packageName == null) {
11935            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11936                    "Attempt to delete null packageName.");
11937            return;
11938        }
11939        PackageParser.Package oldPkg;
11940        PackageSetting oldPkgSetting;
11941        // reader
11942        synchronized (mPackages) {
11943            oldPkg = mPackages.get(packageName);
11944            oldPkgSetting = mSettings.mPackages.get(packageName);
11945            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11946                    (oldPkgSetting == null)) {
11947                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11948                        "Couldn't find package:" + packageName + " information");
11949                return;
11950            }
11951        }
11952
11953        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11954
11955        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11956        res.removedInfo.removedPackage = packageName;
11957        // Remove existing system package
11958        removePackageLI(oldPkgSetting, true);
11959        // writer
11960        synchronized (mPackages) {
11961            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11962            if (!disabledSystem && deletedPackage != null) {
11963                // We didn't need to disable the .apk as a current system package,
11964                // which means we are replacing another update that is already
11965                // installed.  We need to make sure to delete the older one's .apk.
11966                res.removedInfo.args = createInstallArgsForExisting(0,
11967                        deletedPackage.applicationInfo.getCodePath(),
11968                        deletedPackage.applicationInfo.getResourcePath(),
11969                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11970            } else {
11971                res.removedInfo.args = null;
11972            }
11973        }
11974
11975        // Successfully disabled the old package. Now proceed with re-installation
11976        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11977
11978        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11979        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11980
11981        PackageParser.Package newPackage = null;
11982        try {
11983            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11984            if (newPackage.mExtras != null) {
11985                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11986                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11987                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11988
11989                // is the update attempting to change shared user? that isn't going to work...
11990                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11991                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11992                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11993                            + " to " + newPkgSetting.sharedUser);
11994                    updatedSettings = true;
11995                }
11996            }
11997
11998            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11999                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12000                        perUserInstalled, res, user);
12001                updatedSettings = true;
12002            }
12003
12004        } catch (PackageManagerException e) {
12005            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12006        }
12007
12008        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12009            // Re installation failed. Restore old information
12010            // Remove new pkg information
12011            if (newPackage != null) {
12012                removeInstalledPackageLI(newPackage, true);
12013            }
12014            // Add back the old system package
12015            try {
12016                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12017            } catch (PackageManagerException e) {
12018                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12019            }
12020            // Restore the old system information in Settings
12021            synchronized (mPackages) {
12022                if (disabledSystem) {
12023                    mSettings.enableSystemPackageLPw(packageName);
12024                }
12025                if (updatedSettings) {
12026                    mSettings.setInstallerPackageName(packageName,
12027                            oldPkgSetting.installerPackageName);
12028                }
12029                mSettings.writeLPr();
12030            }
12031        }
12032    }
12033
12034    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12035            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12036            UserHandle user) {
12037        String pkgName = newPackage.packageName;
12038        synchronized (mPackages) {
12039            //write settings. the installStatus will be incomplete at this stage.
12040            //note that the new package setting would have already been
12041            //added to mPackages. It hasn't been persisted yet.
12042            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12043            mSettings.writeLPr();
12044        }
12045
12046        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12047
12048        synchronized (mPackages) {
12049            updatePermissionsLPw(newPackage.packageName, newPackage,
12050                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12051                            ? UPDATE_PERMISSIONS_ALL : 0));
12052            // For system-bundled packages, we assume that installing an upgraded version
12053            // of the package implies that the user actually wants to run that new code,
12054            // so we enable the package.
12055            PackageSetting ps = mSettings.mPackages.get(pkgName);
12056            if (ps != null) {
12057                if (isSystemApp(newPackage)) {
12058                    // NB: implicit assumption that system package upgrades apply to all users
12059                    if (DEBUG_INSTALL) {
12060                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12061                    }
12062                    if (res.origUsers != null) {
12063                        for (int userHandle : res.origUsers) {
12064                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12065                                    userHandle, installerPackageName);
12066                        }
12067                    }
12068                    // Also convey the prior install/uninstall state
12069                    if (allUsers != null && perUserInstalled != null) {
12070                        for (int i = 0; i < allUsers.length; i++) {
12071                            if (DEBUG_INSTALL) {
12072                                Slog.d(TAG, "    user " + allUsers[i]
12073                                        + " => " + perUserInstalled[i]);
12074                            }
12075                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12076                        }
12077                        // these install state changes will be persisted in the
12078                        // upcoming call to mSettings.writeLPr().
12079                    }
12080                }
12081                // It's implied that when a user requests installation, they want the app to be
12082                // installed and enabled.
12083                int userId = user.getIdentifier();
12084                if (userId != UserHandle.USER_ALL) {
12085                    ps.setInstalled(true, userId);
12086                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12087                }
12088            }
12089            res.name = pkgName;
12090            res.uid = newPackage.applicationInfo.uid;
12091            res.pkg = newPackage;
12092            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12093            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12094            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12095            //to update install status
12096            mSettings.writeLPr();
12097        }
12098    }
12099
12100    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12101        final int installFlags = args.installFlags;
12102        final String installerPackageName = args.installerPackageName;
12103        final String volumeUuid = args.volumeUuid;
12104        final File tmpPackageFile = new File(args.getCodePath());
12105        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12106        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12107                || (args.volumeUuid != null));
12108        boolean replace = false;
12109        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12110        if (args.move != null) {
12111            // moving a complete application; perfom an initial scan on the new install location
12112            scanFlags |= SCAN_INITIAL;
12113        }
12114        // Result object to be returned
12115        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12116
12117        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12118        // Retrieve PackageSettings and parse package
12119        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12120                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12121                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12122        PackageParser pp = new PackageParser();
12123        pp.setSeparateProcesses(mSeparateProcesses);
12124        pp.setDisplayMetrics(mMetrics);
12125
12126        final PackageParser.Package pkg;
12127        try {
12128            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12129        } catch (PackageParserException e) {
12130            res.setError("Failed parse during installPackageLI", e);
12131            return;
12132        }
12133
12134        // Mark that we have an install time CPU ABI override.
12135        pkg.cpuAbiOverride = args.abiOverride;
12136
12137        String pkgName = res.name = pkg.packageName;
12138        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12139            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12140                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12141                return;
12142            }
12143        }
12144
12145        try {
12146            pp.collectCertificates(pkg, parseFlags);
12147            pp.collectManifestDigest(pkg);
12148        } catch (PackageParserException e) {
12149            res.setError("Failed collect during installPackageLI", e);
12150            return;
12151        }
12152
12153        /* If the installer passed in a manifest digest, compare it now. */
12154        if (args.manifestDigest != null) {
12155            if (DEBUG_INSTALL) {
12156                final String parsedManifest = pkg.manifestDigest == null ? "null"
12157                        : pkg.manifestDigest.toString();
12158                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12159                        + parsedManifest);
12160            }
12161
12162            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12163                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12164                return;
12165            }
12166        } else if (DEBUG_INSTALL) {
12167            final String parsedManifest = pkg.manifestDigest == null
12168                    ? "null" : pkg.manifestDigest.toString();
12169            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12170        }
12171
12172        // Get rid of all references to package scan path via parser.
12173        pp = null;
12174        String oldCodePath = null;
12175        boolean systemApp = false;
12176        synchronized (mPackages) {
12177            // Check if installing already existing package
12178            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12179                String oldName = mSettings.mRenamedPackages.get(pkgName);
12180                if (pkg.mOriginalPackages != null
12181                        && pkg.mOriginalPackages.contains(oldName)
12182                        && mPackages.containsKey(oldName)) {
12183                    // This package is derived from an original package,
12184                    // and this device has been updating from that original
12185                    // name.  We must continue using the original name, so
12186                    // rename the new package here.
12187                    pkg.setPackageName(oldName);
12188                    pkgName = pkg.packageName;
12189                    replace = true;
12190                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12191                            + oldName + " pkgName=" + pkgName);
12192                } else if (mPackages.containsKey(pkgName)) {
12193                    // This package, under its official name, already exists
12194                    // on the device; we should replace it.
12195                    replace = true;
12196                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12197                }
12198
12199                // Prevent apps opting out from runtime permissions
12200                if (replace) {
12201                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12202                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12203                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12204                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12205                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12206                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12207                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12208                                        + " doesn't support runtime permissions but the old"
12209                                        + " target SDK " + oldTargetSdk + " does.");
12210                        return;
12211                    }
12212                }
12213            }
12214
12215            PackageSetting ps = mSettings.mPackages.get(pkgName);
12216            if (ps != null) {
12217                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12218
12219                // Quick sanity check that we're signed correctly if updating;
12220                // we'll check this again later when scanning, but we want to
12221                // bail early here before tripping over redefined permissions.
12222                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12223                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12224                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12225                                + pkg.packageName + " upgrade keys do not match the "
12226                                + "previously installed version");
12227                        return;
12228                    }
12229                } else {
12230                    try {
12231                        verifySignaturesLP(ps, pkg);
12232                    } catch (PackageManagerException e) {
12233                        res.setError(e.error, e.getMessage());
12234                        return;
12235                    }
12236                }
12237
12238                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12239                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12240                    systemApp = (ps.pkg.applicationInfo.flags &
12241                            ApplicationInfo.FLAG_SYSTEM) != 0;
12242                }
12243                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12244            }
12245
12246            // Check whether the newly-scanned package wants to define an already-defined perm
12247            int N = pkg.permissions.size();
12248            for (int i = N-1; i >= 0; i--) {
12249                PackageParser.Permission perm = pkg.permissions.get(i);
12250                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12251                if (bp != null) {
12252                    // If the defining package is signed with our cert, it's okay.  This
12253                    // also includes the "updating the same package" case, of course.
12254                    // "updating same package" could also involve key-rotation.
12255                    final boolean sigsOk;
12256                    if (bp.sourcePackage.equals(pkg.packageName)
12257                            && (bp.packageSetting instanceof PackageSetting)
12258                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12259                                    scanFlags))) {
12260                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12261                    } else {
12262                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12263                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12264                    }
12265                    if (!sigsOk) {
12266                        // If the owning package is the system itself, we log but allow
12267                        // install to proceed; we fail the install on all other permission
12268                        // redefinitions.
12269                        if (!bp.sourcePackage.equals("android")) {
12270                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12271                                    + pkg.packageName + " attempting to redeclare permission "
12272                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12273                            res.origPermission = perm.info.name;
12274                            res.origPackage = bp.sourcePackage;
12275                            return;
12276                        } else {
12277                            Slog.w(TAG, "Package " + pkg.packageName
12278                                    + " attempting to redeclare system permission "
12279                                    + perm.info.name + "; ignoring new declaration");
12280                            pkg.permissions.remove(i);
12281                        }
12282                    }
12283                }
12284            }
12285
12286        }
12287
12288        if (systemApp && onExternal) {
12289            // Disable updates to system apps on sdcard
12290            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12291                    "Cannot install updates to system apps on sdcard");
12292            return;
12293        }
12294
12295        if (args.move != null) {
12296            // We did an in-place move, so dex is ready to roll
12297            scanFlags |= SCAN_NO_DEX;
12298            scanFlags |= SCAN_MOVE;
12299
12300            synchronized (mPackages) {
12301                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12302                if (ps == null) {
12303                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12304                            "Missing settings for moved package " + pkgName);
12305                }
12306
12307                // We moved the entire application as-is, so bring over the
12308                // previously derived ABI information.
12309                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12310                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12311            }
12312
12313        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12314            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12315            scanFlags |= SCAN_NO_DEX;
12316
12317            try {
12318                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12319                        true /* extract libs */);
12320            } catch (PackageManagerException pme) {
12321                Slog.e(TAG, "Error deriving application ABI", pme);
12322                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12323                return;
12324            }
12325
12326            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12327            int result = mPackageDexOptimizer
12328                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12329                            false /* defer */, false /* inclDependencies */);
12330            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12331                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12332                return;
12333            }
12334        }
12335
12336        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12337            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12338            return;
12339        }
12340
12341        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12342
12343        if (replace) {
12344            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12345                    installerPackageName, volumeUuid, res);
12346        } else {
12347            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12348                    args.user, installerPackageName, volumeUuid, res);
12349        }
12350        synchronized (mPackages) {
12351            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12352            if (ps != null) {
12353                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12354            }
12355        }
12356    }
12357
12358    private void startIntentFilterVerifications(int userId, boolean replacing,
12359            PackageParser.Package pkg) {
12360        if (mIntentFilterVerifierComponent == null) {
12361            Slog.w(TAG, "No IntentFilter verification will not be done as "
12362                    + "there is no IntentFilterVerifier available!");
12363            return;
12364        }
12365
12366        final int verifierUid = getPackageUid(
12367                mIntentFilterVerifierComponent.getPackageName(),
12368                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12369
12370        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12371        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12372        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12373        mHandler.sendMessage(msg);
12374    }
12375
12376    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12377            PackageParser.Package pkg) {
12378        int size = pkg.activities.size();
12379        if (size == 0) {
12380            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12381                    "No activity, so no need to verify any IntentFilter!");
12382            return;
12383        }
12384
12385        final boolean hasDomainURLs = hasDomainURLs(pkg);
12386        if (!hasDomainURLs) {
12387            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12388                    "No domain URLs, so no need to verify any IntentFilter!");
12389            return;
12390        }
12391
12392        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12393                + " if any IntentFilter from the " + size
12394                + " Activities needs verification ...");
12395
12396        int count = 0;
12397        final String packageName = pkg.packageName;
12398
12399        synchronized (mPackages) {
12400            // If this is a new install and we see that we've already run verification for this
12401            // package, we have nothing to do: it means the state was restored from backup.
12402            if (!replacing) {
12403                IntentFilterVerificationInfo ivi =
12404                        mSettings.getIntentFilterVerificationLPr(packageName);
12405                if (ivi != null) {
12406                    if (DEBUG_DOMAIN_VERIFICATION) {
12407                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12408                                + ivi.getStatusString());
12409                    }
12410                    return;
12411                }
12412            }
12413
12414            // If any filters need to be verified, then all need to be.
12415            boolean needToVerify = false;
12416            for (PackageParser.Activity a : pkg.activities) {
12417                for (ActivityIntentInfo filter : a.intents) {
12418                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12419                        if (DEBUG_DOMAIN_VERIFICATION) {
12420                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12421                        }
12422                        needToVerify = true;
12423                        break;
12424                    }
12425                }
12426            }
12427
12428            if (needToVerify) {
12429                final int verificationId = mIntentFilterVerificationToken++;
12430                for (PackageParser.Activity a : pkg.activities) {
12431                    for (ActivityIntentInfo filter : a.intents) {
12432                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12433                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12434                                    "Verification needed for IntentFilter:" + filter.toString());
12435                            mIntentFilterVerifier.addOneIntentFilterVerification(
12436                                    verifierUid, userId, verificationId, filter, packageName);
12437                            count++;
12438                        }
12439                    }
12440                }
12441            }
12442        }
12443
12444        if (count > 0) {
12445            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12446                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12447                    +  " for userId:" + userId);
12448            mIntentFilterVerifier.startVerifications(userId);
12449        } else {
12450            if (DEBUG_DOMAIN_VERIFICATION) {
12451                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12452            }
12453        }
12454    }
12455
12456    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12457        final ComponentName cn  = filter.activity.getComponentName();
12458        final String packageName = cn.getPackageName();
12459
12460        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12461                packageName);
12462        if (ivi == null) {
12463            return true;
12464        }
12465        int status = ivi.getStatus();
12466        switch (status) {
12467            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12468            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12469                return true;
12470
12471            default:
12472                // Nothing to do
12473                return false;
12474        }
12475    }
12476
12477    private static boolean isMultiArch(PackageSetting ps) {
12478        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12479    }
12480
12481    private static boolean isMultiArch(ApplicationInfo info) {
12482        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12483    }
12484
12485    private static boolean isExternal(PackageParser.Package pkg) {
12486        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12487    }
12488
12489    private static boolean isExternal(PackageSetting ps) {
12490        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12491    }
12492
12493    private static boolean isExternal(ApplicationInfo info) {
12494        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12495    }
12496
12497    private static boolean isSystemApp(PackageParser.Package pkg) {
12498        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12499    }
12500
12501    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12502        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12503    }
12504
12505    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12506        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12507    }
12508
12509    private static boolean isSystemApp(PackageSetting ps) {
12510        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12511    }
12512
12513    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12514        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12515    }
12516
12517    private int packageFlagsToInstallFlags(PackageSetting ps) {
12518        int installFlags = 0;
12519        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12520            // This existing package was an external ASEC install when we have
12521            // the external flag without a UUID
12522            installFlags |= PackageManager.INSTALL_EXTERNAL;
12523        }
12524        if (ps.isForwardLocked()) {
12525            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12526        }
12527        return installFlags;
12528    }
12529
12530    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12531        if (isExternal(pkg)) {
12532            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12533                return mSettings.getExternalVersion();
12534            } else {
12535                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12536            }
12537        } else {
12538            return mSettings.getInternalVersion();
12539        }
12540    }
12541
12542    private void deleteTempPackageFiles() {
12543        final FilenameFilter filter = new FilenameFilter() {
12544            public boolean accept(File dir, String name) {
12545                return name.startsWith("vmdl") && name.endsWith(".tmp");
12546            }
12547        };
12548        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12549            file.delete();
12550        }
12551    }
12552
12553    @Override
12554    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12555            int flags) {
12556        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12557                flags);
12558    }
12559
12560    @Override
12561    public void deletePackage(final String packageName,
12562            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12563        mContext.enforceCallingOrSelfPermission(
12564                android.Manifest.permission.DELETE_PACKAGES, null);
12565        Preconditions.checkNotNull(packageName);
12566        Preconditions.checkNotNull(observer);
12567        final int uid = Binder.getCallingUid();
12568        if (UserHandle.getUserId(uid) != userId) {
12569            mContext.enforceCallingPermission(
12570                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12571                    "deletePackage for user " + userId);
12572        }
12573        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12574            try {
12575                observer.onPackageDeleted(packageName,
12576                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12577            } catch (RemoteException re) {
12578            }
12579            return;
12580        }
12581
12582        boolean uninstallBlocked = false;
12583        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12584            int[] users = sUserManager.getUserIds();
12585            for (int i = 0; i < users.length; ++i) {
12586                if (getBlockUninstallForUser(packageName, users[i])) {
12587                    uninstallBlocked = true;
12588                    break;
12589                }
12590            }
12591        } else {
12592            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12593        }
12594        if (uninstallBlocked) {
12595            try {
12596                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12597                        null);
12598            } catch (RemoteException re) {
12599            }
12600            return;
12601        }
12602
12603        if (DEBUG_REMOVE) {
12604            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12605        }
12606        // Queue up an async operation since the package deletion may take a little while.
12607        mHandler.post(new Runnable() {
12608            public void run() {
12609                mHandler.removeCallbacks(this);
12610                final int returnCode = deletePackageX(packageName, userId, flags);
12611                if (observer != null) {
12612                    try {
12613                        observer.onPackageDeleted(packageName, returnCode, null);
12614                    } catch (RemoteException e) {
12615                        Log.i(TAG, "Observer no longer exists.");
12616                    } //end catch
12617                } //end if
12618            } //end run
12619        });
12620    }
12621
12622    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12623        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12624                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12625        try {
12626            if (dpm != null) {
12627                if (dpm.isDeviceOwner(packageName)) {
12628                    return true;
12629                }
12630                int[] users;
12631                if (userId == UserHandle.USER_ALL) {
12632                    users = sUserManager.getUserIds();
12633                } else {
12634                    users = new int[]{userId};
12635                }
12636                for (int i = 0; i < users.length; ++i) {
12637                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12638                        return true;
12639                    }
12640                }
12641            }
12642        } catch (RemoteException e) {
12643        }
12644        return false;
12645    }
12646
12647    /**
12648     *  This method is an internal method that could be get invoked either
12649     *  to delete an installed package or to clean up a failed installation.
12650     *  After deleting an installed package, a broadcast is sent to notify any
12651     *  listeners that the package has been installed. For cleaning up a failed
12652     *  installation, the broadcast is not necessary since the package's
12653     *  installation wouldn't have sent the initial broadcast either
12654     *  The key steps in deleting a package are
12655     *  deleting the package information in internal structures like mPackages,
12656     *  deleting the packages base directories through installd
12657     *  updating mSettings to reflect current status
12658     *  persisting settings for later use
12659     *  sending a broadcast if necessary
12660     */
12661    private int deletePackageX(String packageName, int userId, int flags) {
12662        final PackageRemovedInfo info = new PackageRemovedInfo();
12663        final boolean res;
12664
12665        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12666                ? UserHandle.ALL : new UserHandle(userId);
12667
12668        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12669            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12670            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12671        }
12672
12673        boolean removedForAllUsers = false;
12674        boolean systemUpdate = false;
12675
12676        // for the uninstall-updates case and restricted profiles, remember the per-
12677        // userhandle installed state
12678        int[] allUsers;
12679        boolean[] perUserInstalled;
12680        synchronized (mPackages) {
12681            PackageSetting ps = mSettings.mPackages.get(packageName);
12682            allUsers = sUserManager.getUserIds();
12683            perUserInstalled = new boolean[allUsers.length];
12684            for (int i = 0; i < allUsers.length; i++) {
12685                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12686            }
12687        }
12688
12689        synchronized (mInstallLock) {
12690            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12691            res = deletePackageLI(packageName, removeForUser,
12692                    true, allUsers, perUserInstalled,
12693                    flags | REMOVE_CHATTY, info, true);
12694            systemUpdate = info.isRemovedPackageSystemUpdate;
12695            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12696                removedForAllUsers = true;
12697            }
12698            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12699                    + " removedForAllUsers=" + removedForAllUsers);
12700        }
12701
12702        if (res) {
12703            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12704
12705            // If the removed package was a system update, the old system package
12706            // was re-enabled; we need to broadcast this information
12707            if (systemUpdate) {
12708                Bundle extras = new Bundle(1);
12709                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12710                        ? info.removedAppId : info.uid);
12711                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12712
12713                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12714                        extras, null, null, null);
12715                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12716                        extras, null, null, null);
12717                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12718                        null, packageName, null, null);
12719            }
12720        }
12721        // Force a gc here.
12722        Runtime.getRuntime().gc();
12723        // Delete the resources here after sending the broadcast to let
12724        // other processes clean up before deleting resources.
12725        if (info.args != null) {
12726            synchronized (mInstallLock) {
12727                info.args.doPostDeleteLI(true);
12728            }
12729        }
12730
12731        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12732    }
12733
12734    class PackageRemovedInfo {
12735        String removedPackage;
12736        int uid = -1;
12737        int removedAppId = -1;
12738        int[] removedUsers = null;
12739        boolean isRemovedPackageSystemUpdate = false;
12740        // Clean up resources deleted packages.
12741        InstallArgs args = null;
12742
12743        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12744            Bundle extras = new Bundle(1);
12745            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12746            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12747            if (replacing) {
12748                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12749            }
12750            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12751            if (removedPackage != null) {
12752                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12753                        extras, null, null, removedUsers);
12754                if (fullRemove && !replacing) {
12755                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12756                            extras, null, null, removedUsers);
12757                }
12758            }
12759            if (removedAppId >= 0) {
12760                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12761                        removedUsers);
12762            }
12763        }
12764    }
12765
12766    /*
12767     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12768     * flag is not set, the data directory is removed as well.
12769     * make sure this flag is set for partially installed apps. If not its meaningless to
12770     * delete a partially installed application.
12771     */
12772    private void removePackageDataLI(PackageSetting ps,
12773            int[] allUserHandles, boolean[] perUserInstalled,
12774            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12775        String packageName = ps.name;
12776        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12777        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12778        // Retrieve object to delete permissions for shared user later on
12779        final PackageSetting deletedPs;
12780        // reader
12781        synchronized (mPackages) {
12782            deletedPs = mSettings.mPackages.get(packageName);
12783            if (outInfo != null) {
12784                outInfo.removedPackage = packageName;
12785                outInfo.removedUsers = deletedPs != null
12786                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12787                        : null;
12788            }
12789        }
12790        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12791            removeDataDirsLI(ps.volumeUuid, packageName);
12792            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12793        }
12794        // writer
12795        synchronized (mPackages) {
12796            if (deletedPs != null) {
12797                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12798                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12799                    clearDefaultBrowserIfNeeded(packageName);
12800                    if (outInfo != null) {
12801                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12802                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12803                    }
12804                    updatePermissionsLPw(deletedPs.name, null, 0);
12805                    if (deletedPs.sharedUser != null) {
12806                        // Remove permissions associated with package. Since runtime
12807                        // permissions are per user we have to kill the removed package
12808                        // or packages running under the shared user of the removed
12809                        // package if revoking the permissions requested only by the removed
12810                        // package is successful and this causes a change in gids.
12811                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12812                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12813                                    userId);
12814                            if (userIdToKill == UserHandle.USER_ALL
12815                                    || userIdToKill >= UserHandle.USER_OWNER) {
12816                                // If gids changed for this user, kill all affected packages.
12817                                mHandler.post(new Runnable() {
12818                                    @Override
12819                                    public void run() {
12820                                        // This has to happen with no lock held.
12821                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12822                                                KILL_APP_REASON_GIDS_CHANGED);
12823                                    }
12824                                });
12825                                break;
12826                            }
12827                        }
12828                    }
12829                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12830                }
12831                // make sure to preserve per-user disabled state if this removal was just
12832                // a downgrade of a system app to the factory package
12833                if (allUserHandles != null && perUserInstalled != null) {
12834                    if (DEBUG_REMOVE) {
12835                        Slog.d(TAG, "Propagating install state across downgrade");
12836                    }
12837                    for (int i = 0; i < allUserHandles.length; i++) {
12838                        if (DEBUG_REMOVE) {
12839                            Slog.d(TAG, "    user " + allUserHandles[i]
12840                                    + " => " + perUserInstalled[i]);
12841                        }
12842                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12843                    }
12844                }
12845            }
12846            // can downgrade to reader
12847            if (writeSettings) {
12848                // Save settings now
12849                mSettings.writeLPr();
12850            }
12851        }
12852        if (outInfo != null) {
12853            // A user ID was deleted here. Go through all users and remove it
12854            // from KeyStore.
12855            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12856        }
12857    }
12858
12859    static boolean locationIsPrivileged(File path) {
12860        try {
12861            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12862                    .getCanonicalPath();
12863            return path.getCanonicalPath().startsWith(privilegedAppDir);
12864        } catch (IOException e) {
12865            Slog.e(TAG, "Unable to access code path " + path);
12866        }
12867        return false;
12868    }
12869
12870    /*
12871     * Tries to delete system package.
12872     */
12873    private boolean deleteSystemPackageLI(PackageSetting newPs,
12874            int[] allUserHandles, boolean[] perUserInstalled,
12875            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12876        final boolean applyUserRestrictions
12877                = (allUserHandles != null) && (perUserInstalled != null);
12878        PackageSetting disabledPs = null;
12879        // Confirm if the system package has been updated
12880        // An updated system app can be deleted. This will also have to restore
12881        // the system pkg from system partition
12882        // reader
12883        synchronized (mPackages) {
12884            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12885        }
12886        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12887                + " disabledPs=" + disabledPs);
12888        if (disabledPs == null) {
12889            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12890            return false;
12891        } else if (DEBUG_REMOVE) {
12892            Slog.d(TAG, "Deleting system pkg from data partition");
12893        }
12894        if (DEBUG_REMOVE) {
12895            if (applyUserRestrictions) {
12896                Slog.d(TAG, "Remembering install states:");
12897                for (int i = 0; i < allUserHandles.length; i++) {
12898                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12899                }
12900            }
12901        }
12902        // Delete the updated package
12903        outInfo.isRemovedPackageSystemUpdate = true;
12904        if (disabledPs.versionCode < newPs.versionCode) {
12905            // Delete data for downgrades
12906            flags &= ~PackageManager.DELETE_KEEP_DATA;
12907        } else {
12908            // Preserve data by setting flag
12909            flags |= PackageManager.DELETE_KEEP_DATA;
12910        }
12911        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12912                allUserHandles, perUserInstalled, outInfo, writeSettings);
12913        if (!ret) {
12914            return false;
12915        }
12916        // writer
12917        synchronized (mPackages) {
12918            // Reinstate the old system package
12919            mSettings.enableSystemPackageLPw(newPs.name);
12920            // Remove any native libraries from the upgraded package.
12921            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12922        }
12923        // Install the system package
12924        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12925        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12926        if (locationIsPrivileged(disabledPs.codePath)) {
12927            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12928        }
12929
12930        final PackageParser.Package newPkg;
12931        try {
12932            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12933        } catch (PackageManagerException e) {
12934            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12935            return false;
12936        }
12937
12938        // writer
12939        synchronized (mPackages) {
12940            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12941
12942            updatePermissionsLPw(newPkg.packageName, newPkg,
12943                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12944
12945            if (applyUserRestrictions) {
12946                if (DEBUG_REMOVE) {
12947                    Slog.d(TAG, "Propagating install state across reinstall");
12948                }
12949                for (int i = 0; i < allUserHandles.length; i++) {
12950                    if (DEBUG_REMOVE) {
12951                        Slog.d(TAG, "    user " + allUserHandles[i]
12952                                + " => " + perUserInstalled[i]);
12953                    }
12954                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12955
12956                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12957                }
12958                // Regardless of writeSettings we need to ensure that this restriction
12959                // state propagation is persisted
12960                mSettings.writeAllUsersPackageRestrictionsLPr();
12961            }
12962            // can downgrade to reader here
12963            if (writeSettings) {
12964                mSettings.writeLPr();
12965            }
12966        }
12967        return true;
12968    }
12969
12970    private boolean deleteInstalledPackageLI(PackageSetting ps,
12971            boolean deleteCodeAndResources, int flags,
12972            int[] allUserHandles, boolean[] perUserInstalled,
12973            PackageRemovedInfo outInfo, boolean writeSettings) {
12974        if (outInfo != null) {
12975            outInfo.uid = ps.appId;
12976        }
12977
12978        // Delete package data from internal structures and also remove data if flag is set
12979        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12980
12981        // Delete application code and resources
12982        if (deleteCodeAndResources && (outInfo != null)) {
12983            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12984                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12985            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12986        }
12987        return true;
12988    }
12989
12990    @Override
12991    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12992            int userId) {
12993        mContext.enforceCallingOrSelfPermission(
12994                android.Manifest.permission.DELETE_PACKAGES, null);
12995        synchronized (mPackages) {
12996            PackageSetting ps = mSettings.mPackages.get(packageName);
12997            if (ps == null) {
12998                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12999                return false;
13000            }
13001            if (!ps.getInstalled(userId)) {
13002                // Can't block uninstall for an app that is not installed or enabled.
13003                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13004                return false;
13005            }
13006            ps.setBlockUninstall(blockUninstall, userId);
13007            mSettings.writePackageRestrictionsLPr(userId);
13008        }
13009        return true;
13010    }
13011
13012    @Override
13013    public boolean getBlockUninstallForUser(String packageName, int userId) {
13014        synchronized (mPackages) {
13015            PackageSetting ps = mSettings.mPackages.get(packageName);
13016            if (ps == null) {
13017                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13018                return false;
13019            }
13020            return ps.getBlockUninstall(userId);
13021        }
13022    }
13023
13024    /*
13025     * This method handles package deletion in general
13026     */
13027    private boolean deletePackageLI(String packageName, UserHandle user,
13028            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13029            int flags, PackageRemovedInfo outInfo,
13030            boolean writeSettings) {
13031        if (packageName == null) {
13032            Slog.w(TAG, "Attempt to delete null packageName.");
13033            return false;
13034        }
13035        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13036        PackageSetting ps;
13037        boolean dataOnly = false;
13038        int removeUser = -1;
13039        int appId = -1;
13040        synchronized (mPackages) {
13041            ps = mSettings.mPackages.get(packageName);
13042            if (ps == null) {
13043                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13044                return false;
13045            }
13046            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13047                    && user.getIdentifier() != UserHandle.USER_ALL) {
13048                // The caller is asking that the package only be deleted for a single
13049                // user.  To do this, we just mark its uninstalled state and delete
13050                // its data.  If this is a system app, we only allow this to happen if
13051                // they have set the special DELETE_SYSTEM_APP which requests different
13052                // semantics than normal for uninstalling system apps.
13053                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13054                ps.setUserState(user.getIdentifier(),
13055                        COMPONENT_ENABLED_STATE_DEFAULT,
13056                        false, //installed
13057                        true,  //stopped
13058                        true,  //notLaunched
13059                        false, //hidden
13060                        null, null, null,
13061                        false, // blockUninstall
13062                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13063                if (!isSystemApp(ps)) {
13064                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13065                        // Other user still have this package installed, so all
13066                        // we need to do is clear this user's data and save that
13067                        // it is uninstalled.
13068                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13069                        removeUser = user.getIdentifier();
13070                        appId = ps.appId;
13071                        scheduleWritePackageRestrictionsLocked(removeUser);
13072                    } else {
13073                        // We need to set it back to 'installed' so the uninstall
13074                        // broadcasts will be sent correctly.
13075                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13076                        ps.setInstalled(true, user.getIdentifier());
13077                    }
13078                } else {
13079                    // This is a system app, so we assume that the
13080                    // other users still have this package installed, so all
13081                    // we need to do is clear this user's data and save that
13082                    // it is uninstalled.
13083                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13084                    removeUser = user.getIdentifier();
13085                    appId = ps.appId;
13086                    scheduleWritePackageRestrictionsLocked(removeUser);
13087                }
13088            }
13089        }
13090
13091        if (removeUser >= 0) {
13092            // From above, we determined that we are deleting this only
13093            // for a single user.  Continue the work here.
13094            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13095            if (outInfo != null) {
13096                outInfo.removedPackage = packageName;
13097                outInfo.removedAppId = appId;
13098                outInfo.removedUsers = new int[] {removeUser};
13099            }
13100            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13101            removeKeystoreDataIfNeeded(removeUser, appId);
13102            schedulePackageCleaning(packageName, removeUser, false);
13103            synchronized (mPackages) {
13104                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13105                    scheduleWritePackageRestrictionsLocked(removeUser);
13106                }
13107                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13108            }
13109            return true;
13110        }
13111
13112        if (dataOnly) {
13113            // Delete application data first
13114            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13115            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13116            return true;
13117        }
13118
13119        boolean ret = false;
13120        if (isSystemApp(ps)) {
13121            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13122            // When an updated system application is deleted we delete the existing resources as well and
13123            // fall back to existing code in system partition
13124            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13125                    flags, outInfo, writeSettings);
13126        } else {
13127            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13128            // Kill application pre-emptively especially for apps on sd.
13129            killApplication(packageName, ps.appId, "uninstall pkg");
13130            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13131                    allUserHandles, perUserInstalled,
13132                    outInfo, writeSettings);
13133        }
13134
13135        return ret;
13136    }
13137
13138    private final class ClearStorageConnection implements ServiceConnection {
13139        IMediaContainerService mContainerService;
13140
13141        @Override
13142        public void onServiceConnected(ComponentName name, IBinder service) {
13143            synchronized (this) {
13144                mContainerService = IMediaContainerService.Stub.asInterface(service);
13145                notifyAll();
13146            }
13147        }
13148
13149        @Override
13150        public void onServiceDisconnected(ComponentName name) {
13151        }
13152    }
13153
13154    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13155        final boolean mounted;
13156        if (Environment.isExternalStorageEmulated()) {
13157            mounted = true;
13158        } else {
13159            final String status = Environment.getExternalStorageState();
13160
13161            mounted = status.equals(Environment.MEDIA_MOUNTED)
13162                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13163        }
13164
13165        if (!mounted) {
13166            return;
13167        }
13168
13169        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13170        int[] users;
13171        if (userId == UserHandle.USER_ALL) {
13172            users = sUserManager.getUserIds();
13173        } else {
13174            users = new int[] { userId };
13175        }
13176        final ClearStorageConnection conn = new ClearStorageConnection();
13177        if (mContext.bindServiceAsUser(
13178                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13179            try {
13180                for (int curUser : users) {
13181                    long timeout = SystemClock.uptimeMillis() + 5000;
13182                    synchronized (conn) {
13183                        long now = SystemClock.uptimeMillis();
13184                        while (conn.mContainerService == null && now < timeout) {
13185                            try {
13186                                conn.wait(timeout - now);
13187                            } catch (InterruptedException e) {
13188                            }
13189                        }
13190                    }
13191                    if (conn.mContainerService == null) {
13192                        return;
13193                    }
13194
13195                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13196                    clearDirectory(conn.mContainerService,
13197                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13198                    if (allData) {
13199                        clearDirectory(conn.mContainerService,
13200                                userEnv.buildExternalStorageAppDataDirs(packageName));
13201                        clearDirectory(conn.mContainerService,
13202                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13203                    }
13204                }
13205            } finally {
13206                mContext.unbindService(conn);
13207            }
13208        }
13209    }
13210
13211    @Override
13212    public void clearApplicationUserData(final String packageName,
13213            final IPackageDataObserver observer, final int userId) {
13214        mContext.enforceCallingOrSelfPermission(
13215                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13216        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13217        // Queue up an async operation since the package deletion may take a little while.
13218        mHandler.post(new Runnable() {
13219            public void run() {
13220                mHandler.removeCallbacks(this);
13221                final boolean succeeded;
13222                synchronized (mInstallLock) {
13223                    succeeded = clearApplicationUserDataLI(packageName, userId);
13224                }
13225                clearExternalStorageDataSync(packageName, userId, true);
13226                if (succeeded) {
13227                    // invoke DeviceStorageMonitor's update method to clear any notifications
13228                    DeviceStorageMonitorInternal
13229                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13230                    if (dsm != null) {
13231                        dsm.checkMemory();
13232                    }
13233                }
13234                if(observer != null) {
13235                    try {
13236                        observer.onRemoveCompleted(packageName, succeeded);
13237                    } catch (RemoteException e) {
13238                        Log.i(TAG, "Observer no longer exists.");
13239                    }
13240                } //end if observer
13241            } //end run
13242        });
13243    }
13244
13245    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13246        if (packageName == null) {
13247            Slog.w(TAG, "Attempt to delete null packageName.");
13248            return false;
13249        }
13250
13251        // Try finding details about the requested package
13252        PackageParser.Package pkg;
13253        synchronized (mPackages) {
13254            pkg = mPackages.get(packageName);
13255            if (pkg == null) {
13256                final PackageSetting ps = mSettings.mPackages.get(packageName);
13257                if (ps != null) {
13258                    pkg = ps.pkg;
13259                }
13260            }
13261
13262            if (pkg == null) {
13263                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13264                return false;
13265            }
13266
13267            PackageSetting ps = (PackageSetting) pkg.mExtras;
13268            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13269        }
13270
13271        // Always delete data directories for package, even if we found no other
13272        // record of app. This helps users recover from UID mismatches without
13273        // resorting to a full data wipe.
13274        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13275        if (retCode < 0) {
13276            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13277            return false;
13278        }
13279
13280        final int appId = pkg.applicationInfo.uid;
13281        removeKeystoreDataIfNeeded(userId, appId);
13282
13283        // Create a native library symlink only if we have native libraries
13284        // and if the native libraries are 32 bit libraries. We do not provide
13285        // this symlink for 64 bit libraries.
13286        if (pkg.applicationInfo.primaryCpuAbi != null &&
13287                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13288            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13289            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13290                    nativeLibPath, userId) < 0) {
13291                Slog.w(TAG, "Failed linking native library dir");
13292                return false;
13293            }
13294        }
13295
13296        return true;
13297    }
13298
13299    /**
13300     * Reverts user permission state changes (permissions and flags) in
13301     * all packages for a given user.
13302     *
13303     * @param userId The device user for which to do a reset.
13304     */
13305    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13306        final int packageCount = mPackages.size();
13307        for (int i = 0; i < packageCount; i++) {
13308            PackageParser.Package pkg = mPackages.valueAt(i);
13309            PackageSetting ps = (PackageSetting) pkg.mExtras;
13310            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13311        }
13312    }
13313
13314    /**
13315     * Reverts user permission state changes (permissions and flags).
13316     *
13317     * @param ps The package for which to reset.
13318     * @param userId The device user for which to do a reset.
13319     */
13320    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13321            final PackageSetting ps, final int userId) {
13322        if (ps.pkg == null) {
13323            return;
13324        }
13325
13326        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13327                | FLAG_PERMISSION_USER_FIXED
13328                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13329
13330        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13331                | FLAG_PERMISSION_POLICY_FIXED;
13332
13333        boolean writeInstallPermissions = false;
13334        boolean writeRuntimePermissions = false;
13335
13336        final int permissionCount = ps.pkg.requestedPermissions.size();
13337        for (int i = 0; i < permissionCount; i++) {
13338            String permission = ps.pkg.requestedPermissions.get(i);
13339
13340            BasePermission bp = mSettings.mPermissions.get(permission);
13341            if (bp == null) {
13342                continue;
13343            }
13344
13345            // If shared user we just reset the state to which only this app contributed.
13346            if (ps.sharedUser != null) {
13347                boolean used = false;
13348                final int packageCount = ps.sharedUser.packages.size();
13349                for (int j = 0; j < packageCount; j++) {
13350                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13351                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13352                            && pkg.pkg.requestedPermissions.contains(permission)) {
13353                        used = true;
13354                        break;
13355                    }
13356                }
13357                if (used) {
13358                    continue;
13359                }
13360            }
13361
13362            PermissionsState permissionsState = ps.getPermissionsState();
13363
13364            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13365
13366            // Always clear the user settable flags.
13367            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13368                    bp.name) != null;
13369            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13370                if (hasInstallState) {
13371                    writeInstallPermissions = true;
13372                } else {
13373                    writeRuntimePermissions = true;
13374                }
13375            }
13376
13377            // Below is only runtime permission handling.
13378            if (!bp.isRuntime()) {
13379                continue;
13380            }
13381
13382            // Never clobber system or policy.
13383            if ((oldFlags & policyOrSystemFlags) != 0) {
13384                continue;
13385            }
13386
13387            // If this permission was granted by default, make sure it is.
13388            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13389                if (permissionsState.grantRuntimePermission(bp, userId)
13390                        != PERMISSION_OPERATION_FAILURE) {
13391                    writeRuntimePermissions = true;
13392                }
13393            } else {
13394                // Otherwise, reset the permission.
13395                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13396                switch (revokeResult) {
13397                    case PERMISSION_OPERATION_SUCCESS: {
13398                        writeRuntimePermissions = true;
13399                    } break;
13400
13401                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13402                        writeRuntimePermissions = true;
13403                        // If gids changed for this user, kill all affected packages.
13404                        mHandler.post(new Runnable() {
13405                            @Override
13406                            public void run() {
13407                                // This has to happen with no lock held.
13408                                killSettingPackagesForUser(ps, userId,
13409                                        KILL_APP_REASON_GIDS_CHANGED);
13410                            }
13411                        });
13412                    } break;
13413                }
13414            }
13415        }
13416
13417        // Synchronously write as we are taking permissions away.
13418        if (writeRuntimePermissions) {
13419            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13420        }
13421
13422        // Synchronously write as we are taking permissions away.
13423        if (writeInstallPermissions) {
13424            mSettings.writeLPr();
13425        }
13426    }
13427
13428    /**
13429     * Remove entries from the keystore daemon. Will only remove it if the
13430     * {@code appId} is valid.
13431     */
13432    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13433        if (appId < 0) {
13434            return;
13435        }
13436
13437        final KeyStore keyStore = KeyStore.getInstance();
13438        if (keyStore != null) {
13439            if (userId == UserHandle.USER_ALL) {
13440                for (final int individual : sUserManager.getUserIds()) {
13441                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13442                }
13443            } else {
13444                keyStore.clearUid(UserHandle.getUid(userId, appId));
13445            }
13446        } else {
13447            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13448        }
13449    }
13450
13451    @Override
13452    public void deleteApplicationCacheFiles(final String packageName,
13453            final IPackageDataObserver observer) {
13454        mContext.enforceCallingOrSelfPermission(
13455                android.Manifest.permission.DELETE_CACHE_FILES, null);
13456        // Queue up an async operation since the package deletion may take a little while.
13457        final int userId = UserHandle.getCallingUserId();
13458        mHandler.post(new Runnable() {
13459            public void run() {
13460                mHandler.removeCallbacks(this);
13461                final boolean succeded;
13462                synchronized (mInstallLock) {
13463                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13464                }
13465                clearExternalStorageDataSync(packageName, userId, false);
13466                if (observer != null) {
13467                    try {
13468                        observer.onRemoveCompleted(packageName, succeded);
13469                    } catch (RemoteException e) {
13470                        Log.i(TAG, "Observer no longer exists.");
13471                    }
13472                } //end if observer
13473            } //end run
13474        });
13475    }
13476
13477    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13478        if (packageName == null) {
13479            Slog.w(TAG, "Attempt to delete null packageName.");
13480            return false;
13481        }
13482        PackageParser.Package p;
13483        synchronized (mPackages) {
13484            p = mPackages.get(packageName);
13485        }
13486        if (p == null) {
13487            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13488            return false;
13489        }
13490        final ApplicationInfo applicationInfo = p.applicationInfo;
13491        if (applicationInfo == null) {
13492            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13493            return false;
13494        }
13495        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13496        if (retCode < 0) {
13497            Slog.w(TAG, "Couldn't remove cache files for package: "
13498                       + packageName + " u" + userId);
13499            return false;
13500        }
13501        return true;
13502    }
13503
13504    @Override
13505    public void getPackageSizeInfo(final String packageName, int userHandle,
13506            final IPackageStatsObserver observer) {
13507        mContext.enforceCallingOrSelfPermission(
13508                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13509        if (packageName == null) {
13510            throw new IllegalArgumentException("Attempt to get size of null packageName");
13511        }
13512
13513        PackageStats stats = new PackageStats(packageName, userHandle);
13514
13515        /*
13516         * Queue up an async operation since the package measurement may take a
13517         * little while.
13518         */
13519        Message msg = mHandler.obtainMessage(INIT_COPY);
13520        msg.obj = new MeasureParams(stats, observer);
13521        mHandler.sendMessage(msg);
13522    }
13523
13524    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13525            PackageStats pStats) {
13526        if (packageName == null) {
13527            Slog.w(TAG, "Attempt to get size of null packageName.");
13528            return false;
13529        }
13530        PackageParser.Package p;
13531        boolean dataOnly = false;
13532        String libDirRoot = null;
13533        String asecPath = null;
13534        PackageSetting ps = null;
13535        synchronized (mPackages) {
13536            p = mPackages.get(packageName);
13537            ps = mSettings.mPackages.get(packageName);
13538            if(p == null) {
13539                dataOnly = true;
13540                if((ps == null) || (ps.pkg == null)) {
13541                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13542                    return false;
13543                }
13544                p = ps.pkg;
13545            }
13546            if (ps != null) {
13547                libDirRoot = ps.legacyNativeLibraryPathString;
13548            }
13549            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13550                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13551                if (secureContainerId != null) {
13552                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13553                }
13554            }
13555        }
13556        String publicSrcDir = null;
13557        if(!dataOnly) {
13558            final ApplicationInfo applicationInfo = p.applicationInfo;
13559            if (applicationInfo == null) {
13560                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13561                return false;
13562            }
13563            if (p.isForwardLocked()) {
13564                publicSrcDir = applicationInfo.getBaseResourcePath();
13565            }
13566        }
13567        // TODO: extend to measure size of split APKs
13568        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13569        // not just the first level.
13570        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13571        // just the primary.
13572        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13573        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13574                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13575        if (res < 0) {
13576            return false;
13577        }
13578
13579        // Fix-up for forward-locked applications in ASEC containers.
13580        if (!isExternal(p)) {
13581            pStats.codeSize += pStats.externalCodeSize;
13582            pStats.externalCodeSize = 0L;
13583        }
13584
13585        return true;
13586    }
13587
13588
13589    @Override
13590    public void addPackageToPreferred(String packageName) {
13591        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13592    }
13593
13594    @Override
13595    public void removePackageFromPreferred(String packageName) {
13596        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13597    }
13598
13599    @Override
13600    public List<PackageInfo> getPreferredPackages(int flags) {
13601        return new ArrayList<PackageInfo>();
13602    }
13603
13604    private int getUidTargetSdkVersionLockedLPr(int uid) {
13605        Object obj = mSettings.getUserIdLPr(uid);
13606        if (obj instanceof SharedUserSetting) {
13607            final SharedUserSetting sus = (SharedUserSetting) obj;
13608            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13609            final Iterator<PackageSetting> it = sus.packages.iterator();
13610            while (it.hasNext()) {
13611                final PackageSetting ps = it.next();
13612                if (ps.pkg != null) {
13613                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13614                    if (v < vers) vers = v;
13615                }
13616            }
13617            return vers;
13618        } else if (obj instanceof PackageSetting) {
13619            final PackageSetting ps = (PackageSetting) obj;
13620            if (ps.pkg != null) {
13621                return ps.pkg.applicationInfo.targetSdkVersion;
13622            }
13623        }
13624        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13625    }
13626
13627    @Override
13628    public void addPreferredActivity(IntentFilter filter, int match,
13629            ComponentName[] set, ComponentName activity, int userId) {
13630        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13631                "Adding preferred");
13632    }
13633
13634    private void addPreferredActivityInternal(IntentFilter filter, int match,
13635            ComponentName[] set, ComponentName activity, boolean always, int userId,
13636            String opname) {
13637        // writer
13638        int callingUid = Binder.getCallingUid();
13639        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13640        if (filter.countActions() == 0) {
13641            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13642            return;
13643        }
13644        synchronized (mPackages) {
13645            if (mContext.checkCallingOrSelfPermission(
13646                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13647                    != PackageManager.PERMISSION_GRANTED) {
13648                if (getUidTargetSdkVersionLockedLPr(callingUid)
13649                        < Build.VERSION_CODES.FROYO) {
13650                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13651                            + callingUid);
13652                    return;
13653                }
13654                mContext.enforceCallingOrSelfPermission(
13655                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13656            }
13657
13658            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13659            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13660                    + userId + ":");
13661            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13662            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13663            scheduleWritePackageRestrictionsLocked(userId);
13664        }
13665    }
13666
13667    @Override
13668    public void replacePreferredActivity(IntentFilter filter, int match,
13669            ComponentName[] set, ComponentName activity, int userId) {
13670        if (filter.countActions() != 1) {
13671            throw new IllegalArgumentException(
13672                    "replacePreferredActivity expects filter to have only 1 action.");
13673        }
13674        if (filter.countDataAuthorities() != 0
13675                || filter.countDataPaths() != 0
13676                || filter.countDataSchemes() > 1
13677                || filter.countDataTypes() != 0) {
13678            throw new IllegalArgumentException(
13679                    "replacePreferredActivity expects filter to have no data authorities, " +
13680                    "paths, or types; and at most one scheme.");
13681        }
13682
13683        final int callingUid = Binder.getCallingUid();
13684        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13685        synchronized (mPackages) {
13686            if (mContext.checkCallingOrSelfPermission(
13687                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13688                    != PackageManager.PERMISSION_GRANTED) {
13689                if (getUidTargetSdkVersionLockedLPr(callingUid)
13690                        < Build.VERSION_CODES.FROYO) {
13691                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13692                            + Binder.getCallingUid());
13693                    return;
13694                }
13695                mContext.enforceCallingOrSelfPermission(
13696                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13697            }
13698
13699            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13700            if (pir != null) {
13701                // Get all of the existing entries that exactly match this filter.
13702                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13703                if (existing != null && existing.size() == 1) {
13704                    PreferredActivity cur = existing.get(0);
13705                    if (DEBUG_PREFERRED) {
13706                        Slog.i(TAG, "Checking replace of preferred:");
13707                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13708                        if (!cur.mPref.mAlways) {
13709                            Slog.i(TAG, "  -- CUR; not mAlways!");
13710                        } else {
13711                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13712                            Slog.i(TAG, "  -- CUR: mSet="
13713                                    + Arrays.toString(cur.mPref.mSetComponents));
13714                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13715                            Slog.i(TAG, "  -- NEW: mMatch="
13716                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13717                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13718                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13719                        }
13720                    }
13721                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13722                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13723                            && cur.mPref.sameSet(set)) {
13724                        // Setting the preferred activity to what it happens to be already
13725                        if (DEBUG_PREFERRED) {
13726                            Slog.i(TAG, "Replacing with same preferred activity "
13727                                    + cur.mPref.mShortComponent + " for user "
13728                                    + userId + ":");
13729                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13730                        }
13731                        return;
13732                    }
13733                }
13734
13735                if (existing != null) {
13736                    if (DEBUG_PREFERRED) {
13737                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13738                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13739                    }
13740                    for (int i = 0; i < existing.size(); i++) {
13741                        PreferredActivity pa = existing.get(i);
13742                        if (DEBUG_PREFERRED) {
13743                            Slog.i(TAG, "Removing existing preferred activity "
13744                                    + pa.mPref.mComponent + ":");
13745                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13746                        }
13747                        pir.removeFilter(pa);
13748                    }
13749                }
13750            }
13751            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13752                    "Replacing preferred");
13753        }
13754    }
13755
13756    @Override
13757    public void clearPackagePreferredActivities(String packageName) {
13758        final int uid = Binder.getCallingUid();
13759        // writer
13760        synchronized (mPackages) {
13761            PackageParser.Package pkg = mPackages.get(packageName);
13762            if (pkg == null || pkg.applicationInfo.uid != uid) {
13763                if (mContext.checkCallingOrSelfPermission(
13764                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13765                        != PackageManager.PERMISSION_GRANTED) {
13766                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13767                            < Build.VERSION_CODES.FROYO) {
13768                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13769                                + Binder.getCallingUid());
13770                        return;
13771                    }
13772                    mContext.enforceCallingOrSelfPermission(
13773                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13774                }
13775            }
13776
13777            int user = UserHandle.getCallingUserId();
13778            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13779                scheduleWritePackageRestrictionsLocked(user);
13780            }
13781        }
13782    }
13783
13784    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13785    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13786        ArrayList<PreferredActivity> removed = null;
13787        boolean changed = false;
13788        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13789            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13790            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13791            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13792                continue;
13793            }
13794            Iterator<PreferredActivity> it = pir.filterIterator();
13795            while (it.hasNext()) {
13796                PreferredActivity pa = it.next();
13797                // Mark entry for removal only if it matches the package name
13798                // and the entry is of type "always".
13799                if (packageName == null ||
13800                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13801                                && pa.mPref.mAlways)) {
13802                    if (removed == null) {
13803                        removed = new ArrayList<PreferredActivity>();
13804                    }
13805                    removed.add(pa);
13806                }
13807            }
13808            if (removed != null) {
13809                for (int j=0; j<removed.size(); j++) {
13810                    PreferredActivity pa = removed.get(j);
13811                    pir.removeFilter(pa);
13812                }
13813                changed = true;
13814            }
13815        }
13816        return changed;
13817    }
13818
13819    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13820    private void clearIntentFilterVerificationsLPw(int userId) {
13821        final int packageCount = mPackages.size();
13822        for (int i = 0; i < packageCount; i++) {
13823            PackageParser.Package pkg = mPackages.valueAt(i);
13824            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13825        }
13826    }
13827
13828    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13829    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13830        if (userId == UserHandle.USER_ALL) {
13831            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13832                    sUserManager.getUserIds())) {
13833                for (int oneUserId : sUserManager.getUserIds()) {
13834                    scheduleWritePackageRestrictionsLocked(oneUserId);
13835                }
13836            }
13837        } else {
13838            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13839                scheduleWritePackageRestrictionsLocked(userId);
13840            }
13841        }
13842    }
13843
13844    void clearDefaultBrowserIfNeeded(String packageName) {
13845        for (int oneUserId : sUserManager.getUserIds()) {
13846            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13847            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13848            if (packageName.equals(defaultBrowserPackageName)) {
13849                setDefaultBrowserPackageName(null, oneUserId);
13850            }
13851        }
13852    }
13853
13854    @Override
13855    public void resetApplicationPreferences(int userId) {
13856        mContext.enforceCallingOrSelfPermission(
13857                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13858        // writer
13859        synchronized (mPackages) {
13860            final long identity = Binder.clearCallingIdentity();
13861            try {
13862                clearPackagePreferredActivitiesLPw(null, userId);
13863                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13864                // TODO: We have to reset the default SMS and Phone. This requires
13865                // significant refactoring to keep all default apps in the package
13866                // manager (cleaner but more work) or have the services provide
13867                // callbacks to the package manager to request a default app reset.
13868                applyFactoryDefaultBrowserLPw(userId);
13869                clearIntentFilterVerificationsLPw(userId);
13870                primeDomainVerificationsLPw(userId);
13871                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13872                scheduleWritePackageRestrictionsLocked(userId);
13873            } finally {
13874                Binder.restoreCallingIdentity(identity);
13875            }
13876        }
13877    }
13878
13879    @Override
13880    public int getPreferredActivities(List<IntentFilter> outFilters,
13881            List<ComponentName> outActivities, String packageName) {
13882
13883        int num = 0;
13884        final int userId = UserHandle.getCallingUserId();
13885        // reader
13886        synchronized (mPackages) {
13887            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13888            if (pir != null) {
13889                final Iterator<PreferredActivity> it = pir.filterIterator();
13890                while (it.hasNext()) {
13891                    final PreferredActivity pa = it.next();
13892                    if (packageName == null
13893                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13894                                    && pa.mPref.mAlways)) {
13895                        if (outFilters != null) {
13896                            outFilters.add(new IntentFilter(pa));
13897                        }
13898                        if (outActivities != null) {
13899                            outActivities.add(pa.mPref.mComponent);
13900                        }
13901                    }
13902                }
13903            }
13904        }
13905
13906        return num;
13907    }
13908
13909    @Override
13910    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13911            int userId) {
13912        int callingUid = Binder.getCallingUid();
13913        if (callingUid != Process.SYSTEM_UID) {
13914            throw new SecurityException(
13915                    "addPersistentPreferredActivity can only be run by the system");
13916        }
13917        if (filter.countActions() == 0) {
13918            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13919            return;
13920        }
13921        synchronized (mPackages) {
13922            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13923                    " :");
13924            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13925            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13926                    new PersistentPreferredActivity(filter, activity));
13927            scheduleWritePackageRestrictionsLocked(userId);
13928        }
13929    }
13930
13931    @Override
13932    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13933        int callingUid = Binder.getCallingUid();
13934        if (callingUid != Process.SYSTEM_UID) {
13935            throw new SecurityException(
13936                    "clearPackagePersistentPreferredActivities can only be run by the system");
13937        }
13938        ArrayList<PersistentPreferredActivity> removed = null;
13939        boolean changed = false;
13940        synchronized (mPackages) {
13941            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13942                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13943                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13944                        .valueAt(i);
13945                if (userId != thisUserId) {
13946                    continue;
13947                }
13948                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13949                while (it.hasNext()) {
13950                    PersistentPreferredActivity ppa = it.next();
13951                    // Mark entry for removal only if it matches the package name.
13952                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13953                        if (removed == null) {
13954                            removed = new ArrayList<PersistentPreferredActivity>();
13955                        }
13956                        removed.add(ppa);
13957                    }
13958                }
13959                if (removed != null) {
13960                    for (int j=0; j<removed.size(); j++) {
13961                        PersistentPreferredActivity ppa = removed.get(j);
13962                        ppir.removeFilter(ppa);
13963                    }
13964                    changed = true;
13965                }
13966            }
13967
13968            if (changed) {
13969                scheduleWritePackageRestrictionsLocked(userId);
13970            }
13971        }
13972    }
13973
13974    /**
13975     * Common machinery for picking apart a restored XML blob and passing
13976     * it to a caller-supplied functor to be applied to the running system.
13977     */
13978    private void restoreFromXml(XmlPullParser parser, int userId,
13979            String expectedStartTag, BlobXmlRestorer functor)
13980            throws IOException, XmlPullParserException {
13981        int type;
13982        while ((type = parser.next()) != XmlPullParser.START_TAG
13983                && type != XmlPullParser.END_DOCUMENT) {
13984        }
13985        if (type != XmlPullParser.START_TAG) {
13986            // oops didn't find a start tag?!
13987            if (DEBUG_BACKUP) {
13988                Slog.e(TAG, "Didn't find start tag during restore");
13989            }
13990            return;
13991        }
13992
13993        // this is supposed to be TAG_PREFERRED_BACKUP
13994        if (!expectedStartTag.equals(parser.getName())) {
13995            if (DEBUG_BACKUP) {
13996                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13997            }
13998            return;
13999        }
14000
14001        // skip interfering stuff, then we're aligned with the backing implementation
14002        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14003        functor.apply(parser, userId);
14004    }
14005
14006    private interface BlobXmlRestorer {
14007        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14008    }
14009
14010    /**
14011     * Non-Binder method, support for the backup/restore mechanism: write the
14012     * full set of preferred activities in its canonical XML format.  Returns the
14013     * XML output as a byte array, or null if there is none.
14014     */
14015    @Override
14016    public byte[] getPreferredActivityBackup(int userId) {
14017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14018            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14019        }
14020
14021        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14022        try {
14023            final XmlSerializer serializer = new FastXmlSerializer();
14024            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14025            serializer.startDocument(null, true);
14026            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14027
14028            synchronized (mPackages) {
14029                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14030            }
14031
14032            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14033            serializer.endDocument();
14034            serializer.flush();
14035        } catch (Exception e) {
14036            if (DEBUG_BACKUP) {
14037                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14038            }
14039            return null;
14040        }
14041
14042        return dataStream.toByteArray();
14043    }
14044
14045    @Override
14046    public void restorePreferredActivities(byte[] backup, int userId) {
14047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14048            throw new SecurityException("Only the system may call restorePreferredActivities()");
14049        }
14050
14051        try {
14052            final XmlPullParser parser = Xml.newPullParser();
14053            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14054            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14055                    new BlobXmlRestorer() {
14056                        @Override
14057                        public void apply(XmlPullParser parser, int userId)
14058                                throws XmlPullParserException, IOException {
14059                            synchronized (mPackages) {
14060                                mSettings.readPreferredActivitiesLPw(parser, userId);
14061                            }
14062                        }
14063                    } );
14064        } catch (Exception e) {
14065            if (DEBUG_BACKUP) {
14066                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14067            }
14068        }
14069    }
14070
14071    /**
14072     * Non-Binder method, support for the backup/restore mechanism: write the
14073     * default browser (etc) settings in its canonical XML format.  Returns the default
14074     * browser XML representation as a byte array, or null if there is none.
14075     */
14076    @Override
14077    public byte[] getDefaultAppsBackup(int userId) {
14078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14079            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14080        }
14081
14082        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14083        try {
14084            final XmlSerializer serializer = new FastXmlSerializer();
14085            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14086            serializer.startDocument(null, true);
14087            serializer.startTag(null, TAG_DEFAULT_APPS);
14088
14089            synchronized (mPackages) {
14090                mSettings.writeDefaultAppsLPr(serializer, userId);
14091            }
14092
14093            serializer.endTag(null, TAG_DEFAULT_APPS);
14094            serializer.endDocument();
14095            serializer.flush();
14096        } catch (Exception e) {
14097            if (DEBUG_BACKUP) {
14098                Slog.e(TAG, "Unable to write default apps for backup", e);
14099            }
14100            return null;
14101        }
14102
14103        return dataStream.toByteArray();
14104    }
14105
14106    @Override
14107    public void restoreDefaultApps(byte[] backup, int userId) {
14108        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14109            throw new SecurityException("Only the system may call restoreDefaultApps()");
14110        }
14111
14112        try {
14113            final XmlPullParser parser = Xml.newPullParser();
14114            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14115            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14116                    new BlobXmlRestorer() {
14117                        @Override
14118                        public void apply(XmlPullParser parser, int userId)
14119                                throws XmlPullParserException, IOException {
14120                            synchronized (mPackages) {
14121                                mSettings.readDefaultAppsLPw(parser, userId);
14122                            }
14123                        }
14124                    } );
14125        } catch (Exception e) {
14126            if (DEBUG_BACKUP) {
14127                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14128            }
14129        }
14130    }
14131
14132    @Override
14133    public byte[] getIntentFilterVerificationBackup(int userId) {
14134        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14135            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14136        }
14137
14138        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14139        try {
14140            final XmlSerializer serializer = new FastXmlSerializer();
14141            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14142            serializer.startDocument(null, true);
14143            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14144
14145            synchronized (mPackages) {
14146                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14147            }
14148
14149            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14150            serializer.endDocument();
14151            serializer.flush();
14152        } catch (Exception e) {
14153            if (DEBUG_BACKUP) {
14154                Slog.e(TAG, "Unable to write default apps for backup", e);
14155            }
14156            return null;
14157        }
14158
14159        return dataStream.toByteArray();
14160    }
14161
14162    @Override
14163    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14164        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14165            throw new SecurityException("Only the system may call restorePreferredActivities()");
14166        }
14167
14168        try {
14169            final XmlPullParser parser = Xml.newPullParser();
14170            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14171            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14172                    new BlobXmlRestorer() {
14173                        @Override
14174                        public void apply(XmlPullParser parser, int userId)
14175                                throws XmlPullParserException, IOException {
14176                            synchronized (mPackages) {
14177                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14178                                mSettings.writeLPr();
14179                            }
14180                        }
14181                    } );
14182        } catch (Exception e) {
14183            if (DEBUG_BACKUP) {
14184                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14185            }
14186        }
14187    }
14188
14189    @Override
14190    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14191            int sourceUserId, int targetUserId, int flags) {
14192        mContext.enforceCallingOrSelfPermission(
14193                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14194        int callingUid = Binder.getCallingUid();
14195        enforceOwnerRights(ownerPackage, callingUid);
14196        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14197        if (intentFilter.countActions() == 0) {
14198            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14199            return;
14200        }
14201        synchronized (mPackages) {
14202            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14203                    ownerPackage, targetUserId, flags);
14204            CrossProfileIntentResolver resolver =
14205                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14206            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14207            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14208            if (existing != null) {
14209                int size = existing.size();
14210                for (int i = 0; i < size; i++) {
14211                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14212                        return;
14213                    }
14214                }
14215            }
14216            resolver.addFilter(newFilter);
14217            scheduleWritePackageRestrictionsLocked(sourceUserId);
14218        }
14219    }
14220
14221    @Override
14222    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14223        mContext.enforceCallingOrSelfPermission(
14224                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14225        int callingUid = Binder.getCallingUid();
14226        enforceOwnerRights(ownerPackage, callingUid);
14227        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14228        synchronized (mPackages) {
14229            CrossProfileIntentResolver resolver =
14230                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14231            ArraySet<CrossProfileIntentFilter> set =
14232                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14233            for (CrossProfileIntentFilter filter : set) {
14234                if (filter.getOwnerPackage().equals(ownerPackage)) {
14235                    resolver.removeFilter(filter);
14236                }
14237            }
14238            scheduleWritePackageRestrictionsLocked(sourceUserId);
14239        }
14240    }
14241
14242    // Enforcing that callingUid is owning pkg on userId
14243    private void enforceOwnerRights(String pkg, int callingUid) {
14244        // The system owns everything.
14245        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14246            return;
14247        }
14248        int callingUserId = UserHandle.getUserId(callingUid);
14249        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14250        if (pi == null) {
14251            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14252                    + callingUserId);
14253        }
14254        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14255            throw new SecurityException("Calling uid " + callingUid
14256                    + " does not own package " + pkg);
14257        }
14258    }
14259
14260    @Override
14261    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14262        Intent intent = new Intent(Intent.ACTION_MAIN);
14263        intent.addCategory(Intent.CATEGORY_HOME);
14264
14265        final int callingUserId = UserHandle.getCallingUserId();
14266        List<ResolveInfo> list = queryIntentActivities(intent, null,
14267                PackageManager.GET_META_DATA, callingUserId);
14268        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14269                true, false, false, callingUserId);
14270
14271        allHomeCandidates.clear();
14272        if (list != null) {
14273            for (ResolveInfo ri : list) {
14274                allHomeCandidates.add(ri);
14275            }
14276        }
14277        return (preferred == null || preferred.activityInfo == null)
14278                ? null
14279                : new ComponentName(preferred.activityInfo.packageName,
14280                        preferred.activityInfo.name);
14281    }
14282
14283    @Override
14284    public void setApplicationEnabledSetting(String appPackageName,
14285            int newState, int flags, int userId, String callingPackage) {
14286        if (!sUserManager.exists(userId)) return;
14287        if (callingPackage == null) {
14288            callingPackage = Integer.toString(Binder.getCallingUid());
14289        }
14290        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14291    }
14292
14293    @Override
14294    public void setComponentEnabledSetting(ComponentName componentName,
14295            int newState, int flags, int userId) {
14296        if (!sUserManager.exists(userId)) return;
14297        setEnabledSetting(componentName.getPackageName(),
14298                componentName.getClassName(), newState, flags, userId, null);
14299    }
14300
14301    private void setEnabledSetting(final String packageName, String className, int newState,
14302            final int flags, int userId, String callingPackage) {
14303        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14304              || newState == COMPONENT_ENABLED_STATE_ENABLED
14305              || newState == COMPONENT_ENABLED_STATE_DISABLED
14306              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14307              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14308            throw new IllegalArgumentException("Invalid new component state: "
14309                    + newState);
14310        }
14311        PackageSetting pkgSetting;
14312        final int uid = Binder.getCallingUid();
14313        final int permission = mContext.checkCallingOrSelfPermission(
14314                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14315        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14316        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14317        boolean sendNow = false;
14318        boolean isApp = (className == null);
14319        String componentName = isApp ? packageName : className;
14320        int packageUid = -1;
14321        ArrayList<String> components;
14322
14323        // writer
14324        synchronized (mPackages) {
14325            pkgSetting = mSettings.mPackages.get(packageName);
14326            if (pkgSetting == null) {
14327                if (className == null) {
14328                    throw new IllegalArgumentException(
14329                            "Unknown package: " + packageName);
14330                }
14331                throw new IllegalArgumentException(
14332                        "Unknown component: " + packageName
14333                        + "/" + className);
14334            }
14335            // Allow root and verify that userId is not being specified by a different user
14336            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14337                throw new SecurityException(
14338                        "Permission Denial: attempt to change component state from pid="
14339                        + Binder.getCallingPid()
14340                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14341            }
14342            if (className == null) {
14343                // We're dealing with an application/package level state change
14344                if (pkgSetting.getEnabled(userId) == newState) {
14345                    // Nothing to do
14346                    return;
14347                }
14348                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14349                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14350                    // Don't care about who enables an app.
14351                    callingPackage = null;
14352                }
14353                pkgSetting.setEnabled(newState, userId, callingPackage);
14354                // pkgSetting.pkg.mSetEnabled = newState;
14355            } else {
14356                // We're dealing with a component level state change
14357                // First, verify that this is a valid class name.
14358                PackageParser.Package pkg = pkgSetting.pkg;
14359                if (pkg == null || !pkg.hasComponentClassName(className)) {
14360                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14361                        throw new IllegalArgumentException("Component class " + className
14362                                + " does not exist in " + packageName);
14363                    } else {
14364                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14365                                + className + " does not exist in " + packageName);
14366                    }
14367                }
14368                switch (newState) {
14369                case COMPONENT_ENABLED_STATE_ENABLED:
14370                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14371                        return;
14372                    }
14373                    break;
14374                case COMPONENT_ENABLED_STATE_DISABLED:
14375                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14376                        return;
14377                    }
14378                    break;
14379                case COMPONENT_ENABLED_STATE_DEFAULT:
14380                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14381                        return;
14382                    }
14383                    break;
14384                default:
14385                    Slog.e(TAG, "Invalid new component state: " + newState);
14386                    return;
14387                }
14388            }
14389            scheduleWritePackageRestrictionsLocked(userId);
14390            components = mPendingBroadcasts.get(userId, packageName);
14391            final boolean newPackage = components == null;
14392            if (newPackage) {
14393                components = new ArrayList<String>();
14394            }
14395            if (!components.contains(componentName)) {
14396                components.add(componentName);
14397            }
14398            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14399                sendNow = true;
14400                // Purge entry from pending broadcast list if another one exists already
14401                // since we are sending one right away.
14402                mPendingBroadcasts.remove(userId, packageName);
14403            } else {
14404                if (newPackage) {
14405                    mPendingBroadcasts.put(userId, packageName, components);
14406                }
14407                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14408                    // Schedule a message
14409                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14410                }
14411            }
14412        }
14413
14414        long callingId = Binder.clearCallingIdentity();
14415        try {
14416            if (sendNow) {
14417                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14418                sendPackageChangedBroadcast(packageName,
14419                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14420            }
14421        } finally {
14422            Binder.restoreCallingIdentity(callingId);
14423        }
14424    }
14425
14426    private void sendPackageChangedBroadcast(String packageName,
14427            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14428        if (DEBUG_INSTALL)
14429            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14430                    + componentNames);
14431        Bundle extras = new Bundle(4);
14432        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14433        String nameList[] = new String[componentNames.size()];
14434        componentNames.toArray(nameList);
14435        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14436        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14437        extras.putInt(Intent.EXTRA_UID, packageUid);
14438        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14439                new int[] {UserHandle.getUserId(packageUid)});
14440    }
14441
14442    @Override
14443    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14444        if (!sUserManager.exists(userId)) return;
14445        final int uid = Binder.getCallingUid();
14446        final int permission = mContext.checkCallingOrSelfPermission(
14447                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14448        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14449        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14450        // writer
14451        synchronized (mPackages) {
14452            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14453                    allowedByPermission, uid, userId)) {
14454                scheduleWritePackageRestrictionsLocked(userId);
14455            }
14456        }
14457    }
14458
14459    @Override
14460    public String getInstallerPackageName(String packageName) {
14461        // reader
14462        synchronized (mPackages) {
14463            return mSettings.getInstallerPackageNameLPr(packageName);
14464        }
14465    }
14466
14467    @Override
14468    public int getApplicationEnabledSetting(String packageName, int userId) {
14469        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14470        int uid = Binder.getCallingUid();
14471        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14472        // reader
14473        synchronized (mPackages) {
14474            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14475        }
14476    }
14477
14478    @Override
14479    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14480        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14481        int uid = Binder.getCallingUid();
14482        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14483        // reader
14484        synchronized (mPackages) {
14485            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14486        }
14487    }
14488
14489    @Override
14490    public void enterSafeMode() {
14491        enforceSystemOrRoot("Only the system can request entering safe mode");
14492
14493        if (!mSystemReady) {
14494            mSafeMode = true;
14495        }
14496    }
14497
14498    @Override
14499    public void systemReady() {
14500        mSystemReady = true;
14501
14502        // Read the compatibilty setting when the system is ready.
14503        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14504                mContext.getContentResolver(),
14505                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14506        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14507        if (DEBUG_SETTINGS) {
14508            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14509        }
14510
14511        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14512
14513        synchronized (mPackages) {
14514            // Verify that all of the preferred activity components actually
14515            // exist.  It is possible for applications to be updated and at
14516            // that point remove a previously declared activity component that
14517            // had been set as a preferred activity.  We try to clean this up
14518            // the next time we encounter that preferred activity, but it is
14519            // possible for the user flow to never be able to return to that
14520            // situation so here we do a sanity check to make sure we haven't
14521            // left any junk around.
14522            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14523            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14524                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14525                removed.clear();
14526                for (PreferredActivity pa : pir.filterSet()) {
14527                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14528                        removed.add(pa);
14529                    }
14530                }
14531                if (removed.size() > 0) {
14532                    for (int r=0; r<removed.size(); r++) {
14533                        PreferredActivity pa = removed.get(r);
14534                        Slog.w(TAG, "Removing dangling preferred activity: "
14535                                + pa.mPref.mComponent);
14536                        pir.removeFilter(pa);
14537                    }
14538                    mSettings.writePackageRestrictionsLPr(
14539                            mSettings.mPreferredActivities.keyAt(i));
14540                }
14541            }
14542
14543            for (int userId : UserManagerService.getInstance().getUserIds()) {
14544                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14545                    grantPermissionsUserIds = ArrayUtils.appendInt(
14546                            grantPermissionsUserIds, userId);
14547                }
14548            }
14549        }
14550        sUserManager.systemReady();
14551
14552        // If we upgraded grant all default permissions before kicking off.
14553        for (int userId : grantPermissionsUserIds) {
14554            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14555        }
14556
14557        // Kick off any messages waiting for system ready
14558        if (mPostSystemReadyMessages != null) {
14559            for (Message msg : mPostSystemReadyMessages) {
14560                msg.sendToTarget();
14561            }
14562            mPostSystemReadyMessages = null;
14563        }
14564
14565        // Watch for external volumes that come and go over time
14566        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14567        storage.registerListener(mStorageListener);
14568
14569        mInstallerService.systemReady();
14570        mPackageDexOptimizer.systemReady();
14571
14572        MountServiceInternal mountServiceInternal = LocalServices.getService(
14573                MountServiceInternal.class);
14574        mountServiceInternal.addExternalStoragePolicy(
14575                new MountServiceInternal.ExternalStorageMountPolicy() {
14576            @Override
14577            public int getMountMode(int uid, String packageName) {
14578                if (Process.isIsolated(uid)) {
14579                    return Zygote.MOUNT_EXTERNAL_NONE;
14580                }
14581                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14582                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14583                }
14584                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14585                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14586                }
14587                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14588                    return Zygote.MOUNT_EXTERNAL_READ;
14589                }
14590                return Zygote.MOUNT_EXTERNAL_WRITE;
14591            }
14592
14593            @Override
14594            public boolean hasExternalStorage(int uid, String packageName) {
14595                return true;
14596            }
14597        });
14598    }
14599
14600    @Override
14601    public boolean isSafeMode() {
14602        return mSafeMode;
14603    }
14604
14605    @Override
14606    public boolean hasSystemUidErrors() {
14607        return mHasSystemUidErrors;
14608    }
14609
14610    static String arrayToString(int[] array) {
14611        StringBuffer buf = new StringBuffer(128);
14612        buf.append('[');
14613        if (array != null) {
14614            for (int i=0; i<array.length; i++) {
14615                if (i > 0) buf.append(", ");
14616                buf.append(array[i]);
14617            }
14618        }
14619        buf.append(']');
14620        return buf.toString();
14621    }
14622
14623    static class DumpState {
14624        public static final int DUMP_LIBS = 1 << 0;
14625        public static final int DUMP_FEATURES = 1 << 1;
14626        public static final int DUMP_RESOLVERS = 1 << 2;
14627        public static final int DUMP_PERMISSIONS = 1 << 3;
14628        public static final int DUMP_PACKAGES = 1 << 4;
14629        public static final int DUMP_SHARED_USERS = 1 << 5;
14630        public static final int DUMP_MESSAGES = 1 << 6;
14631        public static final int DUMP_PROVIDERS = 1 << 7;
14632        public static final int DUMP_VERIFIERS = 1 << 8;
14633        public static final int DUMP_PREFERRED = 1 << 9;
14634        public static final int DUMP_PREFERRED_XML = 1 << 10;
14635        public static final int DUMP_KEYSETS = 1 << 11;
14636        public static final int DUMP_VERSION = 1 << 12;
14637        public static final int DUMP_INSTALLS = 1 << 13;
14638        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14639        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14640
14641        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14642
14643        private int mTypes;
14644
14645        private int mOptions;
14646
14647        private boolean mTitlePrinted;
14648
14649        private SharedUserSetting mSharedUser;
14650
14651        public boolean isDumping(int type) {
14652            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14653                return true;
14654            }
14655
14656            return (mTypes & type) != 0;
14657        }
14658
14659        public void setDump(int type) {
14660            mTypes |= type;
14661        }
14662
14663        public boolean isOptionEnabled(int option) {
14664            return (mOptions & option) != 0;
14665        }
14666
14667        public void setOptionEnabled(int option) {
14668            mOptions |= option;
14669        }
14670
14671        public boolean onTitlePrinted() {
14672            final boolean printed = mTitlePrinted;
14673            mTitlePrinted = true;
14674            return printed;
14675        }
14676
14677        public boolean getTitlePrinted() {
14678            return mTitlePrinted;
14679        }
14680
14681        public void setTitlePrinted(boolean enabled) {
14682            mTitlePrinted = enabled;
14683        }
14684
14685        public SharedUserSetting getSharedUser() {
14686            return mSharedUser;
14687        }
14688
14689        public void setSharedUser(SharedUserSetting user) {
14690            mSharedUser = user;
14691        }
14692    }
14693
14694    @Override
14695    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14696        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14697                != PackageManager.PERMISSION_GRANTED) {
14698            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14699                    + Binder.getCallingPid()
14700                    + ", uid=" + Binder.getCallingUid()
14701                    + " without permission "
14702                    + android.Manifest.permission.DUMP);
14703            return;
14704        }
14705
14706        DumpState dumpState = new DumpState();
14707        boolean fullPreferred = false;
14708        boolean checkin = false;
14709
14710        String packageName = null;
14711        ArraySet<String> permissionNames = null;
14712
14713        int opti = 0;
14714        while (opti < args.length) {
14715            String opt = args[opti];
14716            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14717                break;
14718            }
14719            opti++;
14720
14721            if ("-a".equals(opt)) {
14722                // Right now we only know how to print all.
14723            } else if ("-h".equals(opt)) {
14724                pw.println("Package manager dump options:");
14725                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14726                pw.println("    --checkin: dump for a checkin");
14727                pw.println("    -f: print details of intent filters");
14728                pw.println("    -h: print this help");
14729                pw.println("  cmd may be one of:");
14730                pw.println("    l[ibraries]: list known shared libraries");
14731                pw.println("    f[ibraries]: list device features");
14732                pw.println("    k[eysets]: print known keysets");
14733                pw.println("    r[esolvers]: dump intent resolvers");
14734                pw.println("    perm[issions]: dump permissions");
14735                pw.println("    permission [name ...]: dump declaration and use of given permission");
14736                pw.println("    pref[erred]: print preferred package settings");
14737                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14738                pw.println("    prov[iders]: dump content providers");
14739                pw.println("    p[ackages]: dump installed packages");
14740                pw.println("    s[hared-users]: dump shared user IDs");
14741                pw.println("    m[essages]: print collected runtime messages");
14742                pw.println("    v[erifiers]: print package verifier info");
14743                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14744                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14745                pw.println("    version: print database version info");
14746                pw.println("    write: write current settings now");
14747                pw.println("    installs: details about install sessions");
14748                pw.println("    <package.name>: info about given package");
14749                return;
14750            } else if ("--checkin".equals(opt)) {
14751                checkin = true;
14752            } else if ("-f".equals(opt)) {
14753                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14754            } else {
14755                pw.println("Unknown argument: " + opt + "; use -h for help");
14756            }
14757        }
14758
14759        // Is the caller requesting to dump a particular piece of data?
14760        if (opti < args.length) {
14761            String cmd = args[opti];
14762            opti++;
14763            // Is this a package name?
14764            if ("android".equals(cmd) || cmd.contains(".")) {
14765                packageName = cmd;
14766                // When dumping a single package, we always dump all of its
14767                // filter information since the amount of data will be reasonable.
14768                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14769            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14770                dumpState.setDump(DumpState.DUMP_LIBS);
14771            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14772                dumpState.setDump(DumpState.DUMP_FEATURES);
14773            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14774                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14775            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14776                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14777            } else if ("permission".equals(cmd)) {
14778                if (opti >= args.length) {
14779                    pw.println("Error: permission requires permission name");
14780                    return;
14781                }
14782                permissionNames = new ArraySet<>();
14783                while (opti < args.length) {
14784                    permissionNames.add(args[opti]);
14785                    opti++;
14786                }
14787                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14788                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14789            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14790                dumpState.setDump(DumpState.DUMP_PREFERRED);
14791            } else if ("preferred-xml".equals(cmd)) {
14792                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14793                if (opti < args.length && "--full".equals(args[opti])) {
14794                    fullPreferred = true;
14795                    opti++;
14796                }
14797            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14798                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14799            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14800                dumpState.setDump(DumpState.DUMP_PACKAGES);
14801            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14802                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14803            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14804                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14805            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14806                dumpState.setDump(DumpState.DUMP_MESSAGES);
14807            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14808                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14809            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14810                    || "intent-filter-verifiers".equals(cmd)) {
14811                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14812            } else if ("version".equals(cmd)) {
14813                dumpState.setDump(DumpState.DUMP_VERSION);
14814            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14815                dumpState.setDump(DumpState.DUMP_KEYSETS);
14816            } else if ("installs".equals(cmd)) {
14817                dumpState.setDump(DumpState.DUMP_INSTALLS);
14818            } else if ("write".equals(cmd)) {
14819                synchronized (mPackages) {
14820                    mSettings.writeLPr();
14821                    pw.println("Settings written.");
14822                    return;
14823                }
14824            }
14825        }
14826
14827        if (checkin) {
14828            pw.println("vers,1");
14829        }
14830
14831        // reader
14832        synchronized (mPackages) {
14833            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14834                if (!checkin) {
14835                    if (dumpState.onTitlePrinted())
14836                        pw.println();
14837                    pw.println("Database versions:");
14838                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14839                }
14840            }
14841
14842            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14843                if (!checkin) {
14844                    if (dumpState.onTitlePrinted())
14845                        pw.println();
14846                    pw.println("Verifiers:");
14847                    pw.print("  Required: ");
14848                    pw.print(mRequiredVerifierPackage);
14849                    pw.print(" (uid=");
14850                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14851                    pw.println(")");
14852                } else if (mRequiredVerifierPackage != null) {
14853                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14854                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14855                }
14856            }
14857
14858            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14859                    packageName == null) {
14860                if (mIntentFilterVerifierComponent != null) {
14861                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14862                    if (!checkin) {
14863                        if (dumpState.onTitlePrinted())
14864                            pw.println();
14865                        pw.println("Intent Filter Verifier:");
14866                        pw.print("  Using: ");
14867                        pw.print(verifierPackageName);
14868                        pw.print(" (uid=");
14869                        pw.print(getPackageUid(verifierPackageName, 0));
14870                        pw.println(")");
14871                    } else if (verifierPackageName != null) {
14872                        pw.print("ifv,"); pw.print(verifierPackageName);
14873                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14874                    }
14875                } else {
14876                    pw.println();
14877                    pw.println("No Intent Filter Verifier available!");
14878                }
14879            }
14880
14881            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14882                boolean printedHeader = false;
14883                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14884                while (it.hasNext()) {
14885                    String name = it.next();
14886                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14887                    if (!checkin) {
14888                        if (!printedHeader) {
14889                            if (dumpState.onTitlePrinted())
14890                                pw.println();
14891                            pw.println("Libraries:");
14892                            printedHeader = true;
14893                        }
14894                        pw.print("  ");
14895                    } else {
14896                        pw.print("lib,");
14897                    }
14898                    pw.print(name);
14899                    if (!checkin) {
14900                        pw.print(" -> ");
14901                    }
14902                    if (ent.path != null) {
14903                        if (!checkin) {
14904                            pw.print("(jar) ");
14905                            pw.print(ent.path);
14906                        } else {
14907                            pw.print(",jar,");
14908                            pw.print(ent.path);
14909                        }
14910                    } else {
14911                        if (!checkin) {
14912                            pw.print("(apk) ");
14913                            pw.print(ent.apk);
14914                        } else {
14915                            pw.print(",apk,");
14916                            pw.print(ent.apk);
14917                        }
14918                    }
14919                    pw.println();
14920                }
14921            }
14922
14923            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14924                if (dumpState.onTitlePrinted())
14925                    pw.println();
14926                if (!checkin) {
14927                    pw.println("Features:");
14928                }
14929                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14930                while (it.hasNext()) {
14931                    String name = it.next();
14932                    if (!checkin) {
14933                        pw.print("  ");
14934                    } else {
14935                        pw.print("feat,");
14936                    }
14937                    pw.println(name);
14938                }
14939            }
14940
14941            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14942                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14943                        : "Activity Resolver Table:", "  ", packageName,
14944                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14945                    dumpState.setTitlePrinted(true);
14946                }
14947                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14948                        : "Receiver Resolver Table:", "  ", packageName,
14949                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14950                    dumpState.setTitlePrinted(true);
14951                }
14952                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14953                        : "Service Resolver Table:", "  ", packageName,
14954                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14955                    dumpState.setTitlePrinted(true);
14956                }
14957                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14958                        : "Provider Resolver Table:", "  ", packageName,
14959                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14960                    dumpState.setTitlePrinted(true);
14961                }
14962            }
14963
14964            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14965                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14966                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14967                    int user = mSettings.mPreferredActivities.keyAt(i);
14968                    if (pir.dump(pw,
14969                            dumpState.getTitlePrinted()
14970                                ? "\nPreferred Activities User " + user + ":"
14971                                : "Preferred Activities User " + user + ":", "  ",
14972                            packageName, true, false)) {
14973                        dumpState.setTitlePrinted(true);
14974                    }
14975                }
14976            }
14977
14978            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14979                pw.flush();
14980                FileOutputStream fout = new FileOutputStream(fd);
14981                BufferedOutputStream str = new BufferedOutputStream(fout);
14982                XmlSerializer serializer = new FastXmlSerializer();
14983                try {
14984                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14985                    serializer.startDocument(null, true);
14986                    serializer.setFeature(
14987                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14988                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14989                    serializer.endDocument();
14990                    serializer.flush();
14991                } catch (IllegalArgumentException e) {
14992                    pw.println("Failed writing: " + e);
14993                } catch (IllegalStateException e) {
14994                    pw.println("Failed writing: " + e);
14995                } catch (IOException e) {
14996                    pw.println("Failed writing: " + e);
14997                }
14998            }
14999
15000            if (!checkin
15001                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15002                    && packageName == null) {
15003                pw.println();
15004                int count = mSettings.mPackages.size();
15005                if (count == 0) {
15006                    pw.println("No applications!");
15007                    pw.println();
15008                } else {
15009                    final String prefix = "  ";
15010                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15011                    if (allPackageSettings.size() == 0) {
15012                        pw.println("No domain preferred apps!");
15013                        pw.println();
15014                    } else {
15015                        pw.println("App verification status:");
15016                        pw.println();
15017                        count = 0;
15018                        for (PackageSetting ps : allPackageSettings) {
15019                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15020                            if (ivi == null || ivi.getPackageName() == null) continue;
15021                            pw.println(prefix + "Package: " + ivi.getPackageName());
15022                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15023                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15024                            pw.println();
15025                            count++;
15026                        }
15027                        if (count == 0) {
15028                            pw.println(prefix + "No app verification established.");
15029                            pw.println();
15030                        }
15031                        for (int userId : sUserManager.getUserIds()) {
15032                            pw.println("App linkages for user " + userId + ":");
15033                            pw.println();
15034                            count = 0;
15035                            for (PackageSetting ps : allPackageSettings) {
15036                                final long status = ps.getDomainVerificationStatusForUser(userId);
15037                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15038                                    continue;
15039                                }
15040                                pw.println(prefix + "Package: " + ps.name);
15041                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15042                                String statusStr = IntentFilterVerificationInfo.
15043                                        getStatusStringFromValue(status);
15044                                pw.println(prefix + "Status:  " + statusStr);
15045                                pw.println();
15046                                count++;
15047                            }
15048                            if (count == 0) {
15049                                pw.println(prefix + "No configured app linkages.");
15050                                pw.println();
15051                            }
15052                        }
15053                    }
15054                }
15055            }
15056
15057            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15058                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15059                if (packageName == null && permissionNames == null) {
15060                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15061                        if (iperm == 0) {
15062                            if (dumpState.onTitlePrinted())
15063                                pw.println();
15064                            pw.println("AppOp Permissions:");
15065                        }
15066                        pw.print("  AppOp Permission ");
15067                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15068                        pw.println(":");
15069                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15070                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15071                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15072                        }
15073                    }
15074                }
15075            }
15076
15077            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15078                boolean printedSomething = false;
15079                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15080                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15081                        continue;
15082                    }
15083                    if (!printedSomething) {
15084                        if (dumpState.onTitlePrinted())
15085                            pw.println();
15086                        pw.println("Registered ContentProviders:");
15087                        printedSomething = true;
15088                    }
15089                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15090                    pw.print("    "); pw.println(p.toString());
15091                }
15092                printedSomething = false;
15093                for (Map.Entry<String, PackageParser.Provider> entry :
15094                        mProvidersByAuthority.entrySet()) {
15095                    PackageParser.Provider p = entry.getValue();
15096                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15097                        continue;
15098                    }
15099                    if (!printedSomething) {
15100                        if (dumpState.onTitlePrinted())
15101                            pw.println();
15102                        pw.println("ContentProvider Authorities:");
15103                        printedSomething = true;
15104                    }
15105                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15106                    pw.print("    "); pw.println(p.toString());
15107                    if (p.info != null && p.info.applicationInfo != null) {
15108                        final String appInfo = p.info.applicationInfo.toString();
15109                        pw.print("      applicationInfo="); pw.println(appInfo);
15110                    }
15111                }
15112            }
15113
15114            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15115                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15116            }
15117
15118            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15119                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15120            }
15121
15122            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15123                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15124            }
15125
15126            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15127                // XXX should handle packageName != null by dumping only install data that
15128                // the given package is involved with.
15129                if (dumpState.onTitlePrinted()) pw.println();
15130                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15131            }
15132
15133            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15134                if (dumpState.onTitlePrinted()) pw.println();
15135                mSettings.dumpReadMessagesLPr(pw, dumpState);
15136
15137                pw.println();
15138                pw.println("Package warning messages:");
15139                BufferedReader in = null;
15140                String line = null;
15141                try {
15142                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15143                    while ((line = in.readLine()) != null) {
15144                        if (line.contains("ignored: updated version")) continue;
15145                        pw.println(line);
15146                    }
15147                } catch (IOException ignored) {
15148                } finally {
15149                    IoUtils.closeQuietly(in);
15150                }
15151            }
15152
15153            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15154                BufferedReader in = null;
15155                String line = null;
15156                try {
15157                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15158                    while ((line = in.readLine()) != null) {
15159                        if (line.contains("ignored: updated version")) continue;
15160                        pw.print("msg,");
15161                        pw.println(line);
15162                    }
15163                } catch (IOException ignored) {
15164                } finally {
15165                    IoUtils.closeQuietly(in);
15166                }
15167            }
15168        }
15169    }
15170
15171    private String dumpDomainString(String packageName) {
15172        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15173        List<IntentFilter> filters = getAllIntentFilters(packageName);
15174
15175        ArraySet<String> result = new ArraySet<>();
15176        if (iviList.size() > 0) {
15177            for (IntentFilterVerificationInfo ivi : iviList) {
15178                for (String host : ivi.getDomains()) {
15179                    result.add(host);
15180                }
15181            }
15182        }
15183        if (filters != null && filters.size() > 0) {
15184            for (IntentFilter filter : filters) {
15185                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15186                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15187                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15188                    result.addAll(filter.getHostsList());
15189                }
15190            }
15191        }
15192
15193        StringBuilder sb = new StringBuilder(result.size() * 16);
15194        for (String domain : result) {
15195            if (sb.length() > 0) sb.append(" ");
15196            sb.append(domain);
15197        }
15198        return sb.toString();
15199    }
15200
15201    // ------- apps on sdcard specific code -------
15202    static final boolean DEBUG_SD_INSTALL = false;
15203
15204    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15205
15206    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15207
15208    private boolean mMediaMounted = false;
15209
15210    static String getEncryptKey() {
15211        try {
15212            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15213                    SD_ENCRYPTION_KEYSTORE_NAME);
15214            if (sdEncKey == null) {
15215                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15216                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15217                if (sdEncKey == null) {
15218                    Slog.e(TAG, "Failed to create encryption keys");
15219                    return null;
15220                }
15221            }
15222            return sdEncKey;
15223        } catch (NoSuchAlgorithmException nsae) {
15224            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15225            return null;
15226        } catch (IOException ioe) {
15227            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15228            return null;
15229        }
15230    }
15231
15232    /*
15233     * Update media status on PackageManager.
15234     */
15235    @Override
15236    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15237        int callingUid = Binder.getCallingUid();
15238        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15239            throw new SecurityException("Media status can only be updated by the system");
15240        }
15241        // reader; this apparently protects mMediaMounted, but should probably
15242        // be a different lock in that case.
15243        synchronized (mPackages) {
15244            Log.i(TAG, "Updating external media status from "
15245                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15246                    + (mediaStatus ? "mounted" : "unmounted"));
15247            if (DEBUG_SD_INSTALL)
15248                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15249                        + ", mMediaMounted=" + mMediaMounted);
15250            if (mediaStatus == mMediaMounted) {
15251                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15252                        : 0, -1);
15253                mHandler.sendMessage(msg);
15254                return;
15255            }
15256            mMediaMounted = mediaStatus;
15257        }
15258        // Queue up an async operation since the package installation may take a
15259        // little while.
15260        mHandler.post(new Runnable() {
15261            public void run() {
15262                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15263            }
15264        });
15265    }
15266
15267    /**
15268     * Called by MountService when the initial ASECs to scan are available.
15269     * Should block until all the ASEC containers are finished being scanned.
15270     */
15271    public void scanAvailableAsecs() {
15272        updateExternalMediaStatusInner(true, false, false);
15273        if (mShouldRestoreconData) {
15274            SELinuxMMAC.setRestoreconDone();
15275            mShouldRestoreconData = false;
15276        }
15277    }
15278
15279    /*
15280     * Collect information of applications on external media, map them against
15281     * existing containers and update information based on current mount status.
15282     * Please note that we always have to report status if reportStatus has been
15283     * set to true especially when unloading packages.
15284     */
15285    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15286            boolean externalStorage) {
15287        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15288        int[] uidArr = EmptyArray.INT;
15289
15290        final String[] list = PackageHelper.getSecureContainerList();
15291        if (ArrayUtils.isEmpty(list)) {
15292            Log.i(TAG, "No secure containers found");
15293        } else {
15294            // Process list of secure containers and categorize them
15295            // as active or stale based on their package internal state.
15296
15297            // reader
15298            synchronized (mPackages) {
15299                for (String cid : list) {
15300                    // Leave stages untouched for now; installer service owns them
15301                    if (PackageInstallerService.isStageName(cid)) continue;
15302
15303                    if (DEBUG_SD_INSTALL)
15304                        Log.i(TAG, "Processing container " + cid);
15305                    String pkgName = getAsecPackageName(cid);
15306                    if (pkgName == null) {
15307                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15308                        continue;
15309                    }
15310                    if (DEBUG_SD_INSTALL)
15311                        Log.i(TAG, "Looking for pkg : " + pkgName);
15312
15313                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15314                    if (ps == null) {
15315                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15316                        continue;
15317                    }
15318
15319                    /*
15320                     * Skip packages that are not external if we're unmounting
15321                     * external storage.
15322                     */
15323                    if (externalStorage && !isMounted && !isExternal(ps)) {
15324                        continue;
15325                    }
15326
15327                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15328                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15329                    // The package status is changed only if the code path
15330                    // matches between settings and the container id.
15331                    if (ps.codePathString != null
15332                            && ps.codePathString.startsWith(args.getCodePath())) {
15333                        if (DEBUG_SD_INSTALL) {
15334                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15335                                    + " at code path: " + ps.codePathString);
15336                        }
15337
15338                        // We do have a valid package installed on sdcard
15339                        processCids.put(args, ps.codePathString);
15340                        final int uid = ps.appId;
15341                        if (uid != -1) {
15342                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15343                        }
15344                    } else {
15345                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15346                                + ps.codePathString);
15347                    }
15348                }
15349            }
15350
15351            Arrays.sort(uidArr);
15352        }
15353
15354        // Process packages with valid entries.
15355        if (isMounted) {
15356            if (DEBUG_SD_INSTALL)
15357                Log.i(TAG, "Loading packages");
15358            loadMediaPackages(processCids, uidArr);
15359            startCleaningPackages();
15360            mInstallerService.onSecureContainersAvailable();
15361        } else {
15362            if (DEBUG_SD_INSTALL)
15363                Log.i(TAG, "Unloading packages");
15364            unloadMediaPackages(processCids, uidArr, reportStatus);
15365        }
15366    }
15367
15368    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15369            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15370        final int size = infos.size();
15371        final String[] packageNames = new String[size];
15372        final int[] packageUids = new int[size];
15373        for (int i = 0; i < size; i++) {
15374            final ApplicationInfo info = infos.get(i);
15375            packageNames[i] = info.packageName;
15376            packageUids[i] = info.uid;
15377        }
15378        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15379                finishedReceiver);
15380    }
15381
15382    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15383            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15384        sendResourcesChangedBroadcast(mediaStatus, replacing,
15385                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15386    }
15387
15388    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15389            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15390        int size = pkgList.length;
15391        if (size > 0) {
15392            // Send broadcasts here
15393            Bundle extras = new Bundle();
15394            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15395            if (uidArr != null) {
15396                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15397            }
15398            if (replacing) {
15399                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15400            }
15401            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15402                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15403            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15404        }
15405    }
15406
15407   /*
15408     * Look at potentially valid container ids from processCids If package
15409     * information doesn't match the one on record or package scanning fails,
15410     * the cid is added to list of removeCids. We currently don't delete stale
15411     * containers.
15412     */
15413    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15414        ArrayList<String> pkgList = new ArrayList<String>();
15415        Set<AsecInstallArgs> keys = processCids.keySet();
15416
15417        for (AsecInstallArgs args : keys) {
15418            String codePath = processCids.get(args);
15419            if (DEBUG_SD_INSTALL)
15420                Log.i(TAG, "Loading container : " + args.cid);
15421            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15422            try {
15423                // Make sure there are no container errors first.
15424                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15425                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15426                            + " when installing from sdcard");
15427                    continue;
15428                }
15429                // Check code path here.
15430                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15431                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15432                            + " does not match one in settings " + codePath);
15433                    continue;
15434                }
15435                // Parse package
15436                int parseFlags = mDefParseFlags;
15437                if (args.isExternalAsec()) {
15438                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15439                }
15440                if (args.isFwdLocked()) {
15441                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15442                }
15443
15444                synchronized (mInstallLock) {
15445                    PackageParser.Package pkg = null;
15446                    try {
15447                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15448                    } catch (PackageManagerException e) {
15449                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15450                    }
15451                    // Scan the package
15452                    if (pkg != null) {
15453                        /*
15454                         * TODO why is the lock being held? doPostInstall is
15455                         * called in other places without the lock. This needs
15456                         * to be straightened out.
15457                         */
15458                        // writer
15459                        synchronized (mPackages) {
15460                            retCode = PackageManager.INSTALL_SUCCEEDED;
15461                            pkgList.add(pkg.packageName);
15462                            // Post process args
15463                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15464                                    pkg.applicationInfo.uid);
15465                        }
15466                    } else {
15467                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15468                    }
15469                }
15470
15471            } finally {
15472                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15473                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15474                }
15475            }
15476        }
15477        // writer
15478        synchronized (mPackages) {
15479            // If the platform SDK has changed since the last time we booted,
15480            // we need to re-grant app permission to catch any new ones that
15481            // appear. This is really a hack, and means that apps can in some
15482            // cases get permissions that the user didn't initially explicitly
15483            // allow... it would be nice to have some better way to handle
15484            // this situation.
15485            final VersionInfo ver = mSettings.getExternalVersion();
15486
15487            int updateFlags = UPDATE_PERMISSIONS_ALL;
15488            if (ver.sdkVersion != mSdkVersion) {
15489                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15490                        + mSdkVersion + "; regranting permissions for external");
15491                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15492            }
15493            updatePermissionsLPw(null, null, updateFlags);
15494
15495            // Yay, everything is now upgraded
15496            ver.forceCurrent();
15497
15498            // can downgrade to reader
15499            // Persist settings
15500            mSettings.writeLPr();
15501        }
15502        // Send a broadcast to let everyone know we are done processing
15503        if (pkgList.size() > 0) {
15504            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15505        }
15506    }
15507
15508   /*
15509     * Utility method to unload a list of specified containers
15510     */
15511    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15512        // Just unmount all valid containers.
15513        for (AsecInstallArgs arg : cidArgs) {
15514            synchronized (mInstallLock) {
15515                arg.doPostDeleteLI(false);
15516           }
15517       }
15518   }
15519
15520    /*
15521     * Unload packages mounted on external media. This involves deleting package
15522     * data from internal structures, sending broadcasts about diabled packages,
15523     * gc'ing to free up references, unmounting all secure containers
15524     * corresponding to packages on external media, and posting a
15525     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15526     * that we always have to post this message if status has been requested no
15527     * matter what.
15528     */
15529    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15530            final boolean reportStatus) {
15531        if (DEBUG_SD_INSTALL)
15532            Log.i(TAG, "unloading media packages");
15533        ArrayList<String> pkgList = new ArrayList<String>();
15534        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15535        final Set<AsecInstallArgs> keys = processCids.keySet();
15536        for (AsecInstallArgs args : keys) {
15537            String pkgName = args.getPackageName();
15538            if (DEBUG_SD_INSTALL)
15539                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15540            // Delete package internally
15541            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15542            synchronized (mInstallLock) {
15543                boolean res = deletePackageLI(pkgName, null, false, null, null,
15544                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15545                if (res) {
15546                    pkgList.add(pkgName);
15547                } else {
15548                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15549                    failedList.add(args);
15550                }
15551            }
15552        }
15553
15554        // reader
15555        synchronized (mPackages) {
15556            // We didn't update the settings after removing each package;
15557            // write them now for all packages.
15558            mSettings.writeLPr();
15559        }
15560
15561        // We have to absolutely send UPDATED_MEDIA_STATUS only
15562        // after confirming that all the receivers processed the ordered
15563        // broadcast when packages get disabled, force a gc to clean things up.
15564        // and unload all the containers.
15565        if (pkgList.size() > 0) {
15566            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15567                    new IIntentReceiver.Stub() {
15568                public void performReceive(Intent intent, int resultCode, String data,
15569                        Bundle extras, boolean ordered, boolean sticky,
15570                        int sendingUser) throws RemoteException {
15571                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15572                            reportStatus ? 1 : 0, 1, keys);
15573                    mHandler.sendMessage(msg);
15574                }
15575            });
15576        } else {
15577            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15578                    keys);
15579            mHandler.sendMessage(msg);
15580        }
15581    }
15582
15583    private void loadPrivatePackages(VolumeInfo vol) {
15584        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15585        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15586        synchronized (mInstallLock) {
15587        synchronized (mPackages) {
15588            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15589            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15590            for (PackageSetting ps : packages) {
15591                final PackageParser.Package pkg;
15592                try {
15593                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15594                    loaded.add(pkg.applicationInfo);
15595                } catch (PackageManagerException e) {
15596                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15597                }
15598
15599                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15600                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15601                }
15602            }
15603
15604            int updateFlags = UPDATE_PERMISSIONS_ALL;
15605            if (ver.sdkVersion != mSdkVersion) {
15606                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15607                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15608                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15609            }
15610            updatePermissionsLPw(null, null, updateFlags);
15611
15612            // Yay, everything is now upgraded
15613            ver.forceCurrent();
15614
15615            mSettings.writeLPr();
15616        }
15617        }
15618
15619        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15620        sendResourcesChangedBroadcast(true, false, loaded, null);
15621    }
15622
15623    private void unloadPrivatePackages(VolumeInfo vol) {
15624        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15625        synchronized (mInstallLock) {
15626        synchronized (mPackages) {
15627            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15628            for (PackageSetting ps : packages) {
15629                if (ps.pkg == null) continue;
15630
15631                final ApplicationInfo info = ps.pkg.applicationInfo;
15632                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15633                if (deletePackageLI(ps.name, null, false, null, null,
15634                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15635                    unloaded.add(info);
15636                } else {
15637                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15638                }
15639            }
15640
15641            mSettings.writeLPr();
15642        }
15643        }
15644
15645        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15646        sendResourcesChangedBroadcast(false, false, unloaded, null);
15647    }
15648
15649    /**
15650     * Examine all users present on given mounted volume, and destroy data
15651     * belonging to users that are no longer valid, or whose user ID has been
15652     * recycled.
15653     */
15654    private void reconcileUsers(String volumeUuid) {
15655        final File[] files = FileUtils
15656                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15657        for (File file : files) {
15658            if (!file.isDirectory()) continue;
15659
15660            final int userId;
15661            final UserInfo info;
15662            try {
15663                userId = Integer.parseInt(file.getName());
15664                info = sUserManager.getUserInfo(userId);
15665            } catch (NumberFormatException e) {
15666                Slog.w(TAG, "Invalid user directory " + file);
15667                continue;
15668            }
15669
15670            boolean destroyUser = false;
15671            if (info == null) {
15672                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15673                        + " because no matching user was found");
15674                destroyUser = true;
15675            } else {
15676                try {
15677                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15678                } catch (IOException e) {
15679                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15680                            + " because we failed to enforce serial number: " + e);
15681                    destroyUser = true;
15682                }
15683            }
15684
15685            if (destroyUser) {
15686                synchronized (mInstallLock) {
15687                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15688                }
15689            }
15690        }
15691
15692        final UserManager um = mContext.getSystemService(UserManager.class);
15693        for (UserInfo user : um.getUsers()) {
15694            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15695            if (userDir.exists()) continue;
15696
15697            try {
15698                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15699                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15700            } catch (IOException e) {
15701                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15702            }
15703        }
15704    }
15705
15706    /**
15707     * Examine all apps present on given mounted volume, and destroy apps that
15708     * aren't expected, either due to uninstallation or reinstallation on
15709     * another volume.
15710     */
15711    private void reconcileApps(String volumeUuid) {
15712        final File[] files = FileUtils
15713                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15714        for (File file : files) {
15715            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15716                    && !PackageInstallerService.isStageName(file.getName());
15717            if (!isPackage) {
15718                // Ignore entries which are not packages
15719                continue;
15720            }
15721
15722            boolean destroyApp = false;
15723            String packageName = null;
15724            try {
15725                final PackageLite pkg = PackageParser.parsePackageLite(file,
15726                        PackageParser.PARSE_MUST_BE_APK);
15727                packageName = pkg.packageName;
15728
15729                synchronized (mPackages) {
15730                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15731                    if (ps == null) {
15732                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15733                                + volumeUuid + " because we found no install record");
15734                        destroyApp = true;
15735                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15736                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15737                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15738                        destroyApp = true;
15739                    }
15740                }
15741
15742            } catch (PackageParserException e) {
15743                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15744                destroyApp = true;
15745            }
15746
15747            if (destroyApp) {
15748                synchronized (mInstallLock) {
15749                    if (packageName != null) {
15750                        removeDataDirsLI(volumeUuid, packageName);
15751                    }
15752                    if (file.isDirectory()) {
15753                        mInstaller.rmPackageDir(file.getAbsolutePath());
15754                    } else {
15755                        file.delete();
15756                    }
15757                }
15758            }
15759        }
15760    }
15761
15762    private void unfreezePackage(String packageName) {
15763        synchronized (mPackages) {
15764            final PackageSetting ps = mSettings.mPackages.get(packageName);
15765            if (ps != null) {
15766                ps.frozen = false;
15767            }
15768        }
15769    }
15770
15771    @Override
15772    public int movePackage(final String packageName, final String volumeUuid) {
15773        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15774
15775        final int moveId = mNextMoveId.getAndIncrement();
15776        try {
15777            movePackageInternal(packageName, volumeUuid, moveId);
15778        } catch (PackageManagerException e) {
15779            Slog.w(TAG, "Failed to move " + packageName, e);
15780            mMoveCallbacks.notifyStatusChanged(moveId,
15781                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15782        }
15783        return moveId;
15784    }
15785
15786    private void movePackageInternal(final String packageName, final String volumeUuid,
15787            final int moveId) throws PackageManagerException {
15788        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15789        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15790        final PackageManager pm = mContext.getPackageManager();
15791
15792        final boolean currentAsec;
15793        final String currentVolumeUuid;
15794        final File codeFile;
15795        final String installerPackageName;
15796        final String packageAbiOverride;
15797        final int appId;
15798        final String seinfo;
15799        final String label;
15800
15801        // reader
15802        synchronized (mPackages) {
15803            final PackageParser.Package pkg = mPackages.get(packageName);
15804            final PackageSetting ps = mSettings.mPackages.get(packageName);
15805            if (pkg == null || ps == null) {
15806                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15807            }
15808
15809            if (pkg.applicationInfo.isSystemApp()) {
15810                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15811                        "Cannot move system application");
15812            }
15813
15814            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15815                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15816                        "Package already moved to " + volumeUuid);
15817            }
15818
15819            final File probe = new File(pkg.codePath);
15820            final File probeOat = new File(probe, "oat");
15821            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15822                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15823                        "Move only supported for modern cluster style installs");
15824            }
15825
15826            if (ps.frozen) {
15827                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15828                        "Failed to move already frozen package");
15829            }
15830            ps.frozen = true;
15831
15832            currentAsec = pkg.applicationInfo.isForwardLocked()
15833                    || pkg.applicationInfo.isExternalAsec();
15834            currentVolumeUuid = ps.volumeUuid;
15835            codeFile = new File(pkg.codePath);
15836            installerPackageName = ps.installerPackageName;
15837            packageAbiOverride = ps.cpuAbiOverrideString;
15838            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15839            seinfo = pkg.applicationInfo.seinfo;
15840            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15841        }
15842
15843        // Now that we're guarded by frozen state, kill app during move
15844        final long token = Binder.clearCallingIdentity();
15845        try {
15846            killApplication(packageName, appId, "move pkg");
15847        } finally {
15848            Binder.restoreCallingIdentity(token);
15849        }
15850
15851        final Bundle extras = new Bundle();
15852        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15853        extras.putString(Intent.EXTRA_TITLE, label);
15854        mMoveCallbacks.notifyCreated(moveId, extras);
15855
15856        int installFlags;
15857        final boolean moveCompleteApp;
15858        final File measurePath;
15859
15860        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15861            installFlags = INSTALL_INTERNAL;
15862            moveCompleteApp = !currentAsec;
15863            measurePath = Environment.getDataAppDirectory(volumeUuid);
15864        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15865            installFlags = INSTALL_EXTERNAL;
15866            moveCompleteApp = false;
15867            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15868        } else {
15869            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15870            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15871                    || !volume.isMountedWritable()) {
15872                unfreezePackage(packageName);
15873                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15874                        "Move location not mounted private volume");
15875            }
15876
15877            Preconditions.checkState(!currentAsec);
15878
15879            installFlags = INSTALL_INTERNAL;
15880            moveCompleteApp = true;
15881            measurePath = Environment.getDataAppDirectory(volumeUuid);
15882        }
15883
15884        final PackageStats stats = new PackageStats(null, -1);
15885        synchronized (mInstaller) {
15886            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15887                unfreezePackage(packageName);
15888                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15889                        "Failed to measure package size");
15890            }
15891        }
15892
15893        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15894                + stats.dataSize);
15895
15896        final long startFreeBytes = measurePath.getFreeSpace();
15897        final long sizeBytes;
15898        if (moveCompleteApp) {
15899            sizeBytes = stats.codeSize + stats.dataSize;
15900        } else {
15901            sizeBytes = stats.codeSize;
15902        }
15903
15904        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15905            unfreezePackage(packageName);
15906            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15907                    "Not enough free space to move");
15908        }
15909
15910        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15911
15912        final CountDownLatch installedLatch = new CountDownLatch(1);
15913        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15914            @Override
15915            public void onUserActionRequired(Intent intent) throws RemoteException {
15916                throw new IllegalStateException();
15917            }
15918
15919            @Override
15920            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15921                    Bundle extras) throws RemoteException {
15922                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15923                        + PackageManager.installStatusToString(returnCode, msg));
15924
15925                installedLatch.countDown();
15926
15927                // Regardless of success or failure of the move operation,
15928                // always unfreeze the package
15929                unfreezePackage(packageName);
15930
15931                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15932                switch (status) {
15933                    case PackageInstaller.STATUS_SUCCESS:
15934                        mMoveCallbacks.notifyStatusChanged(moveId,
15935                                PackageManager.MOVE_SUCCEEDED);
15936                        break;
15937                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15938                        mMoveCallbacks.notifyStatusChanged(moveId,
15939                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15940                        break;
15941                    default:
15942                        mMoveCallbacks.notifyStatusChanged(moveId,
15943                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15944                        break;
15945                }
15946            }
15947        };
15948
15949        final MoveInfo move;
15950        if (moveCompleteApp) {
15951            // Kick off a thread to report progress estimates
15952            new Thread() {
15953                @Override
15954                public void run() {
15955                    while (true) {
15956                        try {
15957                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15958                                break;
15959                            }
15960                        } catch (InterruptedException ignored) {
15961                        }
15962
15963                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15964                        final int progress = 10 + (int) MathUtils.constrain(
15965                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15966                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15967                    }
15968                }
15969            }.start();
15970
15971            final String dataAppName = codeFile.getName();
15972            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15973                    dataAppName, appId, seinfo);
15974        } else {
15975            move = null;
15976        }
15977
15978        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15979
15980        final Message msg = mHandler.obtainMessage(INIT_COPY);
15981        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15982        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15983                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15984        mHandler.sendMessage(msg);
15985    }
15986
15987    @Override
15988    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15989        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15990
15991        final int realMoveId = mNextMoveId.getAndIncrement();
15992        final Bundle extras = new Bundle();
15993        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15994        mMoveCallbacks.notifyCreated(realMoveId, extras);
15995
15996        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15997            @Override
15998            public void onCreated(int moveId, Bundle extras) {
15999                // Ignored
16000            }
16001
16002            @Override
16003            public void onStatusChanged(int moveId, int status, long estMillis) {
16004                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16005            }
16006        };
16007
16008        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16009        storage.setPrimaryStorageUuid(volumeUuid, callback);
16010        return realMoveId;
16011    }
16012
16013    @Override
16014    public int getMoveStatus(int moveId) {
16015        mContext.enforceCallingOrSelfPermission(
16016                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16017        return mMoveCallbacks.mLastStatus.get(moveId);
16018    }
16019
16020    @Override
16021    public void registerMoveCallback(IPackageMoveObserver callback) {
16022        mContext.enforceCallingOrSelfPermission(
16023                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16024        mMoveCallbacks.register(callback);
16025    }
16026
16027    @Override
16028    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16029        mContext.enforceCallingOrSelfPermission(
16030                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16031        mMoveCallbacks.unregister(callback);
16032    }
16033
16034    @Override
16035    public boolean setInstallLocation(int loc) {
16036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16037                null);
16038        if (getInstallLocation() == loc) {
16039            return true;
16040        }
16041        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16042                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16043            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16044                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16045            return true;
16046        }
16047        return false;
16048   }
16049
16050    @Override
16051    public int getInstallLocation() {
16052        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16053                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16054                PackageHelper.APP_INSTALL_AUTO);
16055    }
16056
16057    /** Called by UserManagerService */
16058    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16059        mDirtyUsers.remove(userHandle);
16060        mSettings.removeUserLPw(userHandle);
16061        mPendingBroadcasts.remove(userHandle);
16062        if (mInstaller != null) {
16063            // Technically, we shouldn't be doing this with the package lock
16064            // held.  However, this is very rare, and there is already so much
16065            // other disk I/O going on, that we'll let it slide for now.
16066            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16067            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16068                final String volumeUuid = vol.getFsUuid();
16069                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16070                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16071            }
16072        }
16073        mUserNeedsBadging.delete(userHandle);
16074        removeUnusedPackagesLILPw(userManager, userHandle);
16075    }
16076
16077    /**
16078     * We're removing userHandle and would like to remove any downloaded packages
16079     * that are no longer in use by any other user.
16080     * @param userHandle the user being removed
16081     */
16082    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16083        final boolean DEBUG_CLEAN_APKS = false;
16084        int [] users = userManager.getUserIdsLPr();
16085        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16086        while (psit.hasNext()) {
16087            PackageSetting ps = psit.next();
16088            if (ps.pkg == null) {
16089                continue;
16090            }
16091            final String packageName = ps.pkg.packageName;
16092            // Skip over if system app
16093            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16094                continue;
16095            }
16096            if (DEBUG_CLEAN_APKS) {
16097                Slog.i(TAG, "Checking package " + packageName);
16098            }
16099            boolean keep = false;
16100            for (int i = 0; i < users.length; i++) {
16101                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16102                    keep = true;
16103                    if (DEBUG_CLEAN_APKS) {
16104                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16105                                + users[i]);
16106                    }
16107                    break;
16108                }
16109            }
16110            if (!keep) {
16111                if (DEBUG_CLEAN_APKS) {
16112                    Slog.i(TAG, "  Removing package " + packageName);
16113                }
16114                mHandler.post(new Runnable() {
16115                    public void run() {
16116                        deletePackageX(packageName, userHandle, 0);
16117                    } //end run
16118                });
16119            }
16120        }
16121    }
16122
16123    /** Called by UserManagerService */
16124    void createNewUserLILPw(int userHandle) {
16125        if (mInstaller != null) {
16126            mInstaller.createUserConfig(userHandle);
16127            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16128            applyFactoryDefaultBrowserLPw(userHandle);
16129            primeDomainVerificationsLPw(userHandle);
16130        }
16131    }
16132
16133    void newUserCreated(final int userHandle) {
16134        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16135    }
16136
16137    @Override
16138    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16139        mContext.enforceCallingOrSelfPermission(
16140                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16141                "Only package verification agents can read the verifier device identity");
16142
16143        synchronized (mPackages) {
16144            return mSettings.getVerifierDeviceIdentityLPw();
16145        }
16146    }
16147
16148    @Override
16149    public void setPermissionEnforced(String permission, boolean enforced) {
16150        // TODO: Now that we no longer change GID for storage, this should to away.
16151        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16152                "setPermissionEnforced");
16153        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16154            synchronized (mPackages) {
16155                if (mSettings.mReadExternalStorageEnforced == null
16156                        || mSettings.mReadExternalStorageEnforced != enforced) {
16157                    mSettings.mReadExternalStorageEnforced = enforced;
16158                    mSettings.writeLPr();
16159                }
16160            }
16161            // kill any non-foreground processes so we restart them and
16162            // grant/revoke the GID.
16163            final IActivityManager am = ActivityManagerNative.getDefault();
16164            if (am != null) {
16165                final long token = Binder.clearCallingIdentity();
16166                try {
16167                    am.killProcessesBelowForeground("setPermissionEnforcement");
16168                } catch (RemoteException e) {
16169                } finally {
16170                    Binder.restoreCallingIdentity(token);
16171                }
16172            }
16173        } else {
16174            throw new IllegalArgumentException("No selective enforcement for " + permission);
16175        }
16176    }
16177
16178    @Override
16179    @Deprecated
16180    public boolean isPermissionEnforced(String permission) {
16181        return true;
16182    }
16183
16184    @Override
16185    public boolean isStorageLow() {
16186        final long token = Binder.clearCallingIdentity();
16187        try {
16188            final DeviceStorageMonitorInternal
16189                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16190            if (dsm != null) {
16191                return dsm.isMemoryLow();
16192            } else {
16193                return false;
16194            }
16195        } finally {
16196            Binder.restoreCallingIdentity(token);
16197        }
16198    }
16199
16200    @Override
16201    public IPackageInstaller getPackageInstaller() {
16202        return mInstallerService;
16203    }
16204
16205    private boolean userNeedsBadging(int userId) {
16206        int index = mUserNeedsBadging.indexOfKey(userId);
16207        if (index < 0) {
16208            final UserInfo userInfo;
16209            final long token = Binder.clearCallingIdentity();
16210            try {
16211                userInfo = sUserManager.getUserInfo(userId);
16212            } finally {
16213                Binder.restoreCallingIdentity(token);
16214            }
16215            final boolean b;
16216            if (userInfo != null && userInfo.isManagedProfile()) {
16217                b = true;
16218            } else {
16219                b = false;
16220            }
16221            mUserNeedsBadging.put(userId, b);
16222            return b;
16223        }
16224        return mUserNeedsBadging.valueAt(index);
16225    }
16226
16227    @Override
16228    public KeySet getKeySetByAlias(String packageName, String alias) {
16229        if (packageName == null || alias == null) {
16230            return null;
16231        }
16232        synchronized(mPackages) {
16233            final PackageParser.Package pkg = mPackages.get(packageName);
16234            if (pkg == null) {
16235                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16236                throw new IllegalArgumentException("Unknown package: " + packageName);
16237            }
16238            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16239            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16240        }
16241    }
16242
16243    @Override
16244    public KeySet getSigningKeySet(String packageName) {
16245        if (packageName == null) {
16246            return null;
16247        }
16248        synchronized(mPackages) {
16249            final PackageParser.Package pkg = mPackages.get(packageName);
16250            if (pkg == null) {
16251                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16252                throw new IllegalArgumentException("Unknown package: " + packageName);
16253            }
16254            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16255                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16256                throw new SecurityException("May not access signing KeySet of other apps.");
16257            }
16258            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16259            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16260        }
16261    }
16262
16263    @Override
16264    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16265        if (packageName == null || ks == null) {
16266            return false;
16267        }
16268        synchronized(mPackages) {
16269            final PackageParser.Package pkg = mPackages.get(packageName);
16270            if (pkg == null) {
16271                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16272                throw new IllegalArgumentException("Unknown package: " + packageName);
16273            }
16274            IBinder ksh = ks.getToken();
16275            if (ksh instanceof KeySetHandle) {
16276                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16277                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16278            }
16279            return false;
16280        }
16281    }
16282
16283    @Override
16284    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16285        if (packageName == null || ks == null) {
16286            return false;
16287        }
16288        synchronized(mPackages) {
16289            final PackageParser.Package pkg = mPackages.get(packageName);
16290            if (pkg == null) {
16291                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16292                throw new IllegalArgumentException("Unknown package: " + packageName);
16293            }
16294            IBinder ksh = ks.getToken();
16295            if (ksh instanceof KeySetHandle) {
16296                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16297                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16298            }
16299            return false;
16300        }
16301    }
16302
16303    public void getUsageStatsIfNoPackageUsageInfo() {
16304        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16305            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16306            if (usm == null) {
16307                throw new IllegalStateException("UsageStatsManager must be initialized");
16308            }
16309            long now = System.currentTimeMillis();
16310            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16311            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16312                String packageName = entry.getKey();
16313                PackageParser.Package pkg = mPackages.get(packageName);
16314                if (pkg == null) {
16315                    continue;
16316                }
16317                UsageStats usage = entry.getValue();
16318                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16319                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16320            }
16321        }
16322    }
16323
16324    /**
16325     * Check and throw if the given before/after packages would be considered a
16326     * downgrade.
16327     */
16328    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16329            throws PackageManagerException {
16330        if (after.versionCode < before.mVersionCode) {
16331            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16332                    "Update version code " + after.versionCode + " is older than current "
16333                    + before.mVersionCode);
16334        } else if (after.versionCode == before.mVersionCode) {
16335            if (after.baseRevisionCode < before.baseRevisionCode) {
16336                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16337                        "Update base revision code " + after.baseRevisionCode
16338                        + " is older than current " + before.baseRevisionCode);
16339            }
16340
16341            if (!ArrayUtils.isEmpty(after.splitNames)) {
16342                for (int i = 0; i < after.splitNames.length; i++) {
16343                    final String splitName = after.splitNames[i];
16344                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16345                    if (j != -1) {
16346                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16347                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16348                                    "Update split " + splitName + " revision code "
16349                                    + after.splitRevisionCodes[i] + " is older than current "
16350                                    + before.splitRevisionCodes[j]);
16351                        }
16352                    }
16353                }
16354            }
16355        }
16356    }
16357
16358    private static class MoveCallbacks extends Handler {
16359        private static final int MSG_CREATED = 1;
16360        private static final int MSG_STATUS_CHANGED = 2;
16361
16362        private final RemoteCallbackList<IPackageMoveObserver>
16363                mCallbacks = new RemoteCallbackList<>();
16364
16365        private final SparseIntArray mLastStatus = new SparseIntArray();
16366
16367        public MoveCallbacks(Looper looper) {
16368            super(looper);
16369        }
16370
16371        public void register(IPackageMoveObserver callback) {
16372            mCallbacks.register(callback);
16373        }
16374
16375        public void unregister(IPackageMoveObserver callback) {
16376            mCallbacks.unregister(callback);
16377        }
16378
16379        @Override
16380        public void handleMessage(Message msg) {
16381            final SomeArgs args = (SomeArgs) msg.obj;
16382            final int n = mCallbacks.beginBroadcast();
16383            for (int i = 0; i < n; i++) {
16384                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16385                try {
16386                    invokeCallback(callback, msg.what, args);
16387                } catch (RemoteException ignored) {
16388                }
16389            }
16390            mCallbacks.finishBroadcast();
16391            args.recycle();
16392        }
16393
16394        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16395                throws RemoteException {
16396            switch (what) {
16397                case MSG_CREATED: {
16398                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16399                    break;
16400                }
16401                case MSG_STATUS_CHANGED: {
16402                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16403                    break;
16404                }
16405            }
16406        }
16407
16408        private void notifyCreated(int moveId, Bundle extras) {
16409            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16410
16411            final SomeArgs args = SomeArgs.obtain();
16412            args.argi1 = moveId;
16413            args.arg2 = extras;
16414            obtainMessage(MSG_CREATED, args).sendToTarget();
16415        }
16416
16417        private void notifyStatusChanged(int moveId, int status) {
16418            notifyStatusChanged(moveId, status, -1);
16419        }
16420
16421        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16422            Slog.v(TAG, "Move " + moveId + " status " + status);
16423
16424            final SomeArgs args = SomeArgs.obtain();
16425            args.argi1 = moveId;
16426            args.argi2 = status;
16427            args.arg3 = estMillis;
16428            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16429
16430            synchronized (mLastStatus) {
16431                mLastStatus.put(moveId, status);
16432            }
16433        }
16434    }
16435
16436    private final class OnPermissionChangeListeners extends Handler {
16437        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16438
16439        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16440                new RemoteCallbackList<>();
16441
16442        public OnPermissionChangeListeners(Looper looper) {
16443            super(looper);
16444        }
16445
16446        @Override
16447        public void handleMessage(Message msg) {
16448            switch (msg.what) {
16449                case MSG_ON_PERMISSIONS_CHANGED: {
16450                    final int uid = msg.arg1;
16451                    handleOnPermissionsChanged(uid);
16452                } break;
16453            }
16454        }
16455
16456        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16457            mPermissionListeners.register(listener);
16458
16459        }
16460
16461        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16462            mPermissionListeners.unregister(listener);
16463        }
16464
16465        public void onPermissionsChanged(int uid) {
16466            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16467                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16468            }
16469        }
16470
16471        private void handleOnPermissionsChanged(int uid) {
16472            final int count = mPermissionListeners.beginBroadcast();
16473            try {
16474                for (int i = 0; i < count; i++) {
16475                    IOnPermissionsChangeListener callback = mPermissionListeners
16476                            .getBroadcastItem(i);
16477                    try {
16478                        callback.onPermissionsChanged(uid);
16479                    } catch (RemoteException e) {
16480                        Log.e(TAG, "Permission listener is dead", e);
16481                    }
16482                }
16483            } finally {
16484                mPermissionListeners.finishBroadcast();
16485            }
16486        }
16487    }
16488
16489    private class PackageManagerInternalImpl extends PackageManagerInternal {
16490        @Override
16491        public void setLocationPackagesProvider(PackagesProvider provider) {
16492            synchronized (mPackages) {
16493                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16494            }
16495        }
16496
16497        @Override
16498        public void setImePackagesProvider(PackagesProvider provider) {
16499            synchronized (mPackages) {
16500                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16501            }
16502        }
16503
16504        @Override
16505        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16506            synchronized (mPackages) {
16507                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16508            }
16509        }
16510
16511        @Override
16512        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16513            synchronized (mPackages) {
16514                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16515            }
16516        }
16517
16518        @Override
16519        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16520            synchronized (mPackages) {
16521                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16522            }
16523        }
16524
16525        @Override
16526        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16527            synchronized (mPackages) {
16528                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16529            }
16530        }
16531
16532        @Override
16533        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16534            synchronized (mPackages) {
16535                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16536            }
16537        }
16538
16539        @Override
16540        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16541            synchronized (mPackages) {
16542                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16543                        packageName, userId);
16544            }
16545        }
16546
16547        @Override
16548        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16549            synchronized (mPackages) {
16550                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16551                        packageName, userId);
16552            }
16553        }
16554        @Override
16555        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16556            synchronized (mPackages) {
16557                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16558                        packageName, userId);
16559            }
16560        }
16561    }
16562
16563    @Override
16564    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16565        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16566        synchronized (mPackages) {
16567            final long identity = Binder.clearCallingIdentity();
16568            try {
16569                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16570                        packageNames, userId);
16571            } finally {
16572                Binder.restoreCallingIdentity(identity);
16573            }
16574        }
16575    }
16576
16577    private static void enforceSystemOrPhoneCaller(String tag) {
16578        int callingUid = Binder.getCallingUid();
16579        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16580            throw new SecurityException(
16581                    "Cannot call " + tag + " from UID " + callingUid);
16582        }
16583    }
16584}
16585