PackageManagerService.java revision 673fed99b931ce0efc17b0e549e7842e4775154c
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 *
277mmm frameworks/base/tests/AndroidTests
278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
280 *
281 * {@hide}
282 */
283public class PackageManagerService extends IPackageManager.Stub {
284    static final String TAG = "PackageManager";
285    static final boolean DEBUG_SETTINGS = false;
286    static final boolean DEBUG_PREFERRED = false;
287    static final boolean DEBUG_UPGRADE = false;
288    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
289    private static final boolean DEBUG_BACKUP = false;
290    private static final boolean DEBUG_INSTALL = false;
291    private static final boolean DEBUG_REMOVE = false;
292    private static final boolean DEBUG_BROADCASTS = false;
293    private static final boolean DEBUG_SHOW_INFO = false;
294    private static final boolean DEBUG_PACKAGE_INFO = false;
295    private static final boolean DEBUG_INTENT_MATCHING = false;
296    private static final boolean DEBUG_PACKAGE_SCANNING = false;
297    private static final boolean DEBUG_VERIFY = false;
298    private static final boolean DEBUG_DEXOPT = false;
299    private static final boolean DEBUG_ABI_SELECTION = false;
300
301    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
302
303    private static final int RADIO_UID = Process.PHONE_UID;
304    private static final int LOG_UID = Process.LOG_UID;
305    private static final int NFC_UID = Process.NFC_UID;
306    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
307    private static final int SHELL_UID = Process.SHELL_UID;
308
309    // Cap the size of permission trees that 3rd party apps can define
310    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
311
312    // Suffix used during package installation when copying/moving
313    // package apks to install directory.
314    private static final String INSTALL_PACKAGE_SUFFIX = "-";
315
316    static final int SCAN_NO_DEX = 1<<1;
317    static final int SCAN_FORCE_DEX = 1<<2;
318    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
319    static final int SCAN_NEW_INSTALL = 1<<4;
320    static final int SCAN_NO_PATHS = 1<<5;
321    static final int SCAN_UPDATE_TIME = 1<<6;
322    static final int SCAN_DEFER_DEX = 1<<7;
323    static final int SCAN_BOOTING = 1<<8;
324    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
325    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
326    static final int SCAN_REPLACING = 1<<11;
327    static final int SCAN_REQUIRE_KNOWN = 1<<12;
328    static final int SCAN_MOVE = 1<<13;
329    static final int SCAN_INITIAL = 1<<14;
330
331    static final int REMOVE_CHATTY = 1<<16;
332
333    private static final int[] EMPTY_INT_ARRAY = new int[0];
334
335    /**
336     * Timeout (in milliseconds) after which the watchdog should declare that
337     * our handler thread is wedged.  The usual default for such things is one
338     * minute but we sometimes do very lengthy I/O operations on this thread,
339     * such as installing multi-gigabyte applications, so ours needs to be longer.
340     */
341    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
342
343    /**
344     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
345     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
346     * settings entry if available, otherwise we use the hardcoded default.  If it's been
347     * more than this long since the last fstrim, we force one during the boot sequence.
348     *
349     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
350     * one gets run at the next available charging+idle time.  This final mandatory
351     * no-fstrim check kicks in only of the other scheduling criteria is never met.
352     */
353    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
354
355    /**
356     * Whether verification is enabled by default.
357     */
358    private static final boolean DEFAULT_VERIFY_ENABLE = true;
359
360    /**
361     * The default maximum time to wait for the verification agent to return in
362     * milliseconds.
363     */
364    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
365
366    /**
367     * The default response for package verification timeout.
368     *
369     * This can be either PackageManager.VERIFICATION_ALLOW or
370     * PackageManager.VERIFICATION_REJECT.
371     */
372    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
373
374    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
375
376    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
377            DEFAULT_CONTAINER_PACKAGE,
378            "com.android.defcontainer.DefaultContainerService");
379
380    private static final String KILL_APP_REASON_GIDS_CHANGED =
381            "permission grant or revoke changed gids";
382
383    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
384            "permissions revoked";
385
386    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
387
388    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
389
390    /** Permission grant: not grant the permission. */
391    private static final int GRANT_DENIED = 1;
392
393    /** Permission grant: grant the permission as an install permission. */
394    private static final int GRANT_INSTALL = 2;
395
396    /** Permission grant: grant the permission as an install permission for a legacy app. */
397    private static final int GRANT_INSTALL_LEGACY = 3;
398
399    /** Permission grant: grant the permission as a runtime one. */
400    private static final int GRANT_RUNTIME = 4;
401
402    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
403    private static final int GRANT_UPGRADE = 5;
404
405    /** Canonical intent used to identify what counts as a "web browser" app */
406    private static final Intent sBrowserIntent;
407    static {
408        sBrowserIntent = new Intent();
409        sBrowserIntent.setAction(Intent.ACTION_VIEW);
410        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
411        sBrowserIntent.setData(Uri.parse("http:"));
412    }
413
414    final ServiceThread mHandlerThread;
415
416    final PackageHandler mHandler;
417
418    /**
419     * Messages for {@link #mHandler} that need to wait for system ready before
420     * being dispatched.
421     */
422    private ArrayList<Message> mPostSystemReadyMessages;
423
424    final int mSdkVersion = Build.VERSION.SDK_INT;
425
426    final Context mContext;
427    final boolean mFactoryTest;
428    final boolean mOnlyCore;
429    final boolean mLazyDexOpt;
430    final long mDexOptLRUThresholdInMills;
431    final DisplayMetrics mMetrics;
432    final int mDefParseFlags;
433    final String[] mSeparateProcesses;
434    final boolean mIsUpgrade;
435
436    // This is where all application persistent data goes.
437    final File mAppDataDir;
438
439    // This is where all application persistent data goes for secondary users.
440    final File mUserAppDataDir;
441
442    /** The location for ASEC container files on internal storage. */
443    final String mAsecInternalPath;
444
445    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
446    // LOCK HELD.  Can be called with mInstallLock held.
447    @GuardedBy("mInstallLock")
448    final Installer mInstaller;
449
450    /** Directory where installed third-party apps stored */
451    final File mAppInstallDir;
452
453    /**
454     * Directory to which applications installed internally have their
455     * 32 bit native libraries copied.
456     */
457    private File mAppLib32InstallDir;
458
459    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
460    // apps.
461    final File mDrmAppPrivateInstallDir;
462
463    // ----------------------------------------------------------------
464
465    // Lock for state used when installing and doing other long running
466    // operations.  Methods that must be called with this lock held have
467    // the suffix "LI".
468    final Object mInstallLock = new Object();
469
470    // ----------------------------------------------------------------
471
472    // Keys are String (package name), values are Package.  This also serves
473    // as the lock for the global state.  Methods that must be called with
474    // this lock held have the prefix "LP".
475    @GuardedBy("mPackages")
476    final ArrayMap<String, PackageParser.Package> mPackages =
477            new ArrayMap<String, PackageParser.Package>();
478
479    // Tracks available target package names -> overlay package paths.
480    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
481        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
482
483    /**
484     * Tracks new system packages [receiving in an OTA] that we expect to
485     * find updated user-installed versions. Keys are package name, values
486     * are package location.
487     */
488    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
489
490    final Settings mSettings;
491    boolean mRestoredSettings;
492
493    // System configuration read by SystemConfig.
494    final int[] mGlobalGids;
495    final SparseArray<ArraySet<String>> mSystemPermissions;
496    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
497
498    // If mac_permissions.xml was found for seinfo labeling.
499    boolean mFoundPolicyFile;
500
501    // If a recursive restorecon of /data/data/<pkg> is needed.
502    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
503
504    public static final class SharedLibraryEntry {
505        public final String path;
506        public final String apk;
507
508        SharedLibraryEntry(String _path, String _apk) {
509            path = _path;
510            apk = _apk;
511        }
512    }
513
514    // Currently known shared libraries.
515    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
516            new ArrayMap<String, SharedLibraryEntry>();
517
518    // All available activities, for your resolving pleasure.
519    final ActivityIntentResolver mActivities =
520            new ActivityIntentResolver();
521
522    // All available receivers, for your resolving pleasure.
523    final ActivityIntentResolver mReceivers =
524            new ActivityIntentResolver();
525
526    // All available services, for your resolving pleasure.
527    final ServiceIntentResolver mServices = new ServiceIntentResolver();
528
529    // All available providers, for your resolving pleasure.
530    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
531
532    // Mapping from provider base names (first directory in content URI codePath)
533    // to the provider information.
534    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
535            new ArrayMap<String, PackageParser.Provider>();
536
537    // Mapping from instrumentation class names to info about them.
538    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
539            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
540
541    // Mapping from permission names to info about them.
542    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
543            new ArrayMap<String, PackageParser.PermissionGroup>();
544
545    // Packages whose data we have transfered into another package, thus
546    // should no longer exist.
547    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
548
549    // Broadcast actions that are only available to the system.
550    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
551
552    /** List of packages waiting for verification. */
553    final SparseArray<PackageVerificationState> mPendingVerification
554            = new SparseArray<PackageVerificationState>();
555
556    /** Set of packages associated with each app op permission. */
557    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
558
559    final PackageInstallerService mInstallerService;
560
561    private final PackageDexOptimizer mPackageDexOptimizer;
562
563    private AtomicInteger mNextMoveId = new AtomicInteger();
564    private final MoveCallbacks mMoveCallbacks;
565
566    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
567
568    // Cache of users who need badging.
569    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
570
571    /** Token for keys in mPendingVerification. */
572    private int mPendingVerificationToken = 0;
573
574    volatile boolean mSystemReady;
575    volatile boolean mSafeMode;
576    volatile boolean mHasSystemUidErrors;
577
578    ApplicationInfo mAndroidApplication;
579    final ActivityInfo mResolveActivity = new ActivityInfo();
580    final ResolveInfo mResolveInfo = new ResolveInfo();
581    ComponentName mResolveComponentName;
582    PackageParser.Package mPlatformPackage;
583    ComponentName mCustomResolverComponentName;
584
585    boolean mResolverReplaced = false;
586
587    private final ComponentName mIntentFilterVerifierComponent;
588    private int mIntentFilterVerificationToken = 0;
589
590    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
591            = new SparseArray<IntentFilterVerificationState>();
592
593    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
594            new DefaultPermissionGrantPolicy(this);
595
596    private static class IFVerificationParams {
597        PackageParser.Package pkg;
598        boolean replacing;
599        int userId;
600        int verifierUid;
601
602        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
603                int _userId, int _verifierUid) {
604            pkg = _pkg;
605            replacing = _replacing;
606            userId = _userId;
607            replacing = _replacing;
608            verifierUid = _verifierUid;
609        }
610    }
611
612    private interface IntentFilterVerifier<T extends IntentFilter> {
613        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
614                                               T filter, String packageName);
615        void startVerifications(int userId);
616        void receiveVerificationResponse(int verificationId);
617    }
618
619    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
620        private Context mContext;
621        private ComponentName mIntentFilterVerifierComponent;
622        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
623
624        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
625            mContext = context;
626            mIntentFilterVerifierComponent = verifierComponent;
627        }
628
629        private String getDefaultScheme() {
630            return IntentFilter.SCHEME_HTTPS;
631        }
632
633        @Override
634        public void startVerifications(int userId) {
635            // Launch verifications requests
636            int count = mCurrentIntentFilterVerifications.size();
637            for (int n=0; n<count; n++) {
638                int verificationId = mCurrentIntentFilterVerifications.get(n);
639                final IntentFilterVerificationState ivs =
640                        mIntentFilterVerificationStates.get(verificationId);
641
642                String packageName = ivs.getPackageName();
643
644                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
645                final int filterCount = filters.size();
646                ArraySet<String> domainsSet = new ArraySet<>();
647                for (int m=0; m<filterCount; m++) {
648                    PackageParser.ActivityIntentInfo filter = filters.get(m);
649                    domainsSet.addAll(filter.getHostsList());
650                }
651                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
652                synchronized (mPackages) {
653                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
654                            packageName, domainsList) != null) {
655                        scheduleWriteSettingsLocked();
656                    }
657                }
658                sendVerificationRequest(userId, verificationId, ivs);
659            }
660            mCurrentIntentFilterVerifications.clear();
661        }
662
663        private void sendVerificationRequest(int userId, int verificationId,
664                IntentFilterVerificationState ivs) {
665
666            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
667            verificationIntent.putExtra(
668                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
669                    verificationId);
670            verificationIntent.putExtra(
671                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
672                    getDefaultScheme());
673            verificationIntent.putExtra(
674                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
675                    ivs.getHostsString());
676            verificationIntent.putExtra(
677                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
678                    ivs.getPackageName());
679            verificationIntent.setComponent(mIntentFilterVerifierComponent);
680            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
681
682            UserHandle user = new UserHandle(userId);
683            mContext.sendBroadcastAsUser(verificationIntent, user);
684            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
685                    "Sending IntentFilter verification broadcast");
686        }
687
688        public void receiveVerificationResponse(int verificationId) {
689            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
690
691            final boolean verified = ivs.isVerified();
692
693            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
694            final int count = filters.size();
695            if (DEBUG_DOMAIN_VERIFICATION) {
696                Slog.i(TAG, "Received verification response " + verificationId
697                        + " for " + count + " filters, verified=" + verified);
698            }
699            for (int n=0; n<count; n++) {
700                PackageParser.ActivityIntentInfo filter = filters.get(n);
701                filter.setVerified(verified);
702
703                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
704                        + " verified with result:" + verified + " and hosts:"
705                        + ivs.getHostsString());
706            }
707
708            mIntentFilterVerificationStates.remove(verificationId);
709
710            final String packageName = ivs.getPackageName();
711            IntentFilterVerificationInfo ivi = null;
712
713            synchronized (mPackages) {
714                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
715            }
716            if (ivi == null) {
717                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
718                        + verificationId + " packageName:" + packageName);
719                return;
720            }
721            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
722                    "Updating IntentFilterVerificationInfo for package " + packageName
723                            +" verificationId:" + verificationId);
724
725            synchronized (mPackages) {
726                if (verified) {
727                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
728                } else {
729                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
730                }
731                scheduleWriteSettingsLocked();
732
733                final int userId = ivs.getUserId();
734                if (userId != UserHandle.USER_ALL) {
735                    final int userStatus =
736                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
737
738                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
739                    boolean needUpdate = false;
740
741                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
742                    // already been set by the User thru the Disambiguation dialog
743                    switch (userStatus) {
744                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
745                            if (verified) {
746                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
747                            } else {
748                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
749                            }
750                            needUpdate = true;
751                            break;
752
753                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
754                            if (verified) {
755                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
756                                needUpdate = true;
757                            }
758                            break;
759
760                        default:
761                            // Nothing to do
762                    }
763
764                    if (needUpdate) {
765                        mSettings.updateIntentFilterVerificationStatusLPw(
766                                packageName, updatedStatus, userId);
767                        scheduleWritePackageRestrictionsLocked(userId);
768                    }
769                }
770            }
771        }
772
773        @Override
774        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
775                    ActivityIntentInfo filter, String packageName) {
776            if (!hasValidDomains(filter)) {
777                return false;
778            }
779            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
780            if (ivs == null) {
781                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
782                        packageName);
783            }
784            if (DEBUG_DOMAIN_VERIFICATION) {
785                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
786            }
787            ivs.addFilter(filter);
788            return true;
789        }
790
791        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
792                int userId, int verificationId, String packageName) {
793            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
794                    verifierUid, userId, packageName);
795            ivs.setPendingState();
796            synchronized (mPackages) {
797                mIntentFilterVerificationStates.append(verificationId, ivs);
798                mCurrentIntentFilterVerifications.add(verificationId);
799            }
800            return ivs;
801        }
802    }
803
804    private static boolean hasValidDomains(ActivityIntentInfo filter) {
805        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
806                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
807                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
808    }
809
810    private IntentFilterVerifier mIntentFilterVerifier;
811
812    // Set of pending broadcasts for aggregating enable/disable of components.
813    static class PendingPackageBroadcasts {
814        // for each user id, a map of <package name -> components within that package>
815        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
816
817        public PendingPackageBroadcasts() {
818            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
819        }
820
821        public ArrayList<String> get(int userId, String packageName) {
822            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
823            return packages.get(packageName);
824        }
825
826        public void put(int userId, String packageName, ArrayList<String> components) {
827            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
828            packages.put(packageName, components);
829        }
830
831        public void remove(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
833            if (packages != null) {
834                packages.remove(packageName);
835            }
836        }
837
838        public void remove(int userId) {
839            mUidMap.remove(userId);
840        }
841
842        public int userIdCount() {
843            return mUidMap.size();
844        }
845
846        public int userIdAt(int n) {
847            return mUidMap.keyAt(n);
848        }
849
850        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
851            return mUidMap.get(userId);
852        }
853
854        public int size() {
855            // total number of pending broadcast entries across all userIds
856            int num = 0;
857            for (int i = 0; i< mUidMap.size(); i++) {
858                num += mUidMap.valueAt(i).size();
859            }
860            return num;
861        }
862
863        public void clear() {
864            mUidMap.clear();
865        }
866
867        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
868            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
869            if (map == null) {
870                map = new ArrayMap<String, ArrayList<String>>();
871                mUidMap.put(userId, map);
872            }
873            return map;
874        }
875    }
876    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
877
878    // Service Connection to remote media container service to copy
879    // package uri's from external media onto secure containers
880    // or internal storage.
881    private IMediaContainerService mContainerService = null;
882
883    static final int SEND_PENDING_BROADCAST = 1;
884    static final int MCS_BOUND = 3;
885    static final int END_COPY = 4;
886    static final int INIT_COPY = 5;
887    static final int MCS_UNBIND = 6;
888    static final int START_CLEANING_PACKAGE = 7;
889    static final int FIND_INSTALL_LOC = 8;
890    static final int POST_INSTALL = 9;
891    static final int MCS_RECONNECT = 10;
892    static final int MCS_GIVE_UP = 11;
893    static final int UPDATED_MEDIA_STATUS = 12;
894    static final int WRITE_SETTINGS = 13;
895    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
896    static final int PACKAGE_VERIFIED = 15;
897    static final int CHECK_PENDING_VERIFICATION = 16;
898    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
899    static final int INTENT_FILTER_VERIFIED = 18;
900
901    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
902
903    // Delay time in millisecs
904    static final int BROADCAST_DELAY = 10 * 1000;
905
906    static UserManagerService sUserManager;
907
908    // Stores a list of users whose package restrictions file needs to be updated
909    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
910
911    final private DefaultContainerConnection mDefContainerConn =
912            new DefaultContainerConnection();
913    class DefaultContainerConnection implements ServiceConnection {
914        public void onServiceConnected(ComponentName name, IBinder service) {
915            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
916            IMediaContainerService imcs =
917                IMediaContainerService.Stub.asInterface(service);
918            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
919        }
920
921        public void onServiceDisconnected(ComponentName name) {
922            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
923        }
924    }
925
926    // Recordkeeping of restore-after-install operations that are currently in flight
927    // between the Package Manager and the Backup Manager
928    class PostInstallData {
929        public InstallArgs args;
930        public PackageInstalledInfo res;
931
932        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
933            args = _a;
934            res = _r;
935        }
936    }
937
938    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
939    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
940
941    // XML tags for backup/restore of various bits of state
942    private static final String TAG_PREFERRED_BACKUP = "pa";
943    private static final String TAG_DEFAULT_APPS = "da";
944    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
945
946    final String mRequiredVerifierPackage;
947    final String mRequiredInstallerPackage;
948
949    private final PackageUsage mPackageUsage = new PackageUsage();
950
951    private class PackageUsage {
952        private static final int WRITE_INTERVAL
953            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
954
955        private final Object mFileLock = new Object();
956        private final AtomicLong mLastWritten = new AtomicLong(0);
957        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
958
959        private boolean mIsHistoricalPackageUsageAvailable = true;
960
961        boolean isHistoricalPackageUsageAvailable() {
962            return mIsHistoricalPackageUsageAvailable;
963        }
964
965        void write(boolean force) {
966            if (force) {
967                writeInternal();
968                return;
969            }
970            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
971                && !DEBUG_DEXOPT) {
972                return;
973            }
974            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
975                new Thread("PackageUsage_DiskWriter") {
976                    @Override
977                    public void run() {
978                        try {
979                            writeInternal();
980                        } finally {
981                            mBackgroundWriteRunning.set(false);
982                        }
983                    }
984                }.start();
985            }
986        }
987
988        private void writeInternal() {
989            synchronized (mPackages) {
990                synchronized (mFileLock) {
991                    AtomicFile file = getFile();
992                    FileOutputStream f = null;
993                    try {
994                        f = file.startWrite();
995                        BufferedOutputStream out = new BufferedOutputStream(f);
996                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
997                        StringBuilder sb = new StringBuilder();
998                        for (PackageParser.Package pkg : mPackages.values()) {
999                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1000                                continue;
1001                            }
1002                            sb.setLength(0);
1003                            sb.append(pkg.packageName);
1004                            sb.append(' ');
1005                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1006                            sb.append('\n');
1007                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1008                        }
1009                        out.flush();
1010                        file.finishWrite(f);
1011                    } catch (IOException e) {
1012                        if (f != null) {
1013                            file.failWrite(f);
1014                        }
1015                        Log.e(TAG, "Failed to write package usage times", e);
1016                    }
1017                }
1018            }
1019            mLastWritten.set(SystemClock.elapsedRealtime());
1020        }
1021
1022        void readLP() {
1023            synchronized (mFileLock) {
1024                AtomicFile file = getFile();
1025                BufferedInputStream in = null;
1026                try {
1027                    in = new BufferedInputStream(file.openRead());
1028                    StringBuffer sb = new StringBuffer();
1029                    while (true) {
1030                        String packageName = readToken(in, sb, ' ');
1031                        if (packageName == null) {
1032                            break;
1033                        }
1034                        String timeInMillisString = readToken(in, sb, '\n');
1035                        if (timeInMillisString == null) {
1036                            throw new IOException("Failed to find last usage time for package "
1037                                                  + packageName);
1038                        }
1039                        PackageParser.Package pkg = mPackages.get(packageName);
1040                        if (pkg == null) {
1041                            continue;
1042                        }
1043                        long timeInMillis;
1044                        try {
1045                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1046                        } catch (NumberFormatException e) {
1047                            throw new IOException("Failed to parse " + timeInMillisString
1048                                                  + " as a long.", e);
1049                        }
1050                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1051                    }
1052                } catch (FileNotFoundException expected) {
1053                    mIsHistoricalPackageUsageAvailable = false;
1054                } catch (IOException e) {
1055                    Log.w(TAG, "Failed to read package usage times", e);
1056                } finally {
1057                    IoUtils.closeQuietly(in);
1058                }
1059            }
1060            mLastWritten.set(SystemClock.elapsedRealtime());
1061        }
1062
1063        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1064                throws IOException {
1065            sb.setLength(0);
1066            while (true) {
1067                int ch = in.read();
1068                if (ch == -1) {
1069                    if (sb.length() == 0) {
1070                        return null;
1071                    }
1072                    throw new IOException("Unexpected EOF");
1073                }
1074                if (ch == endOfToken) {
1075                    return sb.toString();
1076                }
1077                sb.append((char)ch);
1078            }
1079        }
1080
1081        private AtomicFile getFile() {
1082            File dataDir = Environment.getDataDirectory();
1083            File systemDir = new File(dataDir, "system");
1084            File fname = new File(systemDir, "package-usage.list");
1085            return new AtomicFile(fname);
1086        }
1087    }
1088
1089    class PackageHandler extends Handler {
1090        private boolean mBound = false;
1091        final ArrayList<HandlerParams> mPendingInstalls =
1092            new ArrayList<HandlerParams>();
1093
1094        private boolean connectToService() {
1095            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1096                    " DefaultContainerService");
1097            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1098            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1099            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1100                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1101                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1102                mBound = true;
1103                return true;
1104            }
1105            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1106            return false;
1107        }
1108
1109        private void disconnectService() {
1110            mContainerService = null;
1111            mBound = false;
1112            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1113            mContext.unbindService(mDefContainerConn);
1114            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115        }
1116
1117        PackageHandler(Looper looper) {
1118            super(looper);
1119        }
1120
1121        public void handleMessage(Message msg) {
1122            try {
1123                doHandleMessage(msg);
1124            } finally {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126            }
1127        }
1128
1129        void doHandleMessage(Message msg) {
1130            switch (msg.what) {
1131                case INIT_COPY: {
1132                    HandlerParams params = (HandlerParams) msg.obj;
1133                    int idx = mPendingInstalls.size();
1134                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1135                    // If a bind was already initiated we dont really
1136                    // need to do anything. The pending install
1137                    // will be processed later on.
1138                    if (!mBound) {
1139                        // If this is the only one pending we might
1140                        // have to bind to the service again.
1141                        if (!connectToService()) {
1142                            Slog.e(TAG, "Failed to bind to media container service");
1143                            params.serviceError();
1144                            return;
1145                        } else {
1146                            // Once we bind to the service, the first
1147                            // pending request will be processed.
1148                            mPendingInstalls.add(idx, params);
1149                        }
1150                    } else {
1151                        mPendingInstalls.add(idx, params);
1152                        // Already bound to the service. Just make
1153                        // sure we trigger off processing the first request.
1154                        if (idx == 0) {
1155                            mHandler.sendEmptyMessage(MCS_BOUND);
1156                        }
1157                    }
1158                    break;
1159                }
1160                case MCS_BOUND: {
1161                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1162                    if (msg.obj != null) {
1163                        mContainerService = (IMediaContainerService) msg.obj;
1164                    }
1165                    if (mContainerService == null) {
1166                        if (!mBound) {
1167                            // Something seriously wrong since we are not bound and we are not
1168                            // waiting for connection. Bail out.
1169                            Slog.e(TAG, "Cannot bind to media container service");
1170                            for (HandlerParams params : mPendingInstalls) {
1171                                // Indicate service bind error
1172                                params.serviceError();
1173                            }
1174                            mPendingInstalls.clear();
1175                        } else {
1176                            Slog.w(TAG, "Waiting to connect to media container service");
1177                        }
1178                    } else if (mPendingInstalls.size() > 0) {
1179                        HandlerParams params = mPendingInstalls.get(0);
1180                        if (params != null) {
1181                            if (params.startCopy()) {
1182                                // We are done...  look for more work or to
1183                                // go idle.
1184                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1185                                        "Checking for more work or unbind...");
1186                                // Delete pending install
1187                                if (mPendingInstalls.size() > 0) {
1188                                    mPendingInstalls.remove(0);
1189                                }
1190                                if (mPendingInstalls.size() == 0) {
1191                                    if (mBound) {
1192                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1193                                                "Posting delayed MCS_UNBIND");
1194                                        removeMessages(MCS_UNBIND);
1195                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1196                                        // Unbind after a little delay, to avoid
1197                                        // continual thrashing.
1198                                        sendMessageDelayed(ubmsg, 10000);
1199                                    }
1200                                } else {
1201                                    // There are more pending requests in queue.
1202                                    // Just post MCS_BOUND message to trigger processing
1203                                    // of next pending install.
1204                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1205                                            "Posting MCS_BOUND for next work");
1206                                    mHandler.sendEmptyMessage(MCS_BOUND);
1207                                }
1208                            }
1209                        }
1210                    } else {
1211                        // Should never happen ideally.
1212                        Slog.w(TAG, "Empty queue");
1213                    }
1214                    break;
1215                }
1216                case MCS_RECONNECT: {
1217                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1218                    if (mPendingInstalls.size() > 0) {
1219                        if (mBound) {
1220                            disconnectService();
1221                        }
1222                        if (!connectToService()) {
1223                            Slog.e(TAG, "Failed to bind to media container service");
1224                            for (HandlerParams params : mPendingInstalls) {
1225                                // Indicate service bind error
1226                                params.serviceError();
1227                            }
1228                            mPendingInstalls.clear();
1229                        }
1230                    }
1231                    break;
1232                }
1233                case MCS_UNBIND: {
1234                    // If there is no actual work left, then time to unbind.
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1236
1237                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1238                        if (mBound) {
1239                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1240
1241                            disconnectService();
1242                        }
1243                    } else if (mPendingInstalls.size() > 0) {
1244                        // There are more pending requests in queue.
1245                        // Just post MCS_BOUND message to trigger processing
1246                        // of next pending install.
1247                        mHandler.sendEmptyMessage(MCS_BOUND);
1248                    }
1249
1250                    break;
1251                }
1252                case MCS_GIVE_UP: {
1253                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1254                    mPendingInstalls.remove(0);
1255                    break;
1256                }
1257                case SEND_PENDING_BROADCAST: {
1258                    String packages[];
1259                    ArrayList<String> components[];
1260                    int size = 0;
1261                    int uids[];
1262                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1263                    synchronized (mPackages) {
1264                        if (mPendingBroadcasts == null) {
1265                            return;
1266                        }
1267                        size = mPendingBroadcasts.size();
1268                        if (size <= 0) {
1269                            // Nothing to be done. Just return
1270                            return;
1271                        }
1272                        packages = new String[size];
1273                        components = new ArrayList[size];
1274                        uids = new int[size];
1275                        int i = 0;  // filling out the above arrays
1276
1277                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1278                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1279                            Iterator<Map.Entry<String, ArrayList<String>>> it
1280                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1281                                            .entrySet().iterator();
1282                            while (it.hasNext() && i < size) {
1283                                Map.Entry<String, ArrayList<String>> ent = it.next();
1284                                packages[i] = ent.getKey();
1285                                components[i] = ent.getValue();
1286                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1287                                uids[i] = (ps != null)
1288                                        ? UserHandle.getUid(packageUserId, ps.appId)
1289                                        : -1;
1290                                i++;
1291                            }
1292                        }
1293                        size = i;
1294                        mPendingBroadcasts.clear();
1295                    }
1296                    // Send broadcasts
1297                    for (int i = 0; i < size; i++) {
1298                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1299                    }
1300                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1301                    break;
1302                }
1303                case START_CLEANING_PACKAGE: {
1304                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1305                    final String packageName = (String)msg.obj;
1306                    final int userId = msg.arg1;
1307                    final boolean andCode = msg.arg2 != 0;
1308                    synchronized (mPackages) {
1309                        if (userId == UserHandle.USER_ALL) {
1310                            int[] users = sUserManager.getUserIds();
1311                            for (int user : users) {
1312                                mSettings.addPackageToCleanLPw(
1313                                        new PackageCleanItem(user, packageName, andCode));
1314                            }
1315                        } else {
1316                            mSettings.addPackageToCleanLPw(
1317                                    new PackageCleanItem(userId, packageName, andCode));
1318                        }
1319                    }
1320                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1321                    startCleaningPackages();
1322                } break;
1323                case POST_INSTALL: {
1324                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1325                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1326                    mRunningInstalls.delete(msg.arg1);
1327                    boolean deleteOld = false;
1328
1329                    if (data != null) {
1330                        InstallArgs args = data.args;
1331                        PackageInstalledInfo res = data.res;
1332
1333                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1334                            final String packageName = res.pkg.applicationInfo.packageName;
1335                            res.removedInfo.sendBroadcast(false, true, false);
1336                            Bundle extras = new Bundle(1);
1337                            extras.putInt(Intent.EXTRA_UID, res.uid);
1338
1339                            // Now that we successfully installed the package, grant runtime
1340                            // permissions if requested before broadcasting the install.
1341                            if ((args.installFlags
1342                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1343                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1344                                        args.installGrantPermissions);
1345                            }
1346
1347                            // Determine the set of users who are adding this
1348                            // package for the first time vs. those who are seeing
1349                            // an update.
1350                            int[] firstUsers;
1351                            int[] updateUsers = new int[0];
1352                            if (res.origUsers == null || res.origUsers.length == 0) {
1353                                firstUsers = res.newUsers;
1354                            } else {
1355                                firstUsers = new int[0];
1356                                for (int i=0; i<res.newUsers.length; i++) {
1357                                    int user = res.newUsers[i];
1358                                    boolean isNew = true;
1359                                    for (int j=0; j<res.origUsers.length; j++) {
1360                                        if (res.origUsers[j] == user) {
1361                                            isNew = false;
1362                                            break;
1363                                        }
1364                                    }
1365                                    if (isNew) {
1366                                        int[] newFirst = new int[firstUsers.length+1];
1367                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1368                                                firstUsers.length);
1369                                        newFirst[firstUsers.length] = user;
1370                                        firstUsers = newFirst;
1371                                    } else {
1372                                        int[] newUpdate = new int[updateUsers.length+1];
1373                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1374                                                updateUsers.length);
1375                                        newUpdate[updateUsers.length] = user;
1376                                        updateUsers = newUpdate;
1377                                    }
1378                                }
1379                            }
1380                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1381                                    packageName, extras, null, null, firstUsers);
1382                            final boolean update = res.removedInfo.removedPackage != null;
1383                            if (update) {
1384                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1385                            }
1386                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1387                                    packageName, extras, null, null, updateUsers);
1388                            if (update) {
1389                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1390                                        packageName, extras, null, null, updateUsers);
1391                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1392                                        null, null, packageName, null, updateUsers);
1393
1394                                // treat asec-hosted packages like removable media on upgrade
1395                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1396                                    if (DEBUG_INSTALL) {
1397                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1398                                                + " is ASEC-hosted -> AVAILABLE");
1399                                    }
1400                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1401                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1402                                    pkgList.add(packageName);
1403                                    sendResourcesChangedBroadcast(true, true,
1404                                            pkgList,uidArray, null);
1405                                }
1406                            }
1407                            if (res.removedInfo.args != null) {
1408                                // Remove the replaced package's older resources safely now
1409                                deleteOld = true;
1410                            }
1411
1412                            // If this app is a browser and it's newly-installed for some
1413                            // users, clear any default-browser state in those users
1414                            if (firstUsers.length > 0) {
1415                                // the app's nature doesn't depend on the user, so we can just
1416                                // check its browser nature in any user and generalize.
1417                                if (packageIsBrowser(packageName, firstUsers[0])) {
1418                                    synchronized (mPackages) {
1419                                        for (int userId : firstUsers) {
1420                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1421                                        }
1422                                    }
1423                                }
1424                            }
1425                            // Log current value of "unknown sources" setting
1426                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1427                                getUnknownSourcesSettings());
1428                        }
1429                        // Force a gc to clear up things
1430                        Runtime.getRuntime().gc();
1431                        // We delete after a gc for applications  on sdcard.
1432                        if (deleteOld) {
1433                            synchronized (mInstallLock) {
1434                                res.removedInfo.args.doPostDeleteLI(true);
1435                            }
1436                        }
1437                        if (args.observer != null) {
1438                            try {
1439                                Bundle extras = extrasForInstallResult(res);
1440                                args.observer.onPackageInstalled(res.name, res.returnCode,
1441                                        res.returnMsg, extras);
1442                            } catch (RemoteException e) {
1443                                Slog.i(TAG, "Observer no longer exists.");
1444                            }
1445                        }
1446                    } else {
1447                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1448                    }
1449                } break;
1450                case UPDATED_MEDIA_STATUS: {
1451                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1452                    boolean reportStatus = msg.arg1 == 1;
1453                    boolean doGc = msg.arg2 == 1;
1454                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1455                    if (doGc) {
1456                        // Force a gc to clear up stale containers.
1457                        Runtime.getRuntime().gc();
1458                    }
1459                    if (msg.obj != null) {
1460                        @SuppressWarnings("unchecked")
1461                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1462                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1463                        // Unload containers
1464                        unloadAllContainers(args);
1465                    }
1466                    if (reportStatus) {
1467                        try {
1468                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1469                            PackageHelper.getMountService().finishMediaUpdate();
1470                        } catch (RemoteException e) {
1471                            Log.e(TAG, "MountService not running?");
1472                        }
1473                    }
1474                } break;
1475                case WRITE_SETTINGS: {
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477                    synchronized (mPackages) {
1478                        removeMessages(WRITE_SETTINGS);
1479                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1480                        mSettings.writeLPr();
1481                        mDirtyUsers.clear();
1482                    }
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                } break;
1485                case WRITE_PACKAGE_RESTRICTIONS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489                        for (int userId : mDirtyUsers) {
1490                            mSettings.writePackageRestrictionsLPr(userId);
1491                        }
1492                        mDirtyUsers.clear();
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                } break;
1496                case CHECK_PENDING_VERIFICATION: {
1497                    final int verificationId = msg.arg1;
1498                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1499
1500                    if ((state != null) && !state.timeoutExtended()) {
1501                        final InstallArgs args = state.getInstallArgs();
1502                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1503
1504                        Slog.i(TAG, "Verification timed out for " + originUri);
1505                        mPendingVerification.remove(verificationId);
1506
1507                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1508
1509                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1510                            Slog.i(TAG, "Continuing with installation of " + originUri);
1511                            state.setVerifierResponse(Binder.getCallingUid(),
1512                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_ALLOW,
1515                                    state.getInstallArgs().getUser());
1516                            try {
1517                                ret = args.copyApk(mContainerService, true);
1518                            } catch (RemoteException e) {
1519                                Slog.e(TAG, "Could not contact the ContainerService");
1520                            }
1521                        } else {
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_REJECT,
1524                                    state.getInstallArgs().getUser());
1525                        }
1526
1527                        processPendingInstall(args, ret);
1528                        mHandler.sendEmptyMessage(MCS_UNBIND);
1529                    }
1530                    break;
1531                }
1532                case PACKAGE_VERIFIED: {
1533                    final int verificationId = msg.arg1;
1534
1535                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1536                    if (state == null) {
1537                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1538                        break;
1539                    }
1540
1541                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1542
1543                    state.setVerifierResponse(response.callerUid, response.code);
1544
1545                    if (state.isVerificationComplete()) {
1546                        mPendingVerification.remove(verificationId);
1547
1548                        final InstallArgs args = state.getInstallArgs();
1549                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1550
1551                        int ret;
1552                        if (state.isInstallAllowed()) {
1553                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1554                            broadcastPackageVerified(verificationId, originUri,
1555                                    response.code, state.getInstallArgs().getUser());
1556                            try {
1557                                ret = args.copyApk(mContainerService, true);
1558                            } catch (RemoteException e) {
1559                                Slog.e(TAG, "Could not contact the ContainerService");
1560                            }
1561                        } else {
1562                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1563                        }
1564
1565                        processPendingInstall(args, ret);
1566
1567                        mHandler.sendEmptyMessage(MCS_UNBIND);
1568                    }
1569
1570                    break;
1571                }
1572                case START_INTENT_FILTER_VERIFICATIONS: {
1573                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1574                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1575                            params.replacing, params.pkg);
1576                    break;
1577                }
1578                case INTENT_FILTER_VERIFIED: {
1579                    final int verificationId = msg.arg1;
1580
1581                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1582                            verificationId);
1583                    if (state == null) {
1584                        Slog.w(TAG, "Invalid IntentFilter verification token "
1585                                + verificationId + " received");
1586                        break;
1587                    }
1588
1589                    final int userId = state.getUserId();
1590
1591                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1592                            "Processing IntentFilter verification with token:"
1593                            + verificationId + " and userId:" + userId);
1594
1595                    final IntentFilterVerificationResponse response =
1596                            (IntentFilterVerificationResponse) msg.obj;
1597
1598                    state.setVerifierResponse(response.callerUid, response.code);
1599
1600                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1601                            "IntentFilter verification with token:" + verificationId
1602                            + " and userId:" + userId
1603                            + " is settings verifier response with response code:"
1604                            + response.code);
1605
1606                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1607                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1608                                + response.getFailedDomainsString());
1609                    }
1610
1611                    if (state.isVerificationComplete()) {
1612                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1613                    } else {
1614                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                                "IntentFilter verification with token:" + verificationId
1616                                + " was not said to be complete");
1617                    }
1618
1619                    break;
1620                }
1621            }
1622        }
1623    }
1624
1625    private StorageEventListener mStorageListener = new StorageEventListener() {
1626        @Override
1627        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1628            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1629                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1630                    final String volumeUuid = vol.getFsUuid();
1631
1632                    // Clean up any users or apps that were removed or recreated
1633                    // while this volume was missing
1634                    reconcileUsers(volumeUuid);
1635                    reconcileApps(volumeUuid);
1636
1637                    // Clean up any install sessions that expired or were
1638                    // cancelled while this volume was missing
1639                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1640
1641                    loadPrivatePackages(vol);
1642
1643                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1644                    unloadPrivatePackages(vol);
1645                }
1646            }
1647
1648            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1649                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1650                    updateExternalMediaStatus(true, false);
1651                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1652                    updateExternalMediaStatus(false, false);
1653                }
1654            }
1655        }
1656
1657        @Override
1658        public void onVolumeForgotten(String fsUuid) {
1659            if (TextUtils.isEmpty(fsUuid)) {
1660                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1661                return;
1662            }
1663
1664            // Remove any apps installed on the forgotten volume
1665            synchronized (mPackages) {
1666                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1667                for (PackageSetting ps : packages) {
1668                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1669                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1670                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1671                }
1672
1673                mSettings.onVolumeForgotten(fsUuid);
1674                mSettings.writeLPr();
1675            }
1676        }
1677    };
1678
1679    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1680            String[] grantedPermissions) {
1681        if (userId >= UserHandle.USER_OWNER) {
1682            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1683        } else if (userId == UserHandle.USER_ALL) {
1684            final int[] userIds;
1685            synchronized (mPackages) {
1686                userIds = UserManagerService.getInstance().getUserIds();
1687            }
1688            for (int someUserId : userIds) {
1689                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1690            }
1691        }
1692
1693        // We could have touched GID membership, so flush out packages.list
1694        synchronized (mPackages) {
1695            mSettings.writePackageListLPr();
1696        }
1697    }
1698
1699    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1700            String[] grantedPermissions) {
1701        SettingBase sb = (SettingBase) pkg.mExtras;
1702        if (sb == null) {
1703            return;
1704        }
1705
1706        PermissionsState permissionsState = sb.getPermissionsState();
1707
1708        for (String permission : pkg.requestedPermissions) {
1709            BasePermission bp = mSettings.mPermissions.get(permission);
1710            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1711                    || ArrayUtils.contains(grantedPermissions, permission))) {
1712                permissionsState.grantRuntimePermission(bp, userId);
1713            }
1714        }
1715    }
1716
1717    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1718        Bundle extras = null;
1719        switch (res.returnCode) {
1720            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1721                extras = new Bundle();
1722                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1723                        res.origPermission);
1724                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1725                        res.origPackage);
1726                break;
1727            }
1728            case PackageManager.INSTALL_SUCCEEDED: {
1729                extras = new Bundle();
1730                extras.putBoolean(Intent.EXTRA_REPLACING,
1731                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1732                break;
1733            }
1734        }
1735        return extras;
1736    }
1737
1738    void scheduleWriteSettingsLocked() {
1739        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1740            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1741        }
1742    }
1743
1744    void scheduleWritePackageRestrictionsLocked(int userId) {
1745        if (!sUserManager.exists(userId)) return;
1746        mDirtyUsers.add(userId);
1747        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1748            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1749        }
1750    }
1751
1752    public static PackageManagerService main(Context context, Installer installer,
1753            boolean factoryTest, boolean onlyCore) {
1754        PackageManagerService m = new PackageManagerService(context, installer,
1755                factoryTest, onlyCore);
1756        ServiceManager.addService("package", m);
1757        return m;
1758    }
1759
1760    static String[] splitString(String str, char sep) {
1761        int count = 1;
1762        int i = 0;
1763        while ((i=str.indexOf(sep, i)) >= 0) {
1764            count++;
1765            i++;
1766        }
1767
1768        String[] res = new String[count];
1769        i=0;
1770        count = 0;
1771        int lastI=0;
1772        while ((i=str.indexOf(sep, i)) >= 0) {
1773            res[count] = str.substring(lastI, i);
1774            count++;
1775            i++;
1776            lastI = i;
1777        }
1778        res[count] = str.substring(lastI, str.length());
1779        return res;
1780    }
1781
1782    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1783        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1784                Context.DISPLAY_SERVICE);
1785        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1786    }
1787
1788    public PackageManagerService(Context context, Installer installer,
1789            boolean factoryTest, boolean onlyCore) {
1790        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1791                SystemClock.uptimeMillis());
1792
1793        if (mSdkVersion <= 0) {
1794            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1795        }
1796
1797        mContext = context;
1798        mFactoryTest = factoryTest;
1799        mOnlyCore = onlyCore;
1800        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1801        mMetrics = new DisplayMetrics();
1802        mSettings = new Settings(mPackages);
1803        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1804                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1805        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1806                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1807        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1808                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1809        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1810                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1811        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1812                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1813        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1814                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1815
1816        // TODO: add a property to control this?
1817        long dexOptLRUThresholdInMinutes;
1818        if (mLazyDexOpt) {
1819            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1820        } else {
1821            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1822        }
1823        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1824
1825        String separateProcesses = SystemProperties.get("debug.separate_processes");
1826        if (separateProcesses != null && separateProcesses.length() > 0) {
1827            if ("*".equals(separateProcesses)) {
1828                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1829                mSeparateProcesses = null;
1830                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1831            } else {
1832                mDefParseFlags = 0;
1833                mSeparateProcesses = separateProcesses.split(",");
1834                Slog.w(TAG, "Running with debug.separate_processes: "
1835                        + separateProcesses);
1836            }
1837        } else {
1838            mDefParseFlags = 0;
1839            mSeparateProcesses = null;
1840        }
1841
1842        mInstaller = installer;
1843        mPackageDexOptimizer = new PackageDexOptimizer(this);
1844        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1845
1846        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1847                FgThread.get().getLooper());
1848
1849        getDefaultDisplayMetrics(context, mMetrics);
1850
1851        SystemConfig systemConfig = SystemConfig.getInstance();
1852        mGlobalGids = systemConfig.getGlobalGids();
1853        mSystemPermissions = systemConfig.getSystemPermissions();
1854        mAvailableFeatures = systemConfig.getAvailableFeatures();
1855
1856        synchronized (mInstallLock) {
1857        // writer
1858        synchronized (mPackages) {
1859            mHandlerThread = new ServiceThread(TAG,
1860                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1861            mHandlerThread.start();
1862            mHandler = new PackageHandler(mHandlerThread.getLooper());
1863            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1864
1865            File dataDir = Environment.getDataDirectory();
1866            mAppDataDir = new File(dataDir, "data");
1867            mAppInstallDir = new File(dataDir, "app");
1868            mAppLib32InstallDir = new File(dataDir, "app-lib");
1869            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1870            mUserAppDataDir = new File(dataDir, "user");
1871            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1872
1873            sUserManager = new UserManagerService(context, this,
1874                    mInstallLock, mPackages);
1875
1876            // Propagate permission configuration in to package manager.
1877            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1878                    = systemConfig.getPermissions();
1879            for (int i=0; i<permConfig.size(); i++) {
1880                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1881                BasePermission bp = mSettings.mPermissions.get(perm.name);
1882                if (bp == null) {
1883                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1884                    mSettings.mPermissions.put(perm.name, bp);
1885                }
1886                if (perm.gids != null) {
1887                    bp.setGids(perm.gids, perm.perUser);
1888                }
1889            }
1890
1891            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1892            for (int i=0; i<libConfig.size(); i++) {
1893                mSharedLibraries.put(libConfig.keyAt(i),
1894                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1895            }
1896
1897            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1898
1899            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1900                    mSdkVersion, mOnlyCore);
1901
1902            String customResolverActivity = Resources.getSystem().getString(
1903                    R.string.config_customResolverActivity);
1904            if (TextUtils.isEmpty(customResolverActivity)) {
1905                customResolverActivity = null;
1906            } else {
1907                mCustomResolverComponentName = ComponentName.unflattenFromString(
1908                        customResolverActivity);
1909            }
1910
1911            long startTime = SystemClock.uptimeMillis();
1912
1913            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1914                    startTime);
1915
1916            // Set flag to monitor and not change apk file paths when
1917            // scanning install directories.
1918            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1919
1920            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1921
1922            /**
1923             * Add everything in the in the boot class path to the
1924             * list of process files because dexopt will have been run
1925             * if necessary during zygote startup.
1926             */
1927            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1928            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1929
1930            if (bootClassPath != null) {
1931                String[] bootClassPathElements = splitString(bootClassPath, ':');
1932                for (String element : bootClassPathElements) {
1933                    alreadyDexOpted.add(element);
1934                }
1935            } else {
1936                Slog.w(TAG, "No BOOTCLASSPATH found!");
1937            }
1938
1939            if (systemServerClassPath != null) {
1940                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1941                for (String element : systemServerClassPathElements) {
1942                    alreadyDexOpted.add(element);
1943                }
1944            } else {
1945                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1946            }
1947
1948            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1949            final String[] dexCodeInstructionSets =
1950                    getDexCodeInstructionSets(
1951                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1952
1953            /**
1954             * Ensure all external libraries have had dexopt run on them.
1955             */
1956            if (mSharedLibraries.size() > 0) {
1957                // NOTE: For now, we're compiling these system "shared libraries"
1958                // (and framework jars) into all available architectures. It's possible
1959                // to compile them only when we come across an app that uses them (there's
1960                // already logic for that in scanPackageLI) but that adds some complexity.
1961                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1962                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1963                        final String lib = libEntry.path;
1964                        if (lib == null) {
1965                            continue;
1966                        }
1967
1968                        try {
1969                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1970                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1971                                alreadyDexOpted.add(lib);
1972                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1973                            }
1974                        } catch (FileNotFoundException e) {
1975                            Slog.w(TAG, "Library not found: " + lib);
1976                        } catch (IOException e) {
1977                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1978                                    + e.getMessage());
1979                        }
1980                    }
1981                }
1982            }
1983
1984            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1985
1986            // Gross hack for now: we know this file doesn't contain any
1987            // code, so don't dexopt it to avoid the resulting log spew.
1988            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1989
1990            // Gross hack for now: we know this file is only part of
1991            // the boot class path for art, so don't dexopt it to
1992            // avoid the resulting log spew.
1993            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1994
1995            /**
1996             * There are a number of commands implemented in Java, which
1997             * we currently need to do the dexopt on so that they can be
1998             * run from a non-root shell.
1999             */
2000            String[] frameworkFiles = frameworkDir.list();
2001            if (frameworkFiles != null) {
2002                // TODO: We could compile these only for the most preferred ABI. We should
2003                // first double check that the dex files for these commands are not referenced
2004                // by other system apps.
2005                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2006                    for (int i=0; i<frameworkFiles.length; i++) {
2007                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2008                        String path = libPath.getPath();
2009                        // Skip the file if we already did it.
2010                        if (alreadyDexOpted.contains(path)) {
2011                            continue;
2012                        }
2013                        // Skip the file if it is not a type we want to dexopt.
2014                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2015                            continue;
2016                        }
2017                        try {
2018                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2019                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2020                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2021                            }
2022                        } catch (FileNotFoundException e) {
2023                            Slog.w(TAG, "Jar not found: " + path);
2024                        } catch (IOException e) {
2025                            Slog.w(TAG, "Exception reading jar: " + path, e);
2026                        }
2027                    }
2028                }
2029            }
2030
2031            // Collect vendor overlay packages.
2032            // (Do this before scanning any apps.)
2033            // For security and version matching reason, only consider
2034            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2035            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2036            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2037                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2038
2039            // Find base frameworks (resource packages without code).
2040            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2041                    | PackageParser.PARSE_IS_SYSTEM_DIR
2042                    | PackageParser.PARSE_IS_PRIVILEGED,
2043                    scanFlags | SCAN_NO_DEX, 0);
2044
2045            // Collected privileged system packages.
2046            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2047            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2048                    | PackageParser.PARSE_IS_SYSTEM_DIR
2049                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2050
2051            // Collect ordinary system packages.
2052            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2053            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2054                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2055
2056            // Collect all vendor packages.
2057            File vendorAppDir = new File("/vendor/app");
2058            try {
2059                vendorAppDir = vendorAppDir.getCanonicalFile();
2060            } catch (IOException e) {
2061                // failed to look up canonical path, continue with original one
2062            }
2063            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2064                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2065
2066            // Collect all OEM packages.
2067            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2068            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2069                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2070
2071            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2072            mInstaller.moveFiles();
2073
2074            // Prune any system packages that no longer exist.
2075            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2076            if (!mOnlyCore) {
2077                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2078                while (psit.hasNext()) {
2079                    PackageSetting ps = psit.next();
2080
2081                    /*
2082                     * If this is not a system app, it can't be a
2083                     * disable system app.
2084                     */
2085                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2086                        continue;
2087                    }
2088
2089                    /*
2090                     * If the package is scanned, it's not erased.
2091                     */
2092                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2093                    if (scannedPkg != null) {
2094                        /*
2095                         * If the system app is both scanned and in the
2096                         * disabled packages list, then it must have been
2097                         * added via OTA. Remove it from the currently
2098                         * scanned package so the previously user-installed
2099                         * application can be scanned.
2100                         */
2101                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2102                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2103                                    + ps.name + "; removing system app.  Last known codePath="
2104                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2105                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2106                                    + scannedPkg.mVersionCode);
2107                            removePackageLI(ps, true);
2108                            mExpectingBetter.put(ps.name, ps.codePath);
2109                        }
2110
2111                        continue;
2112                    }
2113
2114                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2115                        psit.remove();
2116                        logCriticalInfo(Log.WARN, "System package " + ps.name
2117                                + " no longer exists; wiping its data");
2118                        removeDataDirsLI(null, ps.name);
2119                    } else {
2120                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2121                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2122                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2123                        }
2124                    }
2125                }
2126            }
2127
2128            //look for any incomplete package installations
2129            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2130            //clean up list
2131            for(int i = 0; i < deletePkgsList.size(); i++) {
2132                //clean up here
2133                cleanupInstallFailedPackage(deletePkgsList.get(i));
2134            }
2135            //delete tmp files
2136            deleteTempPackageFiles();
2137
2138            // Remove any shared userIDs that have no associated packages
2139            mSettings.pruneSharedUsersLPw();
2140
2141            if (!mOnlyCore) {
2142                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2143                        SystemClock.uptimeMillis());
2144                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2145
2146                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2147                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2148
2149                /**
2150                 * Remove disable package settings for any updated system
2151                 * apps that were removed via an OTA. If they're not a
2152                 * previously-updated app, remove them completely.
2153                 * Otherwise, just revoke their system-level permissions.
2154                 */
2155                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2156                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2157                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2158
2159                    String msg;
2160                    if (deletedPkg == null) {
2161                        msg = "Updated system package " + deletedAppName
2162                                + " no longer exists; wiping its data";
2163                        removeDataDirsLI(null, deletedAppName);
2164                    } else {
2165                        msg = "Updated system app + " + deletedAppName
2166                                + " no longer present; removing system privileges for "
2167                                + deletedAppName;
2168
2169                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2170
2171                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2172                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2173                    }
2174                    logCriticalInfo(Log.WARN, msg);
2175                }
2176
2177                /**
2178                 * Make sure all system apps that we expected to appear on
2179                 * the userdata partition actually showed up. If they never
2180                 * appeared, crawl back and revive the system version.
2181                 */
2182                for (int i = 0; i < mExpectingBetter.size(); i++) {
2183                    final String packageName = mExpectingBetter.keyAt(i);
2184                    if (!mPackages.containsKey(packageName)) {
2185                        final File scanFile = mExpectingBetter.valueAt(i);
2186
2187                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2188                                + " but never showed up; reverting to system");
2189
2190                        final int reparseFlags;
2191                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2192                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2193                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2194                                    | PackageParser.PARSE_IS_PRIVILEGED;
2195                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2196                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2197                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2198                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2199                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2200                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2201                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2202                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2203                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2204                        } else {
2205                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2206                            continue;
2207                        }
2208
2209                        mSettings.enableSystemPackageLPw(packageName);
2210
2211                        try {
2212                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2213                        } catch (PackageManagerException e) {
2214                            Slog.e(TAG, "Failed to parse original system package: "
2215                                    + e.getMessage());
2216                        }
2217                    }
2218                }
2219            }
2220            mExpectingBetter.clear();
2221
2222            // Now that we know all of the shared libraries, update all clients to have
2223            // the correct library paths.
2224            updateAllSharedLibrariesLPw();
2225
2226            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2227                // NOTE: We ignore potential failures here during a system scan (like
2228                // the rest of the commands above) because there's precious little we
2229                // can do about it. A settings error is reported, though.
2230                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2231                        false /* force dexopt */, false /* defer dexopt */);
2232            }
2233
2234            // Now that we know all the packages we are keeping,
2235            // read and update their last usage times.
2236            mPackageUsage.readLP();
2237
2238            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2239                    SystemClock.uptimeMillis());
2240            Slog.i(TAG, "Time to scan packages: "
2241                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2242                    + " seconds");
2243
2244            // If the platform SDK has changed since the last time we booted,
2245            // we need to re-grant app permission to catch any new ones that
2246            // appear.  This is really a hack, and means that apps can in some
2247            // cases get permissions that the user didn't initially explicitly
2248            // allow...  it would be nice to have some better way to handle
2249            // this situation.
2250            final VersionInfo ver = mSettings.getInternalVersion();
2251
2252            int updateFlags = UPDATE_PERMISSIONS_ALL;
2253            if (ver.sdkVersion != mSdkVersion) {
2254                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2255                        + mSdkVersion + "; regranting permissions for internal storage");
2256                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2257            }
2258            updatePermissionsLPw(null, null, updateFlags);
2259            ver.sdkVersion = mSdkVersion;
2260
2261            // If this is the first boot, and it is a normal boot, then
2262            // we need to initialize the default preferred apps.
2263            if (!mRestoredSettings && !onlyCore) {
2264                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2265                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2266                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2267            }
2268
2269            // If this is first boot after an OTA, and a normal boot, then
2270            // we need to clear code cache directories.
2271            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2272            if (mIsUpgrade && !onlyCore) {
2273                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2274                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2275                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2276                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2277                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2278                    }
2279                }
2280                ver.fingerprint = Build.FINGERPRINT;
2281            }
2282
2283            checkDefaultBrowser();
2284
2285            // All the changes are done during package scanning.
2286            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2287
2288            // can downgrade to reader
2289            mSettings.writeLPr();
2290
2291            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2292                    SystemClock.uptimeMillis());
2293
2294            mRequiredVerifierPackage = getRequiredVerifierLPr();
2295            mRequiredInstallerPackage = getRequiredInstallerLPr();
2296
2297            mInstallerService = new PackageInstallerService(context, this);
2298
2299            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2300            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2301                    mIntentFilterVerifierComponent);
2302
2303        } // synchronized (mPackages)
2304        } // synchronized (mInstallLock)
2305
2306        // Now after opening every single application zip, make sure they
2307        // are all flushed.  Not really needed, but keeps things nice and
2308        // tidy.
2309        Runtime.getRuntime().gc();
2310
2311        // Expose private service for system components to use.
2312        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2313    }
2314
2315    @Override
2316    public boolean isFirstBoot() {
2317        return !mRestoredSettings;
2318    }
2319
2320    @Override
2321    public boolean isOnlyCoreApps() {
2322        return mOnlyCore;
2323    }
2324
2325    @Override
2326    public boolean isUpgrade() {
2327        return mIsUpgrade;
2328    }
2329
2330    private String getRequiredVerifierLPr() {
2331        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2332        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2333                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2334
2335        String requiredVerifier = null;
2336
2337        final int N = receivers.size();
2338        for (int i = 0; i < N; i++) {
2339            final ResolveInfo info = receivers.get(i);
2340
2341            if (info.activityInfo == null) {
2342                continue;
2343            }
2344
2345            final String packageName = info.activityInfo.packageName;
2346
2347            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2348                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2349                continue;
2350            }
2351
2352            if (requiredVerifier != null) {
2353                throw new RuntimeException("There can be only one required verifier");
2354            }
2355
2356            requiredVerifier = packageName;
2357        }
2358
2359        return requiredVerifier;
2360    }
2361
2362    private String getRequiredInstallerLPr() {
2363        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2364        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2365        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2366
2367        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2368                PACKAGE_MIME_TYPE, 0, 0);
2369
2370        String requiredInstaller = null;
2371
2372        final int N = installers.size();
2373        for (int i = 0; i < N; i++) {
2374            final ResolveInfo info = installers.get(i);
2375            final String packageName = info.activityInfo.packageName;
2376
2377            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2378                continue;
2379            }
2380
2381            if (requiredInstaller != null) {
2382                throw new RuntimeException("There must be one required installer");
2383            }
2384
2385            requiredInstaller = packageName;
2386        }
2387
2388        if (requiredInstaller == null) {
2389            throw new RuntimeException("There must be one required installer");
2390        }
2391
2392        return requiredInstaller;
2393    }
2394
2395    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2396        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2397        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2398                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2399
2400        ComponentName verifierComponentName = null;
2401
2402        int priority = -1000;
2403        final int N = receivers.size();
2404        for (int i = 0; i < N; i++) {
2405            final ResolveInfo info = receivers.get(i);
2406
2407            if (info.activityInfo == null) {
2408                continue;
2409            }
2410
2411            final String packageName = info.activityInfo.packageName;
2412
2413            final PackageSetting ps = mSettings.mPackages.get(packageName);
2414            if (ps == null) {
2415                continue;
2416            }
2417
2418            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2419                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2420                continue;
2421            }
2422
2423            // Select the IntentFilterVerifier with the highest priority
2424            if (priority < info.priority) {
2425                priority = info.priority;
2426                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2427                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2428                        + verifierComponentName + " with priority: " + info.priority);
2429            }
2430        }
2431
2432        return verifierComponentName;
2433    }
2434
2435    private void primeDomainVerificationsLPw(int userId) {
2436        if (DEBUG_DOMAIN_VERIFICATION) {
2437            Slog.d(TAG, "Priming domain verifications in user " + userId);
2438        }
2439
2440        SystemConfig systemConfig = SystemConfig.getInstance();
2441        ArraySet<String> packages = systemConfig.getLinkedApps();
2442        ArraySet<String> domains = new ArraySet<String>();
2443
2444        for (String packageName : packages) {
2445            PackageParser.Package pkg = mPackages.get(packageName);
2446            if (pkg != null) {
2447                if (!pkg.isSystemApp()) {
2448                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2449                    continue;
2450                }
2451
2452                domains.clear();
2453                for (PackageParser.Activity a : pkg.activities) {
2454                    for (ActivityIntentInfo filter : a.intents) {
2455                        if (hasValidDomains(filter)) {
2456                            domains.addAll(filter.getHostsList());
2457                        }
2458                    }
2459                }
2460
2461                if (domains.size() > 0) {
2462                    if (DEBUG_DOMAIN_VERIFICATION) {
2463                        Slog.v(TAG, "      + " + packageName);
2464                    }
2465                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2466                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2467                    // and then 'always' in the per-user state actually used for intent resolution.
2468                    final IntentFilterVerificationInfo ivi;
2469                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2470                            new ArrayList<String>(domains));
2471                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2472                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2473                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2474                } else {
2475                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2476                            + "' does not handle web links");
2477                }
2478            } else {
2479                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2480            }
2481        }
2482
2483        scheduleWritePackageRestrictionsLocked(userId);
2484        scheduleWriteSettingsLocked();
2485    }
2486
2487    private void applyFactoryDefaultBrowserLPw(int userId) {
2488        // The default browser app's package name is stored in a string resource,
2489        // with a product-specific overlay used for vendor customization.
2490        String browserPkg = mContext.getResources().getString(
2491                com.android.internal.R.string.default_browser);
2492        if (!TextUtils.isEmpty(browserPkg)) {
2493            // non-empty string => required to be a known package
2494            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2495            if (ps == null) {
2496                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2497                browserPkg = null;
2498            } else {
2499                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2500            }
2501        }
2502
2503        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2504        // default.  If there's more than one, just leave everything alone.
2505        if (browserPkg == null) {
2506            calculateDefaultBrowserLPw(userId);
2507        }
2508    }
2509
2510    private void calculateDefaultBrowserLPw(int userId) {
2511        List<String> allBrowsers = resolveAllBrowserApps(userId);
2512        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2513        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2514    }
2515
2516    private List<String> resolveAllBrowserApps(int userId) {
2517        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2518        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2519                PackageManager.MATCH_ALL, userId);
2520
2521        final int count = list.size();
2522        List<String> result = new ArrayList<String>(count);
2523        for (int i=0; i<count; i++) {
2524            ResolveInfo info = list.get(i);
2525            if (info.activityInfo == null
2526                    || !info.handleAllWebDataURI
2527                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2528                    || result.contains(info.activityInfo.packageName)) {
2529                continue;
2530            }
2531            result.add(info.activityInfo.packageName);
2532        }
2533
2534        return result;
2535    }
2536
2537    private boolean packageIsBrowser(String packageName, int userId) {
2538        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2539                PackageManager.MATCH_ALL, userId);
2540        final int N = list.size();
2541        for (int i = 0; i < N; i++) {
2542            ResolveInfo info = list.get(i);
2543            if (packageName.equals(info.activityInfo.packageName)) {
2544                return true;
2545            }
2546        }
2547        return false;
2548    }
2549
2550    private void checkDefaultBrowser() {
2551        final int myUserId = UserHandle.myUserId();
2552        final String packageName = getDefaultBrowserPackageName(myUserId);
2553        if (packageName != null) {
2554            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2555            if (info == null) {
2556                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2557                synchronized (mPackages) {
2558                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2559                }
2560            }
2561        }
2562    }
2563
2564    @Override
2565    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2566            throws RemoteException {
2567        try {
2568            return super.onTransact(code, data, reply, flags);
2569        } catch (RuntimeException e) {
2570            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2571                Slog.wtf(TAG, "Package Manager Crash", e);
2572            }
2573            throw e;
2574        }
2575    }
2576
2577    void cleanupInstallFailedPackage(PackageSetting ps) {
2578        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2579
2580        removeDataDirsLI(ps.volumeUuid, ps.name);
2581        if (ps.codePath != null) {
2582            if (ps.codePath.isDirectory()) {
2583                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2584            } else {
2585                ps.codePath.delete();
2586            }
2587        }
2588        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2589            if (ps.resourcePath.isDirectory()) {
2590                FileUtils.deleteContents(ps.resourcePath);
2591            }
2592            ps.resourcePath.delete();
2593        }
2594        mSettings.removePackageLPw(ps.name);
2595    }
2596
2597    static int[] appendInts(int[] cur, int[] add) {
2598        if (add == null) return cur;
2599        if (cur == null) return add;
2600        final int N = add.length;
2601        for (int i=0; i<N; i++) {
2602            cur = appendInt(cur, add[i]);
2603        }
2604        return cur;
2605    }
2606
2607    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2608        if (!sUserManager.exists(userId)) return null;
2609        final PackageSetting ps = (PackageSetting) p.mExtras;
2610        if (ps == null) {
2611            return null;
2612        }
2613
2614        final PermissionsState permissionsState = ps.getPermissionsState();
2615
2616        final int[] gids = permissionsState.computeGids(userId);
2617        final Set<String> permissions = permissionsState.getPermissions(userId);
2618        final PackageUserState state = ps.readUserState(userId);
2619
2620        return PackageParser.generatePackageInfo(p, gids, flags,
2621                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2622    }
2623
2624    @Override
2625    public boolean isPackageFrozen(String packageName) {
2626        synchronized (mPackages) {
2627            final PackageSetting ps = mSettings.mPackages.get(packageName);
2628            if (ps != null) {
2629                return ps.frozen;
2630            }
2631        }
2632        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2633        return true;
2634    }
2635
2636    @Override
2637    public boolean isPackageAvailable(String packageName, int userId) {
2638        if (!sUserManager.exists(userId)) return false;
2639        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2640        synchronized (mPackages) {
2641            PackageParser.Package p = mPackages.get(packageName);
2642            if (p != null) {
2643                final PackageSetting ps = (PackageSetting) p.mExtras;
2644                if (ps != null) {
2645                    final PackageUserState state = ps.readUserState(userId);
2646                    if (state != null) {
2647                        return PackageParser.isAvailable(state);
2648                    }
2649                }
2650            }
2651        }
2652        return false;
2653    }
2654
2655    @Override
2656    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2657        if (!sUserManager.exists(userId)) return null;
2658        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2659        // reader
2660        synchronized (mPackages) {
2661            PackageParser.Package p = mPackages.get(packageName);
2662            if (DEBUG_PACKAGE_INFO)
2663                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2664            if (p != null) {
2665                return generatePackageInfo(p, flags, userId);
2666            }
2667            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2668                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2669            }
2670        }
2671        return null;
2672    }
2673
2674    @Override
2675    public String[] currentToCanonicalPackageNames(String[] names) {
2676        String[] out = new String[names.length];
2677        // reader
2678        synchronized (mPackages) {
2679            for (int i=names.length-1; i>=0; i--) {
2680                PackageSetting ps = mSettings.mPackages.get(names[i]);
2681                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2682            }
2683        }
2684        return out;
2685    }
2686
2687    @Override
2688    public String[] canonicalToCurrentPackageNames(String[] names) {
2689        String[] out = new String[names.length];
2690        // reader
2691        synchronized (mPackages) {
2692            for (int i=names.length-1; i>=0; i--) {
2693                String cur = mSettings.mRenamedPackages.get(names[i]);
2694                out[i] = cur != null ? cur : names[i];
2695            }
2696        }
2697        return out;
2698    }
2699
2700    @Override
2701    public int getPackageUid(String packageName, int userId) {
2702        if (!sUserManager.exists(userId)) return -1;
2703        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2704
2705        // reader
2706        synchronized (mPackages) {
2707            PackageParser.Package p = mPackages.get(packageName);
2708            if(p != null) {
2709                return UserHandle.getUid(userId, p.applicationInfo.uid);
2710            }
2711            PackageSetting ps = mSettings.mPackages.get(packageName);
2712            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2713                return -1;
2714            }
2715            p = ps.pkg;
2716            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2717        }
2718    }
2719
2720    @Override
2721    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2722        if (!sUserManager.exists(userId)) {
2723            return null;
2724        }
2725
2726        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2727                "getPackageGids");
2728
2729        // reader
2730        synchronized (mPackages) {
2731            PackageParser.Package p = mPackages.get(packageName);
2732            if (DEBUG_PACKAGE_INFO) {
2733                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2734            }
2735            if (p != null) {
2736                PackageSetting ps = (PackageSetting) p.mExtras;
2737                return ps.getPermissionsState().computeGids(userId);
2738            }
2739        }
2740
2741        return null;
2742    }
2743
2744    static PermissionInfo generatePermissionInfo(
2745            BasePermission bp, int flags) {
2746        if (bp.perm != null) {
2747            return PackageParser.generatePermissionInfo(bp.perm, flags);
2748        }
2749        PermissionInfo pi = new PermissionInfo();
2750        pi.name = bp.name;
2751        pi.packageName = bp.sourcePackage;
2752        pi.nonLocalizedLabel = bp.name;
2753        pi.protectionLevel = bp.protectionLevel;
2754        return pi;
2755    }
2756
2757    @Override
2758    public PermissionInfo getPermissionInfo(String name, int flags) {
2759        // reader
2760        synchronized (mPackages) {
2761            final BasePermission p = mSettings.mPermissions.get(name);
2762            if (p != null) {
2763                return generatePermissionInfo(p, flags);
2764            }
2765            return null;
2766        }
2767    }
2768
2769    @Override
2770    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2771        // reader
2772        synchronized (mPackages) {
2773            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2774            for (BasePermission p : mSettings.mPermissions.values()) {
2775                if (group == null) {
2776                    if (p.perm == null || p.perm.info.group == null) {
2777                        out.add(generatePermissionInfo(p, flags));
2778                    }
2779                } else {
2780                    if (p.perm != null && group.equals(p.perm.info.group)) {
2781                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2782                    }
2783                }
2784            }
2785
2786            if (out.size() > 0) {
2787                return out;
2788            }
2789            return mPermissionGroups.containsKey(group) ? out : null;
2790        }
2791    }
2792
2793    @Override
2794    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2795        // reader
2796        synchronized (mPackages) {
2797            return PackageParser.generatePermissionGroupInfo(
2798                    mPermissionGroups.get(name), flags);
2799        }
2800    }
2801
2802    @Override
2803    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2804        // reader
2805        synchronized (mPackages) {
2806            final int N = mPermissionGroups.size();
2807            ArrayList<PermissionGroupInfo> out
2808                    = new ArrayList<PermissionGroupInfo>(N);
2809            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2810                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2811            }
2812            return out;
2813        }
2814    }
2815
2816    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2817            int userId) {
2818        if (!sUserManager.exists(userId)) return null;
2819        PackageSetting ps = mSettings.mPackages.get(packageName);
2820        if (ps != null) {
2821            if (ps.pkg == null) {
2822                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2823                        flags, userId);
2824                if (pInfo != null) {
2825                    return pInfo.applicationInfo;
2826                }
2827                return null;
2828            }
2829            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2830                    ps.readUserState(userId), userId);
2831        }
2832        return null;
2833    }
2834
2835    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2836            int userId) {
2837        if (!sUserManager.exists(userId)) return null;
2838        PackageSetting ps = mSettings.mPackages.get(packageName);
2839        if (ps != null) {
2840            PackageParser.Package pkg = ps.pkg;
2841            if (pkg == null) {
2842                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2843                    return null;
2844                }
2845                // Only data remains, so we aren't worried about code paths
2846                pkg = new PackageParser.Package(packageName);
2847                pkg.applicationInfo.packageName = packageName;
2848                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2849                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2850                pkg.applicationInfo.dataDir = Environment
2851                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2852                        .getAbsolutePath();
2853                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2854                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2855            }
2856            return generatePackageInfo(pkg, flags, userId);
2857        }
2858        return null;
2859    }
2860
2861    @Override
2862    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2863        if (!sUserManager.exists(userId)) return null;
2864        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2865        // writer
2866        synchronized (mPackages) {
2867            PackageParser.Package p = mPackages.get(packageName);
2868            if (DEBUG_PACKAGE_INFO) Log.v(
2869                    TAG, "getApplicationInfo " + packageName
2870                    + ": " + p);
2871            if (p != null) {
2872                PackageSetting ps = mSettings.mPackages.get(packageName);
2873                if (ps == null) return null;
2874                // Note: isEnabledLP() does not apply here - always return info
2875                return PackageParser.generateApplicationInfo(
2876                        p, flags, ps.readUserState(userId), userId);
2877            }
2878            if ("android".equals(packageName)||"system".equals(packageName)) {
2879                return mAndroidApplication;
2880            }
2881            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2882                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2883            }
2884        }
2885        return null;
2886    }
2887
2888    @Override
2889    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2890            final IPackageDataObserver observer) {
2891        mContext.enforceCallingOrSelfPermission(
2892                android.Manifest.permission.CLEAR_APP_CACHE, null);
2893        // Queue up an async operation since clearing cache may take a little while.
2894        mHandler.post(new Runnable() {
2895            public void run() {
2896                mHandler.removeCallbacks(this);
2897                int retCode = -1;
2898                synchronized (mInstallLock) {
2899                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2900                    if (retCode < 0) {
2901                        Slog.w(TAG, "Couldn't clear application caches");
2902                    }
2903                }
2904                if (observer != null) {
2905                    try {
2906                        observer.onRemoveCompleted(null, (retCode >= 0));
2907                    } catch (RemoteException e) {
2908                        Slog.w(TAG, "RemoveException when invoking call back");
2909                    }
2910                }
2911            }
2912        });
2913    }
2914
2915    @Override
2916    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2917            final IntentSender pi) {
2918        mContext.enforceCallingOrSelfPermission(
2919                android.Manifest.permission.CLEAR_APP_CACHE, null);
2920        // Queue up an async operation since clearing cache may take a little while.
2921        mHandler.post(new Runnable() {
2922            public void run() {
2923                mHandler.removeCallbacks(this);
2924                int retCode = -1;
2925                synchronized (mInstallLock) {
2926                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2927                    if (retCode < 0) {
2928                        Slog.w(TAG, "Couldn't clear application caches");
2929                    }
2930                }
2931                if(pi != null) {
2932                    try {
2933                        // Callback via pending intent
2934                        int code = (retCode >= 0) ? 1 : 0;
2935                        pi.sendIntent(null, code, null,
2936                                null, null);
2937                    } catch (SendIntentException e1) {
2938                        Slog.i(TAG, "Failed to send pending intent");
2939                    }
2940                }
2941            }
2942        });
2943    }
2944
2945    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2946        synchronized (mInstallLock) {
2947            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2948                throw new IOException("Failed to free enough space");
2949            }
2950        }
2951    }
2952
2953    @Override
2954    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2955        if (!sUserManager.exists(userId)) return null;
2956        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2957        synchronized (mPackages) {
2958            PackageParser.Activity a = mActivities.mActivities.get(component);
2959
2960            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2961            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2962                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2963                if (ps == null) return null;
2964                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2965                        userId);
2966            }
2967            if (mResolveComponentName.equals(component)) {
2968                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2969                        new PackageUserState(), userId);
2970            }
2971        }
2972        return null;
2973    }
2974
2975    @Override
2976    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2977            String resolvedType) {
2978        synchronized (mPackages) {
2979            if (component.equals(mResolveComponentName)) {
2980                // The resolver supports EVERYTHING!
2981                return true;
2982            }
2983            PackageParser.Activity a = mActivities.mActivities.get(component);
2984            if (a == null) {
2985                return false;
2986            }
2987            for (int i=0; i<a.intents.size(); i++) {
2988                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2989                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2990                    return true;
2991                }
2992            }
2993            return false;
2994        }
2995    }
2996
2997    @Override
2998    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2999        if (!sUserManager.exists(userId)) return null;
3000        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3001        synchronized (mPackages) {
3002            PackageParser.Activity a = mReceivers.mActivities.get(component);
3003            if (DEBUG_PACKAGE_INFO) Log.v(
3004                TAG, "getReceiverInfo " + component + ": " + a);
3005            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3006                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3007                if (ps == null) return null;
3008                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3009                        userId);
3010            }
3011        }
3012        return null;
3013    }
3014
3015    @Override
3016    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3017        if (!sUserManager.exists(userId)) return null;
3018        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3019        synchronized (mPackages) {
3020            PackageParser.Service s = mServices.mServices.get(component);
3021            if (DEBUG_PACKAGE_INFO) Log.v(
3022                TAG, "getServiceInfo " + component + ": " + s);
3023            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3024                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3025                if (ps == null) return null;
3026                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3027                        userId);
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3035        if (!sUserManager.exists(userId)) return null;
3036        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3037        synchronized (mPackages) {
3038            PackageParser.Provider p = mProviders.mProviders.get(component);
3039            if (DEBUG_PACKAGE_INFO) Log.v(
3040                TAG, "getProviderInfo " + component + ": " + p);
3041            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3042                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3043                if (ps == null) return null;
3044                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3045                        userId);
3046            }
3047        }
3048        return null;
3049    }
3050
3051    @Override
3052    public String[] getSystemSharedLibraryNames() {
3053        Set<String> libSet;
3054        synchronized (mPackages) {
3055            libSet = mSharedLibraries.keySet();
3056            int size = libSet.size();
3057            if (size > 0) {
3058                String[] libs = new String[size];
3059                libSet.toArray(libs);
3060                return libs;
3061            }
3062        }
3063        return null;
3064    }
3065
3066    /**
3067     * @hide
3068     */
3069    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3070        synchronized (mPackages) {
3071            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3072            if (lib != null && lib.apk != null) {
3073                return mPackages.get(lib.apk);
3074            }
3075        }
3076        return null;
3077    }
3078
3079    @Override
3080    public FeatureInfo[] getSystemAvailableFeatures() {
3081        Collection<FeatureInfo> featSet;
3082        synchronized (mPackages) {
3083            featSet = mAvailableFeatures.values();
3084            int size = featSet.size();
3085            if (size > 0) {
3086                FeatureInfo[] features = new FeatureInfo[size+1];
3087                featSet.toArray(features);
3088                FeatureInfo fi = new FeatureInfo();
3089                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3090                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3091                features[size] = fi;
3092                return features;
3093            }
3094        }
3095        return null;
3096    }
3097
3098    @Override
3099    public boolean hasSystemFeature(String name) {
3100        synchronized (mPackages) {
3101            return mAvailableFeatures.containsKey(name);
3102        }
3103    }
3104
3105    private void checkValidCaller(int uid, int userId) {
3106        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3107            return;
3108
3109        throw new SecurityException("Caller uid=" + uid
3110                + " is not privileged to communicate with user=" + userId);
3111    }
3112
3113    @Override
3114    public int checkPermission(String permName, String pkgName, int userId) {
3115        if (!sUserManager.exists(userId)) {
3116            return PackageManager.PERMISSION_DENIED;
3117        }
3118
3119        synchronized (mPackages) {
3120            final PackageParser.Package p = mPackages.get(pkgName);
3121            if (p != null && p.mExtras != null) {
3122                final PackageSetting ps = (PackageSetting) p.mExtras;
3123                final PermissionsState permissionsState = ps.getPermissionsState();
3124                if (permissionsState.hasPermission(permName, userId)) {
3125                    return PackageManager.PERMISSION_GRANTED;
3126                }
3127                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3128                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3129                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3130                    return PackageManager.PERMISSION_GRANTED;
3131                }
3132            }
3133        }
3134
3135        return PackageManager.PERMISSION_DENIED;
3136    }
3137
3138    @Override
3139    public int checkUidPermission(String permName, int uid) {
3140        final int userId = UserHandle.getUserId(uid);
3141
3142        if (!sUserManager.exists(userId)) {
3143            return PackageManager.PERMISSION_DENIED;
3144        }
3145
3146        synchronized (mPackages) {
3147            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3148            if (obj != null) {
3149                final SettingBase ps = (SettingBase) obj;
3150                final PermissionsState permissionsState = ps.getPermissionsState();
3151                if (permissionsState.hasPermission(permName, userId)) {
3152                    return PackageManager.PERMISSION_GRANTED;
3153                }
3154                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3155                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3156                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3157                    return PackageManager.PERMISSION_GRANTED;
3158                }
3159            } else {
3160                ArraySet<String> perms = mSystemPermissions.get(uid);
3161                if (perms != null) {
3162                    if (perms.contains(permName)) {
3163                        return PackageManager.PERMISSION_GRANTED;
3164                    }
3165                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3166                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3167                        return PackageManager.PERMISSION_GRANTED;
3168                    }
3169                }
3170            }
3171        }
3172
3173        return PackageManager.PERMISSION_DENIED;
3174    }
3175
3176    @Override
3177    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3178        if (UserHandle.getCallingUserId() != userId) {
3179            mContext.enforceCallingPermission(
3180                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3181                    "isPermissionRevokedByPolicy for user " + userId);
3182        }
3183
3184        if (checkPermission(permission, packageName, userId)
3185                == PackageManager.PERMISSION_GRANTED) {
3186            return false;
3187        }
3188
3189        final long identity = Binder.clearCallingIdentity();
3190        try {
3191            final int flags = getPermissionFlags(permission, packageName, userId);
3192            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3193        } finally {
3194            Binder.restoreCallingIdentity(identity);
3195        }
3196    }
3197
3198    /**
3199     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3200     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3201     * @param checkShell TODO(yamasani):
3202     * @param message the message to log on security exception
3203     */
3204    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3205            boolean checkShell, String message) {
3206        if (userId < 0) {
3207            throw new IllegalArgumentException("Invalid userId " + userId);
3208        }
3209        if (checkShell) {
3210            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3211        }
3212        if (userId == UserHandle.getUserId(callingUid)) return;
3213        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3214            if (requireFullPermission) {
3215                mContext.enforceCallingOrSelfPermission(
3216                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3217            } else {
3218                try {
3219                    mContext.enforceCallingOrSelfPermission(
3220                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3221                } catch (SecurityException se) {
3222                    mContext.enforceCallingOrSelfPermission(
3223                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3224                }
3225            }
3226        }
3227    }
3228
3229    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3230        if (callingUid == Process.SHELL_UID) {
3231            if (userHandle >= 0
3232                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3233                throw new SecurityException("Shell does not have permission to access user "
3234                        + userHandle);
3235            } else if (userHandle < 0) {
3236                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3237                        + Debug.getCallers(3));
3238            }
3239        }
3240    }
3241
3242    private BasePermission findPermissionTreeLP(String permName) {
3243        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3244            if (permName.startsWith(bp.name) &&
3245                    permName.length() > bp.name.length() &&
3246                    permName.charAt(bp.name.length()) == '.') {
3247                return bp;
3248            }
3249        }
3250        return null;
3251    }
3252
3253    private BasePermission checkPermissionTreeLP(String permName) {
3254        if (permName != null) {
3255            BasePermission bp = findPermissionTreeLP(permName);
3256            if (bp != null) {
3257                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3258                    return bp;
3259                }
3260                throw new SecurityException("Calling uid "
3261                        + Binder.getCallingUid()
3262                        + " is not allowed to add to permission tree "
3263                        + bp.name + " owned by uid " + bp.uid);
3264            }
3265        }
3266        throw new SecurityException("No permission tree found for " + permName);
3267    }
3268
3269    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3270        if (s1 == null) {
3271            return s2 == null;
3272        }
3273        if (s2 == null) {
3274            return false;
3275        }
3276        if (s1.getClass() != s2.getClass()) {
3277            return false;
3278        }
3279        return s1.equals(s2);
3280    }
3281
3282    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3283        if (pi1.icon != pi2.icon) return false;
3284        if (pi1.logo != pi2.logo) return false;
3285        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3286        if (!compareStrings(pi1.name, pi2.name)) return false;
3287        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3288        // We'll take care of setting this one.
3289        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3290        // These are not currently stored in settings.
3291        //if (!compareStrings(pi1.group, pi2.group)) return false;
3292        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3293        //if (pi1.labelRes != pi2.labelRes) return false;
3294        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3295        return true;
3296    }
3297
3298    int permissionInfoFootprint(PermissionInfo info) {
3299        int size = info.name.length();
3300        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3301        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3302        return size;
3303    }
3304
3305    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3306        int size = 0;
3307        for (BasePermission perm : mSettings.mPermissions.values()) {
3308            if (perm.uid == tree.uid) {
3309                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3310            }
3311        }
3312        return size;
3313    }
3314
3315    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3316        // We calculate the max size of permissions defined by this uid and throw
3317        // if that plus the size of 'info' would exceed our stated maximum.
3318        if (tree.uid != Process.SYSTEM_UID) {
3319            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3320            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3321                throw new SecurityException("Permission tree size cap exceeded");
3322            }
3323        }
3324    }
3325
3326    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3327        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3328            throw new SecurityException("Label must be specified in permission");
3329        }
3330        BasePermission tree = checkPermissionTreeLP(info.name);
3331        BasePermission bp = mSettings.mPermissions.get(info.name);
3332        boolean added = bp == null;
3333        boolean changed = true;
3334        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3335        if (added) {
3336            enforcePermissionCapLocked(info, tree);
3337            bp = new BasePermission(info.name, tree.sourcePackage,
3338                    BasePermission.TYPE_DYNAMIC);
3339        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3340            throw new SecurityException(
3341                    "Not allowed to modify non-dynamic permission "
3342                    + info.name);
3343        } else {
3344            if (bp.protectionLevel == fixedLevel
3345                    && bp.perm.owner.equals(tree.perm.owner)
3346                    && bp.uid == tree.uid
3347                    && comparePermissionInfos(bp.perm.info, info)) {
3348                changed = false;
3349            }
3350        }
3351        bp.protectionLevel = fixedLevel;
3352        info = new PermissionInfo(info);
3353        info.protectionLevel = fixedLevel;
3354        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3355        bp.perm.info.packageName = tree.perm.info.packageName;
3356        bp.uid = tree.uid;
3357        if (added) {
3358            mSettings.mPermissions.put(info.name, bp);
3359        }
3360        if (changed) {
3361            if (!async) {
3362                mSettings.writeLPr();
3363            } else {
3364                scheduleWriteSettingsLocked();
3365            }
3366        }
3367        return added;
3368    }
3369
3370    @Override
3371    public boolean addPermission(PermissionInfo info) {
3372        synchronized (mPackages) {
3373            return addPermissionLocked(info, false);
3374        }
3375    }
3376
3377    @Override
3378    public boolean addPermissionAsync(PermissionInfo info) {
3379        synchronized (mPackages) {
3380            return addPermissionLocked(info, true);
3381        }
3382    }
3383
3384    @Override
3385    public void removePermission(String name) {
3386        synchronized (mPackages) {
3387            checkPermissionTreeLP(name);
3388            BasePermission bp = mSettings.mPermissions.get(name);
3389            if (bp != null) {
3390                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3391                    throw new SecurityException(
3392                            "Not allowed to modify non-dynamic permission "
3393                            + name);
3394                }
3395                mSettings.mPermissions.remove(name);
3396                mSettings.writeLPr();
3397            }
3398        }
3399    }
3400
3401    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3402            BasePermission bp) {
3403        int index = pkg.requestedPermissions.indexOf(bp.name);
3404        if (index == -1) {
3405            throw new SecurityException("Package " + pkg.packageName
3406                    + " has not requested permission " + bp.name);
3407        }
3408        if (!bp.isRuntime()) {
3409            throw new SecurityException("Permission " + bp.name
3410                    + " is not a changeable permission type");
3411        }
3412    }
3413
3414    @Override
3415    public void grantRuntimePermission(String packageName, String name, final int userId) {
3416        if (!sUserManager.exists(userId)) {
3417            Log.e(TAG, "No such user:" + userId);
3418            return;
3419        }
3420
3421        mContext.enforceCallingOrSelfPermission(
3422                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3423                "grantRuntimePermission");
3424
3425        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3426                "grantRuntimePermission");
3427
3428        final int uid;
3429        final SettingBase sb;
3430
3431        synchronized (mPackages) {
3432            final PackageParser.Package pkg = mPackages.get(packageName);
3433            if (pkg == null) {
3434                throw new IllegalArgumentException("Unknown package: " + packageName);
3435            }
3436
3437            final BasePermission bp = mSettings.mPermissions.get(name);
3438            if (bp == null) {
3439                throw new IllegalArgumentException("Unknown permission: " + name);
3440            }
3441
3442            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3443
3444            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3445            sb = (SettingBase) pkg.mExtras;
3446            if (sb == null) {
3447                throw new IllegalArgumentException("Unknown package: " + packageName);
3448            }
3449
3450            final PermissionsState permissionsState = sb.getPermissionsState();
3451
3452            final int flags = permissionsState.getPermissionFlags(name, userId);
3453            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3454                throw new SecurityException("Cannot grant system fixed permission: "
3455                        + name + " for package: " + packageName);
3456            }
3457
3458            final int result = permissionsState.grantRuntimePermission(bp, userId);
3459            switch (result) {
3460                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3461                    return;
3462                }
3463
3464                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3465                    mHandler.post(new Runnable() {
3466                        @Override
3467                        public void run() {
3468                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3469                        }
3470                    });
3471                } break;
3472            }
3473
3474            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3475
3476            // Not critical if that is lost - app has to request again.
3477            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3478        }
3479
3480        // Only need to do this if user is initialized. Otherwise it's a new user
3481        // and there are no processes running as the user yet and there's no need
3482        // to make an expensive call to remount processes for the changed permissions.
3483        if (READ_EXTERNAL_STORAGE.equals(name)
3484                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3485            final long token = Binder.clearCallingIdentity();
3486            try {
3487                if (sUserManager.isInitialized(userId)) {
3488                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3489                            MountServiceInternal.class);
3490                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3491                }
3492            } finally {
3493                Binder.restoreCallingIdentity(token);
3494            }
3495        }
3496    }
3497
3498    @Override
3499    public void revokeRuntimePermission(String packageName, String name, int userId) {
3500        if (!sUserManager.exists(userId)) {
3501            Log.e(TAG, "No such user:" + userId);
3502            return;
3503        }
3504
3505        mContext.enforceCallingOrSelfPermission(
3506                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3507                "revokeRuntimePermission");
3508
3509        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3510                "revokeRuntimePermission");
3511
3512        final SettingBase sb;
3513
3514        synchronized (mPackages) {
3515            final PackageParser.Package pkg = mPackages.get(packageName);
3516            if (pkg == null) {
3517                throw new IllegalArgumentException("Unknown package: " + packageName);
3518            }
3519
3520            final BasePermission bp = mSettings.mPermissions.get(name);
3521            if (bp == null) {
3522                throw new IllegalArgumentException("Unknown permission: " + name);
3523            }
3524
3525            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3526
3527            sb = (SettingBase) pkg.mExtras;
3528            if (sb == null) {
3529                throw new IllegalArgumentException("Unknown package: " + packageName);
3530            }
3531
3532            final PermissionsState permissionsState = sb.getPermissionsState();
3533
3534            final int flags = permissionsState.getPermissionFlags(name, userId);
3535            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3536                throw new SecurityException("Cannot revoke system fixed permission: "
3537                        + name + " for package: " + packageName);
3538            }
3539
3540            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3541                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3542                return;
3543            }
3544
3545            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3546
3547            // Critical, after this call app should never have the permission.
3548            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3549        }
3550
3551        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3552    }
3553
3554    @Override
3555    public void resetRuntimePermissions() {
3556        mContext.enforceCallingOrSelfPermission(
3557                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3558                "revokeRuntimePermission");
3559
3560        int callingUid = Binder.getCallingUid();
3561        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3562            mContext.enforceCallingOrSelfPermission(
3563                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3564                    "resetRuntimePermissions");
3565        }
3566
3567        synchronized (mPackages) {
3568            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3569            for (int userId : UserManagerService.getInstance().getUserIds()) {
3570                final int packageCount = mPackages.size();
3571                for (int i = 0; i < packageCount; i++) {
3572                    PackageParser.Package pkg = mPackages.valueAt(i);
3573                    if (!(pkg.mExtras instanceof PackageSetting)) {
3574                        continue;
3575                    }
3576                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3577                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3578                }
3579            }
3580        }
3581    }
3582
3583    @Override
3584    public int getPermissionFlags(String name, String packageName, int userId) {
3585        if (!sUserManager.exists(userId)) {
3586            return 0;
3587        }
3588
3589        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3590
3591        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3592                "getPermissionFlags");
3593
3594        synchronized (mPackages) {
3595            final PackageParser.Package pkg = mPackages.get(packageName);
3596            if (pkg == null) {
3597                throw new IllegalArgumentException("Unknown package: " + packageName);
3598            }
3599
3600            final BasePermission bp = mSettings.mPermissions.get(name);
3601            if (bp == null) {
3602                throw new IllegalArgumentException("Unknown permission: " + name);
3603            }
3604
3605            SettingBase sb = (SettingBase) pkg.mExtras;
3606            if (sb == null) {
3607                throw new IllegalArgumentException("Unknown package: " + packageName);
3608            }
3609
3610            PermissionsState permissionsState = sb.getPermissionsState();
3611            return permissionsState.getPermissionFlags(name, userId);
3612        }
3613    }
3614
3615    @Override
3616    public void updatePermissionFlags(String name, String packageName, int flagMask,
3617            int flagValues, int userId) {
3618        if (!sUserManager.exists(userId)) {
3619            return;
3620        }
3621
3622        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3623
3624        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3625                "updatePermissionFlags");
3626
3627        // Only the system can change these flags and nothing else.
3628        if (getCallingUid() != Process.SYSTEM_UID) {
3629            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3630            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3631            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3632            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3633            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3634            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3635        }
3636
3637        synchronized (mPackages) {
3638            final PackageParser.Package pkg = mPackages.get(packageName);
3639            if (pkg == null) {
3640                throw new IllegalArgumentException("Unknown package: " + packageName);
3641            }
3642
3643            final BasePermission bp = mSettings.mPermissions.get(name);
3644            if (bp == null) {
3645                throw new IllegalArgumentException("Unknown permission: " + name);
3646            }
3647
3648            SettingBase sb = (SettingBase) pkg.mExtras;
3649            if (sb == null) {
3650                throw new IllegalArgumentException("Unknown package: " + packageName);
3651            }
3652
3653            PermissionsState permissionsState = sb.getPermissionsState();
3654
3655            // Only the package manager can change flags for system component permissions.
3656            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3657            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3658                return;
3659            }
3660
3661            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3662
3663            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3664                // Install and runtime permissions are stored in different places,
3665                // so figure out what permission changed and persist the change.
3666                if (permissionsState.getInstallPermissionState(name) != null) {
3667                    scheduleWriteSettingsLocked();
3668                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3669                        || hadState) {
3670                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3671                }
3672            }
3673        }
3674    }
3675
3676    /**
3677     * Update the permission flags for all packages and runtime permissions of a user in order
3678     * to allow device or profile owner to remove POLICY_FIXED.
3679     */
3680    @Override
3681    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3682        if (!sUserManager.exists(userId)) {
3683            return;
3684        }
3685
3686        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3687
3688        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3689                "updatePermissionFlagsForAllApps");
3690
3691        // Only the system can change system fixed flags.
3692        if (getCallingUid() != Process.SYSTEM_UID) {
3693            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3694            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3695        }
3696
3697        synchronized (mPackages) {
3698            boolean changed = false;
3699            final int packageCount = mPackages.size();
3700            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3701                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3702                SettingBase sb = (SettingBase) pkg.mExtras;
3703                if (sb == null) {
3704                    continue;
3705                }
3706                PermissionsState permissionsState = sb.getPermissionsState();
3707                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3708                        userId, flagMask, flagValues);
3709            }
3710            if (changed) {
3711                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3712            }
3713        }
3714    }
3715
3716    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3717        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3718                != PackageManager.PERMISSION_GRANTED
3719            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3720                != PackageManager.PERMISSION_GRANTED) {
3721            throw new SecurityException(message + " requires "
3722                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3723                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3724        }
3725    }
3726
3727    @Override
3728    public boolean shouldShowRequestPermissionRationale(String permissionName,
3729            String packageName, int userId) {
3730        if (UserHandle.getCallingUserId() != userId) {
3731            mContext.enforceCallingPermission(
3732                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3733                    "canShowRequestPermissionRationale for user " + userId);
3734        }
3735
3736        final int uid = getPackageUid(packageName, userId);
3737        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3738            return false;
3739        }
3740
3741        if (checkPermission(permissionName, packageName, userId)
3742                == PackageManager.PERMISSION_GRANTED) {
3743            return false;
3744        }
3745
3746        final int flags;
3747
3748        final long identity = Binder.clearCallingIdentity();
3749        try {
3750            flags = getPermissionFlags(permissionName,
3751                    packageName, userId);
3752        } finally {
3753            Binder.restoreCallingIdentity(identity);
3754        }
3755
3756        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3757                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3758                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3759
3760        if ((flags & fixedFlags) != 0) {
3761            return false;
3762        }
3763
3764        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3765    }
3766
3767    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3768        BasePermission bp = mSettings.mPermissions.get(permission);
3769        if (bp == null) {
3770            throw new SecurityException("Missing " + permission + " permission");
3771        }
3772
3773        SettingBase sb = (SettingBase) pkg.mExtras;
3774        PermissionsState permissionsState = sb.getPermissionsState();
3775
3776        if (permissionsState.grantInstallPermission(bp) !=
3777                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3778            scheduleWriteSettingsLocked();
3779        }
3780    }
3781
3782    @Override
3783    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3784        mContext.enforceCallingOrSelfPermission(
3785                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3786                "addOnPermissionsChangeListener");
3787
3788        synchronized (mPackages) {
3789            mOnPermissionChangeListeners.addListenerLocked(listener);
3790        }
3791    }
3792
3793    @Override
3794    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3795        synchronized (mPackages) {
3796            mOnPermissionChangeListeners.removeListenerLocked(listener);
3797        }
3798    }
3799
3800    @Override
3801    public boolean isProtectedBroadcast(String actionName) {
3802        synchronized (mPackages) {
3803            return mProtectedBroadcasts.contains(actionName);
3804        }
3805    }
3806
3807    @Override
3808    public int checkSignatures(String pkg1, String pkg2) {
3809        synchronized (mPackages) {
3810            final PackageParser.Package p1 = mPackages.get(pkg1);
3811            final PackageParser.Package p2 = mPackages.get(pkg2);
3812            if (p1 == null || p1.mExtras == null
3813                    || p2 == null || p2.mExtras == null) {
3814                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3815            }
3816            return compareSignatures(p1.mSignatures, p2.mSignatures);
3817        }
3818    }
3819
3820    @Override
3821    public int checkUidSignatures(int uid1, int uid2) {
3822        // Map to base uids.
3823        uid1 = UserHandle.getAppId(uid1);
3824        uid2 = UserHandle.getAppId(uid2);
3825        // reader
3826        synchronized (mPackages) {
3827            Signature[] s1;
3828            Signature[] s2;
3829            Object obj = mSettings.getUserIdLPr(uid1);
3830            if (obj != null) {
3831                if (obj instanceof SharedUserSetting) {
3832                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3833                } else if (obj instanceof PackageSetting) {
3834                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3835                } else {
3836                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3837                }
3838            } else {
3839                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3840            }
3841            obj = mSettings.getUserIdLPr(uid2);
3842            if (obj != null) {
3843                if (obj instanceof SharedUserSetting) {
3844                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3845                } else if (obj instanceof PackageSetting) {
3846                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3847                } else {
3848                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3849                }
3850            } else {
3851                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3852            }
3853            return compareSignatures(s1, s2);
3854        }
3855    }
3856
3857    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3858        final long identity = Binder.clearCallingIdentity();
3859        try {
3860            if (sb instanceof SharedUserSetting) {
3861                SharedUserSetting sus = (SharedUserSetting) sb;
3862                final int packageCount = sus.packages.size();
3863                for (int i = 0; i < packageCount; i++) {
3864                    PackageSetting susPs = sus.packages.valueAt(i);
3865                    if (userId == UserHandle.USER_ALL) {
3866                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3867                    } else {
3868                        final int uid = UserHandle.getUid(userId, susPs.appId);
3869                        killUid(uid, reason);
3870                    }
3871                }
3872            } else if (sb instanceof PackageSetting) {
3873                PackageSetting ps = (PackageSetting) sb;
3874                if (userId == UserHandle.USER_ALL) {
3875                    killApplication(ps.pkg.packageName, ps.appId, reason);
3876                } else {
3877                    final int uid = UserHandle.getUid(userId, ps.appId);
3878                    killUid(uid, reason);
3879                }
3880            }
3881        } finally {
3882            Binder.restoreCallingIdentity(identity);
3883        }
3884    }
3885
3886    private static void killUid(int uid, String reason) {
3887        IActivityManager am = ActivityManagerNative.getDefault();
3888        if (am != null) {
3889            try {
3890                am.killUid(uid, reason);
3891            } catch (RemoteException e) {
3892                /* ignore - same process */
3893            }
3894        }
3895    }
3896
3897    /**
3898     * Compares two sets of signatures. Returns:
3899     * <br />
3900     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3901     * <br />
3902     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3903     * <br />
3904     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3905     * <br />
3906     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3907     * <br />
3908     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3909     */
3910    static int compareSignatures(Signature[] s1, Signature[] s2) {
3911        if (s1 == null) {
3912            return s2 == null
3913                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3914                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3915        }
3916
3917        if (s2 == null) {
3918            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3919        }
3920
3921        if (s1.length != s2.length) {
3922            return PackageManager.SIGNATURE_NO_MATCH;
3923        }
3924
3925        // Since both signature sets are of size 1, we can compare without HashSets.
3926        if (s1.length == 1) {
3927            return s1[0].equals(s2[0]) ?
3928                    PackageManager.SIGNATURE_MATCH :
3929                    PackageManager.SIGNATURE_NO_MATCH;
3930        }
3931
3932        ArraySet<Signature> set1 = new ArraySet<Signature>();
3933        for (Signature sig : s1) {
3934            set1.add(sig);
3935        }
3936        ArraySet<Signature> set2 = new ArraySet<Signature>();
3937        for (Signature sig : s2) {
3938            set2.add(sig);
3939        }
3940        // Make sure s2 contains all signatures in s1.
3941        if (set1.equals(set2)) {
3942            return PackageManager.SIGNATURE_MATCH;
3943        }
3944        return PackageManager.SIGNATURE_NO_MATCH;
3945    }
3946
3947    /**
3948     * If the database version for this type of package (internal storage or
3949     * external storage) is less than the version where package signatures
3950     * were updated, return true.
3951     */
3952    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3953        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3954        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3955    }
3956
3957    /**
3958     * Used for backward compatibility to make sure any packages with
3959     * certificate chains get upgraded to the new style. {@code existingSigs}
3960     * will be in the old format (since they were stored on disk from before the
3961     * system upgrade) and {@code scannedSigs} will be in the newer format.
3962     */
3963    private int compareSignaturesCompat(PackageSignatures existingSigs,
3964            PackageParser.Package scannedPkg) {
3965        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3966            return PackageManager.SIGNATURE_NO_MATCH;
3967        }
3968
3969        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3970        for (Signature sig : existingSigs.mSignatures) {
3971            existingSet.add(sig);
3972        }
3973        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3974        for (Signature sig : scannedPkg.mSignatures) {
3975            try {
3976                Signature[] chainSignatures = sig.getChainSignatures();
3977                for (Signature chainSig : chainSignatures) {
3978                    scannedCompatSet.add(chainSig);
3979                }
3980            } catch (CertificateEncodingException e) {
3981                scannedCompatSet.add(sig);
3982            }
3983        }
3984        /*
3985         * Make sure the expanded scanned set contains all signatures in the
3986         * existing one.
3987         */
3988        if (scannedCompatSet.equals(existingSet)) {
3989            // Migrate the old signatures to the new scheme.
3990            existingSigs.assignSignatures(scannedPkg.mSignatures);
3991            // The new KeySets will be re-added later in the scanning process.
3992            synchronized (mPackages) {
3993                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3994            }
3995            return PackageManager.SIGNATURE_MATCH;
3996        }
3997        return PackageManager.SIGNATURE_NO_MATCH;
3998    }
3999
4000    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4001        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4002        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4003    }
4004
4005    private int compareSignaturesRecover(PackageSignatures existingSigs,
4006            PackageParser.Package scannedPkg) {
4007        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4008            return PackageManager.SIGNATURE_NO_MATCH;
4009        }
4010
4011        String msg = null;
4012        try {
4013            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4014                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4015                        + scannedPkg.packageName);
4016                return PackageManager.SIGNATURE_MATCH;
4017            }
4018        } catch (CertificateException e) {
4019            msg = e.getMessage();
4020        }
4021
4022        logCriticalInfo(Log.INFO,
4023                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4024        return PackageManager.SIGNATURE_NO_MATCH;
4025    }
4026
4027    @Override
4028    public String[] getPackagesForUid(int uid) {
4029        uid = UserHandle.getAppId(uid);
4030        // reader
4031        synchronized (mPackages) {
4032            Object obj = mSettings.getUserIdLPr(uid);
4033            if (obj instanceof SharedUserSetting) {
4034                final SharedUserSetting sus = (SharedUserSetting) obj;
4035                final int N = sus.packages.size();
4036                final String[] res = new String[N];
4037                final Iterator<PackageSetting> it = sus.packages.iterator();
4038                int i = 0;
4039                while (it.hasNext()) {
4040                    res[i++] = it.next().name;
4041                }
4042                return res;
4043            } else if (obj instanceof PackageSetting) {
4044                final PackageSetting ps = (PackageSetting) obj;
4045                return new String[] { ps.name };
4046            }
4047        }
4048        return null;
4049    }
4050
4051    @Override
4052    public String getNameForUid(int uid) {
4053        // reader
4054        synchronized (mPackages) {
4055            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4056            if (obj instanceof SharedUserSetting) {
4057                final SharedUserSetting sus = (SharedUserSetting) obj;
4058                return sus.name + ":" + sus.userId;
4059            } else if (obj instanceof PackageSetting) {
4060                final PackageSetting ps = (PackageSetting) obj;
4061                return ps.name;
4062            }
4063        }
4064        return null;
4065    }
4066
4067    @Override
4068    public int getUidForSharedUser(String sharedUserName) {
4069        if(sharedUserName == null) {
4070            return -1;
4071        }
4072        // reader
4073        synchronized (mPackages) {
4074            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4075            if (suid == null) {
4076                return -1;
4077            }
4078            return suid.userId;
4079        }
4080    }
4081
4082    @Override
4083    public int getFlagsForUid(int uid) {
4084        synchronized (mPackages) {
4085            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4086            if (obj instanceof SharedUserSetting) {
4087                final SharedUserSetting sus = (SharedUserSetting) obj;
4088                return sus.pkgFlags;
4089            } else if (obj instanceof PackageSetting) {
4090                final PackageSetting ps = (PackageSetting) obj;
4091                return ps.pkgFlags;
4092            }
4093        }
4094        return 0;
4095    }
4096
4097    @Override
4098    public int getPrivateFlagsForUid(int uid) {
4099        synchronized (mPackages) {
4100            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4101            if (obj instanceof SharedUserSetting) {
4102                final SharedUserSetting sus = (SharedUserSetting) obj;
4103                return sus.pkgPrivateFlags;
4104            } else if (obj instanceof PackageSetting) {
4105                final PackageSetting ps = (PackageSetting) obj;
4106                return ps.pkgPrivateFlags;
4107            }
4108        }
4109        return 0;
4110    }
4111
4112    @Override
4113    public boolean isUidPrivileged(int uid) {
4114        uid = UserHandle.getAppId(uid);
4115        // reader
4116        synchronized (mPackages) {
4117            Object obj = mSettings.getUserIdLPr(uid);
4118            if (obj instanceof SharedUserSetting) {
4119                final SharedUserSetting sus = (SharedUserSetting) obj;
4120                final Iterator<PackageSetting> it = sus.packages.iterator();
4121                while (it.hasNext()) {
4122                    if (it.next().isPrivileged()) {
4123                        return true;
4124                    }
4125                }
4126            } else if (obj instanceof PackageSetting) {
4127                final PackageSetting ps = (PackageSetting) obj;
4128                return ps.isPrivileged();
4129            }
4130        }
4131        return false;
4132    }
4133
4134    @Override
4135    public String[] getAppOpPermissionPackages(String permissionName) {
4136        synchronized (mPackages) {
4137            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4138            if (pkgs == null) {
4139                return null;
4140            }
4141            return pkgs.toArray(new String[pkgs.size()]);
4142        }
4143    }
4144
4145    @Override
4146    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4147            int flags, int userId) {
4148        if (!sUserManager.exists(userId)) return null;
4149        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4150        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4151        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4152    }
4153
4154    @Override
4155    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4156            IntentFilter filter, int match, ComponentName activity) {
4157        final int userId = UserHandle.getCallingUserId();
4158        if (DEBUG_PREFERRED) {
4159            Log.v(TAG, "setLastChosenActivity intent=" + intent
4160                + " resolvedType=" + resolvedType
4161                + " flags=" + flags
4162                + " filter=" + filter
4163                + " match=" + match
4164                + " activity=" + activity);
4165            filter.dump(new PrintStreamPrinter(System.out), "    ");
4166        }
4167        intent.setComponent(null);
4168        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4169        // Find any earlier preferred or last chosen entries and nuke them
4170        findPreferredActivity(intent, resolvedType,
4171                flags, query, 0, false, true, false, userId);
4172        // Add the new activity as the last chosen for this filter
4173        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4174                "Setting last chosen");
4175    }
4176
4177    @Override
4178    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4179        final int userId = UserHandle.getCallingUserId();
4180        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4181        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4182        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4183                false, false, false, userId);
4184    }
4185
4186    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4187            int flags, List<ResolveInfo> query, int userId) {
4188        if (query != null) {
4189            final int N = query.size();
4190            if (N == 1) {
4191                return query.get(0);
4192            } else if (N > 1) {
4193                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4194                // If there is more than one activity with the same priority,
4195                // then let the user decide between them.
4196                ResolveInfo r0 = query.get(0);
4197                ResolveInfo r1 = query.get(1);
4198                if (DEBUG_INTENT_MATCHING || debug) {
4199                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4200                            + r1.activityInfo.name + "=" + r1.priority);
4201                }
4202                // If the first activity has a higher priority, or a different
4203                // default, then it is always desireable to pick it.
4204                if (r0.priority != r1.priority
4205                        || r0.preferredOrder != r1.preferredOrder
4206                        || r0.isDefault != r1.isDefault) {
4207                    return query.get(0);
4208                }
4209                // If we have saved a preference for a preferred activity for
4210                // this Intent, use that.
4211                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4212                        flags, query, r0.priority, true, false, debug, userId);
4213                if (ri != null) {
4214                    return ri;
4215                }
4216                if (userId != 0) {
4217                    ri = new ResolveInfo(mResolveInfo);
4218                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4219                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4220                            ri.activityInfo.applicationInfo);
4221                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4222                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4223                    return ri;
4224                }
4225                return mResolveInfo;
4226            }
4227        }
4228        return null;
4229    }
4230
4231    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4232            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4233        final int N = query.size();
4234        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4235                .get(userId);
4236        // Get the list of persistent preferred activities that handle the intent
4237        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4238        List<PersistentPreferredActivity> pprefs = ppir != null
4239                ? ppir.queryIntent(intent, resolvedType,
4240                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4241                : null;
4242        if (pprefs != null && pprefs.size() > 0) {
4243            final int M = pprefs.size();
4244            for (int i=0; i<M; i++) {
4245                final PersistentPreferredActivity ppa = pprefs.get(i);
4246                if (DEBUG_PREFERRED || debug) {
4247                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4248                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4249                            + "\n  component=" + ppa.mComponent);
4250                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4251                }
4252                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4253                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4254                if (DEBUG_PREFERRED || debug) {
4255                    Slog.v(TAG, "Found persistent preferred activity:");
4256                    if (ai != null) {
4257                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4258                    } else {
4259                        Slog.v(TAG, "  null");
4260                    }
4261                }
4262                if (ai == null) {
4263                    // This previously registered persistent preferred activity
4264                    // component is no longer known. Ignore it and do NOT remove it.
4265                    continue;
4266                }
4267                for (int j=0; j<N; j++) {
4268                    final ResolveInfo ri = query.get(j);
4269                    if (!ri.activityInfo.applicationInfo.packageName
4270                            .equals(ai.applicationInfo.packageName)) {
4271                        continue;
4272                    }
4273                    if (!ri.activityInfo.name.equals(ai.name)) {
4274                        continue;
4275                    }
4276                    //  Found a persistent preference that can handle the intent.
4277                    if (DEBUG_PREFERRED || debug) {
4278                        Slog.v(TAG, "Returning persistent preferred activity: " +
4279                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4280                    }
4281                    return ri;
4282                }
4283            }
4284        }
4285        return null;
4286    }
4287
4288    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4289            List<ResolveInfo> query, int priority, boolean always,
4290            boolean removeMatches, boolean debug, int userId) {
4291        if (!sUserManager.exists(userId)) return null;
4292        // writer
4293        synchronized (mPackages) {
4294            if (intent.getSelector() != null) {
4295                intent = intent.getSelector();
4296            }
4297            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4298
4299            // Try to find a matching persistent preferred activity.
4300            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4301                    debug, userId);
4302
4303            // If a persistent preferred activity matched, use it.
4304            if (pri != null) {
4305                return pri;
4306            }
4307
4308            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4309            // Get the list of preferred activities that handle the intent
4310            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4311            List<PreferredActivity> prefs = pir != null
4312                    ? pir.queryIntent(intent, resolvedType,
4313                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4314                    : null;
4315            if (prefs != null && prefs.size() > 0) {
4316                boolean changed = false;
4317                try {
4318                    // First figure out how good the original match set is.
4319                    // We will only allow preferred activities that came
4320                    // from the same match quality.
4321                    int match = 0;
4322
4323                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4324
4325                    final int N = query.size();
4326                    for (int j=0; j<N; j++) {
4327                        final ResolveInfo ri = query.get(j);
4328                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4329                                + ": 0x" + Integer.toHexString(match));
4330                        if (ri.match > match) {
4331                            match = ri.match;
4332                        }
4333                    }
4334
4335                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4336                            + Integer.toHexString(match));
4337
4338                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4339                    final int M = prefs.size();
4340                    for (int i=0; i<M; i++) {
4341                        final PreferredActivity pa = prefs.get(i);
4342                        if (DEBUG_PREFERRED || debug) {
4343                            Slog.v(TAG, "Checking PreferredActivity ds="
4344                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4345                                    + "\n  component=" + pa.mPref.mComponent);
4346                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4347                        }
4348                        if (pa.mPref.mMatch != match) {
4349                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4350                                    + Integer.toHexString(pa.mPref.mMatch));
4351                            continue;
4352                        }
4353                        // If it's not an "always" type preferred activity and that's what we're
4354                        // looking for, skip it.
4355                        if (always && !pa.mPref.mAlways) {
4356                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4357                            continue;
4358                        }
4359                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4360                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4361                        if (DEBUG_PREFERRED || debug) {
4362                            Slog.v(TAG, "Found preferred activity:");
4363                            if (ai != null) {
4364                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4365                            } else {
4366                                Slog.v(TAG, "  null");
4367                            }
4368                        }
4369                        if (ai == null) {
4370                            // This previously registered preferred activity
4371                            // component is no longer known.  Most likely an update
4372                            // to the app was installed and in the new version this
4373                            // component no longer exists.  Clean it up by removing
4374                            // it from the preferred activities list, and skip it.
4375                            Slog.w(TAG, "Removing dangling preferred activity: "
4376                                    + pa.mPref.mComponent);
4377                            pir.removeFilter(pa);
4378                            changed = true;
4379                            continue;
4380                        }
4381                        for (int j=0; j<N; j++) {
4382                            final ResolveInfo ri = query.get(j);
4383                            if (!ri.activityInfo.applicationInfo.packageName
4384                                    .equals(ai.applicationInfo.packageName)) {
4385                                continue;
4386                            }
4387                            if (!ri.activityInfo.name.equals(ai.name)) {
4388                                continue;
4389                            }
4390
4391                            if (removeMatches) {
4392                                pir.removeFilter(pa);
4393                                changed = true;
4394                                if (DEBUG_PREFERRED) {
4395                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4396                                }
4397                                break;
4398                            }
4399
4400                            // Okay we found a previously set preferred or last chosen app.
4401                            // If the result set is different from when this
4402                            // was created, we need to clear it and re-ask the
4403                            // user their preference, if we're looking for an "always" type entry.
4404                            if (always && !pa.mPref.sameSet(query)) {
4405                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4406                                        + intent + " type " + resolvedType);
4407                                if (DEBUG_PREFERRED) {
4408                                    Slog.v(TAG, "Removing preferred activity since set changed "
4409                                            + pa.mPref.mComponent);
4410                                }
4411                                pir.removeFilter(pa);
4412                                // Re-add the filter as a "last chosen" entry (!always)
4413                                PreferredActivity lastChosen = new PreferredActivity(
4414                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4415                                pir.addFilter(lastChosen);
4416                                changed = true;
4417                                return null;
4418                            }
4419
4420                            // Yay! Either the set matched or we're looking for the last chosen
4421                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4422                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4423                            return ri;
4424                        }
4425                    }
4426                } finally {
4427                    if (changed) {
4428                        if (DEBUG_PREFERRED) {
4429                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4430                        }
4431                        scheduleWritePackageRestrictionsLocked(userId);
4432                    }
4433                }
4434            }
4435        }
4436        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4437        return null;
4438    }
4439
4440    /*
4441     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4442     */
4443    @Override
4444    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4445            int targetUserId) {
4446        mContext.enforceCallingOrSelfPermission(
4447                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4448        List<CrossProfileIntentFilter> matches =
4449                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4450        if (matches != null) {
4451            int size = matches.size();
4452            for (int i = 0; i < size; i++) {
4453                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4454            }
4455        }
4456        if (hasWebURI(intent)) {
4457            // cross-profile app linking works only towards the parent.
4458            final UserInfo parent = getProfileParent(sourceUserId);
4459            synchronized(mPackages) {
4460                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4461                        intent, resolvedType, 0, sourceUserId, parent.id);
4462                return xpDomainInfo != null;
4463            }
4464        }
4465        return false;
4466    }
4467
4468    private UserInfo getProfileParent(int userId) {
4469        final long identity = Binder.clearCallingIdentity();
4470        try {
4471            return sUserManager.getProfileParent(userId);
4472        } finally {
4473            Binder.restoreCallingIdentity(identity);
4474        }
4475    }
4476
4477    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4478            String resolvedType, int userId) {
4479        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4480        if (resolver != null) {
4481            return resolver.queryIntent(intent, resolvedType, false, userId);
4482        }
4483        return null;
4484    }
4485
4486    @Override
4487    public List<ResolveInfo> queryIntentActivities(Intent intent,
4488            String resolvedType, int flags, int userId) {
4489        if (!sUserManager.exists(userId)) return Collections.emptyList();
4490        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4491        ComponentName comp = intent.getComponent();
4492        if (comp == null) {
4493            if (intent.getSelector() != null) {
4494                intent = intent.getSelector();
4495                comp = intent.getComponent();
4496            }
4497        }
4498
4499        if (comp != null) {
4500            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4501            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4502            if (ai != null) {
4503                final ResolveInfo ri = new ResolveInfo();
4504                ri.activityInfo = ai;
4505                list.add(ri);
4506            }
4507            return list;
4508        }
4509
4510        // reader
4511        synchronized (mPackages) {
4512            final String pkgName = intent.getPackage();
4513            if (pkgName == null) {
4514                List<CrossProfileIntentFilter> matchingFilters =
4515                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4516                // Check for results that need to skip the current profile.
4517                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4518                        resolvedType, flags, userId);
4519                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4520                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4521                    result.add(xpResolveInfo);
4522                    return filterIfNotPrimaryUser(result, userId);
4523                }
4524
4525                // Check for results in the current profile.
4526                List<ResolveInfo> result = mActivities.queryIntent(
4527                        intent, resolvedType, flags, userId);
4528
4529                // Check for cross profile results.
4530                xpResolveInfo = queryCrossProfileIntents(
4531                        matchingFilters, intent, resolvedType, flags, userId);
4532                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4533                    result.add(xpResolveInfo);
4534                    Collections.sort(result, mResolvePrioritySorter);
4535                }
4536                result = filterIfNotPrimaryUser(result, userId);
4537                if (hasWebURI(intent)) {
4538                    CrossProfileDomainInfo xpDomainInfo = null;
4539                    final UserInfo parent = getProfileParent(userId);
4540                    if (parent != null) {
4541                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4542                                flags, userId, parent.id);
4543                    }
4544                    if (xpDomainInfo != null) {
4545                        if (xpResolveInfo != null) {
4546                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4547                            // in the result.
4548                            result.remove(xpResolveInfo);
4549                        }
4550                        if (result.size() == 0) {
4551                            result.add(xpDomainInfo.resolveInfo);
4552                            return result;
4553                        }
4554                    } else if (result.size() <= 1) {
4555                        return result;
4556                    }
4557                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4558                            xpDomainInfo, userId);
4559                    Collections.sort(result, mResolvePrioritySorter);
4560                }
4561                return result;
4562            }
4563            final PackageParser.Package pkg = mPackages.get(pkgName);
4564            if (pkg != null) {
4565                return filterIfNotPrimaryUser(
4566                        mActivities.queryIntentForPackage(
4567                                intent, resolvedType, flags, pkg.activities, userId),
4568                        userId);
4569            }
4570            return new ArrayList<ResolveInfo>();
4571        }
4572    }
4573
4574    private static class CrossProfileDomainInfo {
4575        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4576        ResolveInfo resolveInfo;
4577        /* Best domain verification status of the activities found in the other profile */
4578        int bestDomainVerificationStatus;
4579    }
4580
4581    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4582            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4583        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4584                sourceUserId)) {
4585            return null;
4586        }
4587        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4588                resolvedType, flags, parentUserId);
4589
4590        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4591            return null;
4592        }
4593        CrossProfileDomainInfo result = null;
4594        int size = resultTargetUser.size();
4595        for (int i = 0; i < size; i++) {
4596            ResolveInfo riTargetUser = resultTargetUser.get(i);
4597            // Intent filter verification is only for filters that specify a host. So don't return
4598            // those that handle all web uris.
4599            if (riTargetUser.handleAllWebDataURI) {
4600                continue;
4601            }
4602            String packageName = riTargetUser.activityInfo.packageName;
4603            PackageSetting ps = mSettings.mPackages.get(packageName);
4604            if (ps == null) {
4605                continue;
4606            }
4607            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4608            int status = (int)(verificationState >> 32);
4609            if (result == null) {
4610                result = new CrossProfileDomainInfo();
4611                result.resolveInfo =
4612                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4613                result.bestDomainVerificationStatus = status;
4614            } else {
4615                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4616                        result.bestDomainVerificationStatus);
4617            }
4618        }
4619        // Don't consider matches with status NEVER across profiles.
4620        if (result != null && result.bestDomainVerificationStatus
4621                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4622            return null;
4623        }
4624        return result;
4625    }
4626
4627    /**
4628     * Verification statuses are ordered from the worse to the best, except for
4629     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4630     */
4631    private int bestDomainVerificationStatus(int status1, int status2) {
4632        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4633            return status2;
4634        }
4635        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4636            return status1;
4637        }
4638        return (int) MathUtils.max(status1, status2);
4639    }
4640
4641    private boolean isUserEnabled(int userId) {
4642        long callingId = Binder.clearCallingIdentity();
4643        try {
4644            UserInfo userInfo = sUserManager.getUserInfo(userId);
4645            return userInfo != null && userInfo.isEnabled();
4646        } finally {
4647            Binder.restoreCallingIdentity(callingId);
4648        }
4649    }
4650
4651    /**
4652     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4653     *
4654     * @return filtered list
4655     */
4656    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4657        if (userId == UserHandle.USER_OWNER) {
4658            return resolveInfos;
4659        }
4660        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4661            ResolveInfo info = resolveInfos.get(i);
4662            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4663                resolveInfos.remove(i);
4664            }
4665        }
4666        return resolveInfos;
4667    }
4668
4669    private static boolean hasWebURI(Intent intent) {
4670        if (intent.getData() == null) {
4671            return false;
4672        }
4673        final String scheme = intent.getScheme();
4674        if (TextUtils.isEmpty(scheme)) {
4675            return false;
4676        }
4677        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4678    }
4679
4680    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4681            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4682            int userId) {
4683        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4684
4685        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4686            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4687                    candidates.size());
4688        }
4689
4690        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4691        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4692        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4693        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4694        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4695
4696        synchronized (mPackages) {
4697            final int count = candidates.size();
4698            // First, try to use linked apps. Partition the candidates into four lists:
4699            // one for the final results, one for the "do not use ever", one for "undefined status"
4700            // and finally one for "browser app type".
4701            for (int n=0; n<count; n++) {
4702                ResolveInfo info = candidates.get(n);
4703                String packageName = info.activityInfo.packageName;
4704                PackageSetting ps = mSettings.mPackages.get(packageName);
4705                if (ps != null) {
4706                    // Add to the special match all list (Browser use case)
4707                    if (info.handleAllWebDataURI) {
4708                        matchAllList.add(info);
4709                        continue;
4710                    }
4711                    // Try to get the status from User settings first
4712                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4713                    int status = (int)(packedStatus >> 32);
4714                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4715                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4716                        if (DEBUG_DOMAIN_VERIFICATION) {
4717                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4718                                    + " : linkgen=" + linkGeneration);
4719                        }
4720                        // Use link-enabled generation as preferredOrder, i.e.
4721                        // prefer newly-enabled over earlier-enabled.
4722                        info.preferredOrder = linkGeneration;
4723                        alwaysList.add(info);
4724                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4725                        if (DEBUG_DOMAIN_VERIFICATION) {
4726                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4727                        }
4728                        neverList.add(info);
4729                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4730                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4731                        if (DEBUG_DOMAIN_VERIFICATION) {
4732                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4733                        }
4734                        undefinedList.add(info);
4735                    }
4736                }
4737            }
4738            // First try to add the "always" resolution(s) for the current user, if any
4739            if (alwaysList.size() > 0) {
4740                result.addAll(alwaysList);
4741            // if there is an "always" for the parent user, add it.
4742            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4743                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4744                result.add(xpDomainInfo.resolveInfo);
4745            } else {
4746                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4747                result.addAll(undefinedList);
4748                if (xpDomainInfo != null && (
4749                        xpDomainInfo.bestDomainVerificationStatus
4750                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4751                        || xpDomainInfo.bestDomainVerificationStatus
4752                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4753                    result.add(xpDomainInfo.resolveInfo);
4754                }
4755                // Also add Browsers (all of them or only the default one)
4756                if ((matchFlags & MATCH_ALL) != 0) {
4757                    result.addAll(matchAllList);
4758                } else {
4759                    // Browser/generic handling case.  If there's a default browser, go straight
4760                    // to that (but only if there is no other higher-priority match).
4761                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4762                    int maxMatchPrio = 0;
4763                    ResolveInfo defaultBrowserMatch = null;
4764                    final int numCandidates = matchAllList.size();
4765                    for (int n = 0; n < numCandidates; n++) {
4766                        ResolveInfo info = matchAllList.get(n);
4767                        // track the highest overall match priority...
4768                        if (info.priority > maxMatchPrio) {
4769                            maxMatchPrio = info.priority;
4770                        }
4771                        // ...and the highest-priority default browser match
4772                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4773                            if (defaultBrowserMatch == null
4774                                    || (defaultBrowserMatch.priority < info.priority)) {
4775                                if (debug) {
4776                                    Slog.v(TAG, "Considering default browser match " + info);
4777                                }
4778                                defaultBrowserMatch = info;
4779                            }
4780                        }
4781                    }
4782                    if (defaultBrowserMatch != null
4783                            && defaultBrowserMatch.priority >= maxMatchPrio
4784                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4785                    {
4786                        if (debug) {
4787                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4788                        }
4789                        result.add(defaultBrowserMatch);
4790                    } else {
4791                        result.addAll(matchAllList);
4792                    }
4793                }
4794
4795                // If there is nothing selected, add all candidates and remove the ones that the user
4796                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4797                if (result.size() == 0) {
4798                    result.addAll(candidates);
4799                    result.removeAll(neverList);
4800                }
4801            }
4802        }
4803        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4804            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4805                    result.size());
4806            for (ResolveInfo info : result) {
4807                Slog.v(TAG, "  + " + info.activityInfo);
4808            }
4809        }
4810        return result;
4811    }
4812
4813    // Returns a packed value as a long:
4814    //
4815    // high 'int'-sized word: link status: undefined/ask/never/always.
4816    // low 'int'-sized word: relative priority among 'always' results.
4817    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4818        long result = ps.getDomainVerificationStatusForUser(userId);
4819        // if none available, get the master status
4820        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4821            if (ps.getIntentFilterVerificationInfo() != null) {
4822                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4823            }
4824        }
4825        return result;
4826    }
4827
4828    private ResolveInfo querySkipCurrentProfileIntents(
4829            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4830            int flags, int sourceUserId) {
4831        if (matchingFilters != null) {
4832            int size = matchingFilters.size();
4833            for (int i = 0; i < size; i ++) {
4834                CrossProfileIntentFilter filter = matchingFilters.get(i);
4835                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4836                    // Checking if there are activities in the target user that can handle the
4837                    // intent.
4838                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4839                            flags, sourceUserId);
4840                    if (resolveInfo != null) {
4841                        return resolveInfo;
4842                    }
4843                }
4844            }
4845        }
4846        return null;
4847    }
4848
4849    // Return matching ResolveInfo if any for skip current profile intent filters.
4850    private ResolveInfo queryCrossProfileIntents(
4851            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4852            int flags, int sourceUserId) {
4853        if (matchingFilters != null) {
4854            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4855            // match the same intent. For performance reasons, it is better not to
4856            // run queryIntent twice for the same userId
4857            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4858            int size = matchingFilters.size();
4859            for (int i = 0; i < size; i++) {
4860                CrossProfileIntentFilter filter = matchingFilters.get(i);
4861                int targetUserId = filter.getTargetUserId();
4862                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4863                        && !alreadyTriedUserIds.get(targetUserId)) {
4864                    // Checking if there are activities in the target user that can handle the
4865                    // intent.
4866                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4867                            flags, sourceUserId);
4868                    if (resolveInfo != null) return resolveInfo;
4869                    alreadyTriedUserIds.put(targetUserId, true);
4870                }
4871            }
4872        }
4873        return null;
4874    }
4875
4876    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4877            String resolvedType, int flags, int sourceUserId) {
4878        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4879                resolvedType, flags, filter.getTargetUserId());
4880        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4881            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4882        }
4883        return null;
4884    }
4885
4886    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4887            int sourceUserId, int targetUserId) {
4888        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4889        String className;
4890        if (targetUserId == UserHandle.USER_OWNER) {
4891            className = FORWARD_INTENT_TO_USER_OWNER;
4892        } else {
4893            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4894        }
4895        ComponentName forwardingActivityComponentName = new ComponentName(
4896                mAndroidApplication.packageName, className);
4897        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4898                sourceUserId);
4899        if (targetUserId == UserHandle.USER_OWNER) {
4900            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4901            forwardingResolveInfo.noResourceId = true;
4902        }
4903        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4904        forwardingResolveInfo.priority = 0;
4905        forwardingResolveInfo.preferredOrder = 0;
4906        forwardingResolveInfo.match = 0;
4907        forwardingResolveInfo.isDefault = true;
4908        forwardingResolveInfo.filter = filter;
4909        forwardingResolveInfo.targetUserId = targetUserId;
4910        return forwardingResolveInfo;
4911    }
4912
4913    @Override
4914    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4915            Intent[] specifics, String[] specificTypes, Intent intent,
4916            String resolvedType, int flags, int userId) {
4917        if (!sUserManager.exists(userId)) return Collections.emptyList();
4918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4919                false, "query intent activity options");
4920        final String resultsAction = intent.getAction();
4921
4922        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4923                | PackageManager.GET_RESOLVED_FILTER, userId);
4924
4925        if (DEBUG_INTENT_MATCHING) {
4926            Log.v(TAG, "Query " + intent + ": " + results);
4927        }
4928
4929        int specificsPos = 0;
4930        int N;
4931
4932        // todo: note that the algorithm used here is O(N^2).  This
4933        // isn't a problem in our current environment, but if we start running
4934        // into situations where we have more than 5 or 10 matches then this
4935        // should probably be changed to something smarter...
4936
4937        // First we go through and resolve each of the specific items
4938        // that were supplied, taking care of removing any corresponding
4939        // duplicate items in the generic resolve list.
4940        if (specifics != null) {
4941            for (int i=0; i<specifics.length; i++) {
4942                final Intent sintent = specifics[i];
4943                if (sintent == null) {
4944                    continue;
4945                }
4946
4947                if (DEBUG_INTENT_MATCHING) {
4948                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4949                }
4950
4951                String action = sintent.getAction();
4952                if (resultsAction != null && resultsAction.equals(action)) {
4953                    // If this action was explicitly requested, then don't
4954                    // remove things that have it.
4955                    action = null;
4956                }
4957
4958                ResolveInfo ri = null;
4959                ActivityInfo ai = null;
4960
4961                ComponentName comp = sintent.getComponent();
4962                if (comp == null) {
4963                    ri = resolveIntent(
4964                        sintent,
4965                        specificTypes != null ? specificTypes[i] : null,
4966                            flags, userId);
4967                    if (ri == null) {
4968                        continue;
4969                    }
4970                    if (ri == mResolveInfo) {
4971                        // ACK!  Must do something better with this.
4972                    }
4973                    ai = ri.activityInfo;
4974                    comp = new ComponentName(ai.applicationInfo.packageName,
4975                            ai.name);
4976                } else {
4977                    ai = getActivityInfo(comp, flags, userId);
4978                    if (ai == null) {
4979                        continue;
4980                    }
4981                }
4982
4983                // Look for any generic query activities that are duplicates
4984                // of this specific one, and remove them from the results.
4985                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4986                N = results.size();
4987                int j;
4988                for (j=specificsPos; j<N; j++) {
4989                    ResolveInfo sri = results.get(j);
4990                    if ((sri.activityInfo.name.equals(comp.getClassName())
4991                            && sri.activityInfo.applicationInfo.packageName.equals(
4992                                    comp.getPackageName()))
4993                        || (action != null && sri.filter.matchAction(action))) {
4994                        results.remove(j);
4995                        if (DEBUG_INTENT_MATCHING) Log.v(
4996                            TAG, "Removing duplicate item from " + j
4997                            + " due to specific " + specificsPos);
4998                        if (ri == null) {
4999                            ri = sri;
5000                        }
5001                        j--;
5002                        N--;
5003                    }
5004                }
5005
5006                // Add this specific item to its proper place.
5007                if (ri == null) {
5008                    ri = new ResolveInfo();
5009                    ri.activityInfo = ai;
5010                }
5011                results.add(specificsPos, ri);
5012                ri.specificIndex = i;
5013                specificsPos++;
5014            }
5015        }
5016
5017        // Now we go through the remaining generic results and remove any
5018        // duplicate actions that are found here.
5019        N = results.size();
5020        for (int i=specificsPos; i<N-1; i++) {
5021            final ResolveInfo rii = results.get(i);
5022            if (rii.filter == null) {
5023                continue;
5024            }
5025
5026            // Iterate over all of the actions of this result's intent
5027            // filter...  typically this should be just one.
5028            final Iterator<String> it = rii.filter.actionsIterator();
5029            if (it == null) {
5030                continue;
5031            }
5032            while (it.hasNext()) {
5033                final String action = it.next();
5034                if (resultsAction != null && resultsAction.equals(action)) {
5035                    // If this action was explicitly requested, then don't
5036                    // remove things that have it.
5037                    continue;
5038                }
5039                for (int j=i+1; j<N; j++) {
5040                    final ResolveInfo rij = results.get(j);
5041                    if (rij.filter != null && rij.filter.hasAction(action)) {
5042                        results.remove(j);
5043                        if (DEBUG_INTENT_MATCHING) Log.v(
5044                            TAG, "Removing duplicate item from " + j
5045                            + " due to action " + action + " at " + i);
5046                        j--;
5047                        N--;
5048                    }
5049                }
5050            }
5051
5052            // If the caller didn't request filter information, drop it now
5053            // so we don't have to marshall/unmarshall it.
5054            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5055                rii.filter = null;
5056            }
5057        }
5058
5059        // Filter out the caller activity if so requested.
5060        if (caller != null) {
5061            N = results.size();
5062            for (int i=0; i<N; i++) {
5063                ActivityInfo ainfo = results.get(i).activityInfo;
5064                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5065                        && caller.getClassName().equals(ainfo.name)) {
5066                    results.remove(i);
5067                    break;
5068                }
5069            }
5070        }
5071
5072        // If the caller didn't request filter information,
5073        // drop them now so we don't have to
5074        // marshall/unmarshall it.
5075        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5076            N = results.size();
5077            for (int i=0; i<N; i++) {
5078                results.get(i).filter = null;
5079            }
5080        }
5081
5082        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5083        return results;
5084    }
5085
5086    @Override
5087    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5088            int userId) {
5089        if (!sUserManager.exists(userId)) return Collections.emptyList();
5090        ComponentName comp = intent.getComponent();
5091        if (comp == null) {
5092            if (intent.getSelector() != null) {
5093                intent = intent.getSelector();
5094                comp = intent.getComponent();
5095            }
5096        }
5097        if (comp != null) {
5098            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5099            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5100            if (ai != null) {
5101                ResolveInfo ri = new ResolveInfo();
5102                ri.activityInfo = ai;
5103                list.add(ri);
5104            }
5105            return list;
5106        }
5107
5108        // reader
5109        synchronized (mPackages) {
5110            String pkgName = intent.getPackage();
5111            if (pkgName == null) {
5112                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5113            }
5114            final PackageParser.Package pkg = mPackages.get(pkgName);
5115            if (pkg != null) {
5116                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5117                        userId);
5118            }
5119            return null;
5120        }
5121    }
5122
5123    @Override
5124    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5125        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5126        if (!sUserManager.exists(userId)) return null;
5127        if (query != null) {
5128            if (query.size() >= 1) {
5129                // If there is more than one service with the same priority,
5130                // just arbitrarily pick the first one.
5131                return query.get(0);
5132            }
5133        }
5134        return null;
5135    }
5136
5137    @Override
5138    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5139            int userId) {
5140        if (!sUserManager.exists(userId)) return Collections.emptyList();
5141        ComponentName comp = intent.getComponent();
5142        if (comp == null) {
5143            if (intent.getSelector() != null) {
5144                intent = intent.getSelector();
5145                comp = intent.getComponent();
5146            }
5147        }
5148        if (comp != null) {
5149            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5150            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5151            if (si != null) {
5152                final ResolveInfo ri = new ResolveInfo();
5153                ri.serviceInfo = si;
5154                list.add(ri);
5155            }
5156            return list;
5157        }
5158
5159        // reader
5160        synchronized (mPackages) {
5161            String pkgName = intent.getPackage();
5162            if (pkgName == null) {
5163                return mServices.queryIntent(intent, resolvedType, flags, userId);
5164            }
5165            final PackageParser.Package pkg = mPackages.get(pkgName);
5166            if (pkg != null) {
5167                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5168                        userId);
5169            }
5170            return null;
5171        }
5172    }
5173
5174    @Override
5175    public List<ResolveInfo> queryIntentContentProviders(
5176            Intent intent, String resolvedType, int flags, int userId) {
5177        if (!sUserManager.exists(userId)) return Collections.emptyList();
5178        ComponentName comp = intent.getComponent();
5179        if (comp == null) {
5180            if (intent.getSelector() != null) {
5181                intent = intent.getSelector();
5182                comp = intent.getComponent();
5183            }
5184        }
5185        if (comp != null) {
5186            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5187            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5188            if (pi != null) {
5189                final ResolveInfo ri = new ResolveInfo();
5190                ri.providerInfo = pi;
5191                list.add(ri);
5192            }
5193            return list;
5194        }
5195
5196        // reader
5197        synchronized (mPackages) {
5198            String pkgName = intent.getPackage();
5199            if (pkgName == null) {
5200                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5201            }
5202            final PackageParser.Package pkg = mPackages.get(pkgName);
5203            if (pkg != null) {
5204                return mProviders.queryIntentForPackage(
5205                        intent, resolvedType, flags, pkg.providers, userId);
5206            }
5207            return null;
5208        }
5209    }
5210
5211    @Override
5212    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5213        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5214
5215        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5216
5217        // writer
5218        synchronized (mPackages) {
5219            ArrayList<PackageInfo> list;
5220            if (listUninstalled) {
5221                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5222                for (PackageSetting ps : mSettings.mPackages.values()) {
5223                    PackageInfo pi;
5224                    if (ps.pkg != null) {
5225                        pi = generatePackageInfo(ps.pkg, flags, userId);
5226                    } else {
5227                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5228                    }
5229                    if (pi != null) {
5230                        list.add(pi);
5231                    }
5232                }
5233            } else {
5234                list = new ArrayList<PackageInfo>(mPackages.size());
5235                for (PackageParser.Package p : mPackages.values()) {
5236                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5237                    if (pi != null) {
5238                        list.add(pi);
5239                    }
5240                }
5241            }
5242
5243            return new ParceledListSlice<PackageInfo>(list);
5244        }
5245    }
5246
5247    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5248            String[] permissions, boolean[] tmp, int flags, int userId) {
5249        int numMatch = 0;
5250        final PermissionsState permissionsState = ps.getPermissionsState();
5251        for (int i=0; i<permissions.length; i++) {
5252            final String permission = permissions[i];
5253            if (permissionsState.hasPermission(permission, userId)) {
5254                tmp[i] = true;
5255                numMatch++;
5256            } else {
5257                tmp[i] = false;
5258            }
5259        }
5260        if (numMatch == 0) {
5261            return;
5262        }
5263        PackageInfo pi;
5264        if (ps.pkg != null) {
5265            pi = generatePackageInfo(ps.pkg, flags, userId);
5266        } else {
5267            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5268        }
5269        // The above might return null in cases of uninstalled apps or install-state
5270        // skew across users/profiles.
5271        if (pi != null) {
5272            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5273                if (numMatch == permissions.length) {
5274                    pi.requestedPermissions = permissions;
5275                } else {
5276                    pi.requestedPermissions = new String[numMatch];
5277                    numMatch = 0;
5278                    for (int i=0; i<permissions.length; i++) {
5279                        if (tmp[i]) {
5280                            pi.requestedPermissions[numMatch] = permissions[i];
5281                            numMatch++;
5282                        }
5283                    }
5284                }
5285            }
5286            list.add(pi);
5287        }
5288    }
5289
5290    @Override
5291    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5292            String[] permissions, int flags, int userId) {
5293        if (!sUserManager.exists(userId)) return null;
5294        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5295
5296        // writer
5297        synchronized (mPackages) {
5298            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5299            boolean[] tmpBools = new boolean[permissions.length];
5300            if (listUninstalled) {
5301                for (PackageSetting ps : mSettings.mPackages.values()) {
5302                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5303                }
5304            } else {
5305                for (PackageParser.Package pkg : mPackages.values()) {
5306                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5307                    if (ps != null) {
5308                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5309                                userId);
5310                    }
5311                }
5312            }
5313
5314            return new ParceledListSlice<PackageInfo>(list);
5315        }
5316    }
5317
5318    @Override
5319    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5320        if (!sUserManager.exists(userId)) return null;
5321        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5322
5323        // writer
5324        synchronized (mPackages) {
5325            ArrayList<ApplicationInfo> list;
5326            if (listUninstalled) {
5327                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5328                for (PackageSetting ps : mSettings.mPackages.values()) {
5329                    ApplicationInfo ai;
5330                    if (ps.pkg != null) {
5331                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5332                                ps.readUserState(userId), userId);
5333                    } else {
5334                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5335                    }
5336                    if (ai != null) {
5337                        list.add(ai);
5338                    }
5339                }
5340            } else {
5341                list = new ArrayList<ApplicationInfo>(mPackages.size());
5342                for (PackageParser.Package p : mPackages.values()) {
5343                    if (p.mExtras != null) {
5344                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5345                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5346                        if (ai != null) {
5347                            list.add(ai);
5348                        }
5349                    }
5350                }
5351            }
5352
5353            return new ParceledListSlice<ApplicationInfo>(list);
5354        }
5355    }
5356
5357    public List<ApplicationInfo> getPersistentApplications(int flags) {
5358        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5359
5360        // reader
5361        synchronized (mPackages) {
5362            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5363            final int userId = UserHandle.getCallingUserId();
5364            while (i.hasNext()) {
5365                final PackageParser.Package p = i.next();
5366                if (p.applicationInfo != null
5367                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5368                        && (!mSafeMode || isSystemApp(p))) {
5369                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5370                    if (ps != null) {
5371                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5372                                ps.readUserState(userId), userId);
5373                        if (ai != null) {
5374                            finalList.add(ai);
5375                        }
5376                    }
5377                }
5378            }
5379        }
5380
5381        return finalList;
5382    }
5383
5384    @Override
5385    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5386        if (!sUserManager.exists(userId)) return null;
5387        // reader
5388        synchronized (mPackages) {
5389            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5390            PackageSetting ps = provider != null
5391                    ? mSettings.mPackages.get(provider.owner.packageName)
5392                    : null;
5393            return ps != null
5394                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5395                    && (!mSafeMode || (provider.info.applicationInfo.flags
5396                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5397                    ? PackageParser.generateProviderInfo(provider, flags,
5398                            ps.readUserState(userId), userId)
5399                    : null;
5400        }
5401    }
5402
5403    /**
5404     * @deprecated
5405     */
5406    @Deprecated
5407    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5408        // reader
5409        synchronized (mPackages) {
5410            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5411                    .entrySet().iterator();
5412            final int userId = UserHandle.getCallingUserId();
5413            while (i.hasNext()) {
5414                Map.Entry<String, PackageParser.Provider> entry = i.next();
5415                PackageParser.Provider p = entry.getValue();
5416                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5417
5418                if (ps != null && p.syncable
5419                        && (!mSafeMode || (p.info.applicationInfo.flags
5420                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5421                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5422                            ps.readUserState(userId), userId);
5423                    if (info != null) {
5424                        outNames.add(entry.getKey());
5425                        outInfo.add(info);
5426                    }
5427                }
5428            }
5429        }
5430    }
5431
5432    @Override
5433    public List<ProviderInfo> queryContentProviders(String processName,
5434            int uid, int flags) {
5435        ArrayList<ProviderInfo> finalList = null;
5436        // reader
5437        synchronized (mPackages) {
5438            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5439            final int userId = processName != null ?
5440                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5441            while (i.hasNext()) {
5442                final PackageParser.Provider p = i.next();
5443                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5444                if (ps != null && p.info.authority != null
5445                        && (processName == null
5446                                || (p.info.processName.equals(processName)
5447                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5448                        && mSettings.isEnabledLPr(p.info, flags, userId)
5449                        && (!mSafeMode
5450                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5451                    if (finalList == null) {
5452                        finalList = new ArrayList<ProviderInfo>(3);
5453                    }
5454                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5455                            ps.readUserState(userId), userId);
5456                    if (info != null) {
5457                        finalList.add(info);
5458                    }
5459                }
5460            }
5461        }
5462
5463        if (finalList != null) {
5464            Collections.sort(finalList, mProviderInitOrderSorter);
5465        }
5466
5467        return finalList;
5468    }
5469
5470    @Override
5471    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5472            int flags) {
5473        // reader
5474        synchronized (mPackages) {
5475            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5476            return PackageParser.generateInstrumentationInfo(i, flags);
5477        }
5478    }
5479
5480    @Override
5481    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5482            int flags) {
5483        ArrayList<InstrumentationInfo> finalList =
5484            new ArrayList<InstrumentationInfo>();
5485
5486        // reader
5487        synchronized (mPackages) {
5488            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5489            while (i.hasNext()) {
5490                final PackageParser.Instrumentation p = i.next();
5491                if (targetPackage == null
5492                        || targetPackage.equals(p.info.targetPackage)) {
5493                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5494                            flags);
5495                    if (ii != null) {
5496                        finalList.add(ii);
5497                    }
5498                }
5499            }
5500        }
5501
5502        return finalList;
5503    }
5504
5505    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5506        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5507        if (overlays == null) {
5508            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5509            return;
5510        }
5511        for (PackageParser.Package opkg : overlays.values()) {
5512            // Not much to do if idmap fails: we already logged the error
5513            // and we certainly don't want to abort installation of pkg simply
5514            // because an overlay didn't fit properly. For these reasons,
5515            // ignore the return value of createIdmapForPackagePairLI.
5516            createIdmapForPackagePairLI(pkg, opkg);
5517        }
5518    }
5519
5520    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5521            PackageParser.Package opkg) {
5522        if (!opkg.mTrustedOverlay) {
5523            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5524                    opkg.baseCodePath + ": overlay not trusted");
5525            return false;
5526        }
5527        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5528        if (overlaySet == null) {
5529            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5530                    opkg.baseCodePath + " but target package has no known overlays");
5531            return false;
5532        }
5533        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5534        // TODO: generate idmap for split APKs
5535        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5536            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5537                    + opkg.baseCodePath);
5538            return false;
5539        }
5540        PackageParser.Package[] overlayArray =
5541            overlaySet.values().toArray(new PackageParser.Package[0]);
5542        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5543            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5544                return p1.mOverlayPriority - p2.mOverlayPriority;
5545            }
5546        };
5547        Arrays.sort(overlayArray, cmp);
5548
5549        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5550        int i = 0;
5551        for (PackageParser.Package p : overlayArray) {
5552            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5553        }
5554        return true;
5555    }
5556
5557    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5558        final File[] files = dir.listFiles();
5559        if (ArrayUtils.isEmpty(files)) {
5560            Log.d(TAG, "No files in app dir " + dir);
5561            return;
5562        }
5563
5564        if (DEBUG_PACKAGE_SCANNING) {
5565            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5566                    + " flags=0x" + Integer.toHexString(parseFlags));
5567        }
5568
5569        for (File file : files) {
5570            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5571                    && !PackageInstallerService.isStageName(file.getName());
5572            if (!isPackage) {
5573                // Ignore entries which are not packages
5574                continue;
5575            }
5576            try {
5577                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5578                        scanFlags, currentTime, null);
5579            } catch (PackageManagerException e) {
5580                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5581
5582                // Delete invalid userdata apps
5583                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5584                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5585                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5586                    if (file.isDirectory()) {
5587                        mInstaller.rmPackageDir(file.getAbsolutePath());
5588                    } else {
5589                        file.delete();
5590                    }
5591                }
5592            }
5593        }
5594    }
5595
5596    private static File getSettingsProblemFile() {
5597        File dataDir = Environment.getDataDirectory();
5598        File systemDir = new File(dataDir, "system");
5599        File fname = new File(systemDir, "uiderrors.txt");
5600        return fname;
5601    }
5602
5603    static void reportSettingsProblem(int priority, String msg) {
5604        logCriticalInfo(priority, msg);
5605    }
5606
5607    static void logCriticalInfo(int priority, String msg) {
5608        Slog.println(priority, TAG, msg);
5609        EventLogTags.writePmCriticalInfo(msg);
5610        try {
5611            File fname = getSettingsProblemFile();
5612            FileOutputStream out = new FileOutputStream(fname, true);
5613            PrintWriter pw = new FastPrintWriter(out);
5614            SimpleDateFormat formatter = new SimpleDateFormat();
5615            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5616            pw.println(dateString + ": " + msg);
5617            pw.close();
5618            FileUtils.setPermissions(
5619                    fname.toString(),
5620                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5621                    -1, -1);
5622        } catch (java.io.IOException e) {
5623        }
5624    }
5625
5626    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5627            PackageParser.Package pkg, File srcFile, int parseFlags)
5628            throws PackageManagerException {
5629        if (ps != null
5630                && ps.codePath.equals(srcFile)
5631                && ps.timeStamp == srcFile.lastModified()
5632                && !isCompatSignatureUpdateNeeded(pkg)
5633                && !isRecoverSignatureUpdateNeeded(pkg)) {
5634            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5635            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5636            ArraySet<PublicKey> signingKs;
5637            synchronized (mPackages) {
5638                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5639            }
5640            if (ps.signatures.mSignatures != null
5641                    && ps.signatures.mSignatures.length != 0
5642                    && signingKs != null) {
5643                // Optimization: reuse the existing cached certificates
5644                // if the package appears to be unchanged.
5645                pkg.mSignatures = ps.signatures.mSignatures;
5646                pkg.mSigningKeys = signingKs;
5647                return;
5648            }
5649
5650            Slog.w(TAG, "PackageSetting for " + ps.name
5651                    + " is missing signatures.  Collecting certs again to recover them.");
5652        } else {
5653            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5654        }
5655
5656        try {
5657            pp.collectCertificates(pkg, parseFlags);
5658            pp.collectManifestDigest(pkg);
5659        } catch (PackageParserException e) {
5660            throw PackageManagerException.from(e);
5661        }
5662    }
5663
5664    /*
5665     *  Scan a package and return the newly parsed package.
5666     *  Returns null in case of errors and the error code is stored in mLastScanError
5667     */
5668    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5669            long currentTime, UserHandle user) throws PackageManagerException {
5670        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5671        parseFlags |= mDefParseFlags;
5672        PackageParser pp = new PackageParser();
5673        pp.setSeparateProcesses(mSeparateProcesses);
5674        pp.setOnlyCoreApps(mOnlyCore);
5675        pp.setDisplayMetrics(mMetrics);
5676
5677        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5678            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5679        }
5680
5681        final PackageParser.Package pkg;
5682        try {
5683            pkg = pp.parsePackage(scanFile, parseFlags);
5684        } catch (PackageParserException e) {
5685            throw PackageManagerException.from(e);
5686        }
5687
5688        PackageSetting ps = null;
5689        PackageSetting updatedPkg;
5690        // reader
5691        synchronized (mPackages) {
5692            // Look to see if we already know about this package.
5693            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5694            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5695                // This package has been renamed to its original name.  Let's
5696                // use that.
5697                ps = mSettings.peekPackageLPr(oldName);
5698            }
5699            // If there was no original package, see one for the real package name.
5700            if (ps == null) {
5701                ps = mSettings.peekPackageLPr(pkg.packageName);
5702            }
5703            // Check to see if this package could be hiding/updating a system
5704            // package.  Must look for it either under the original or real
5705            // package name depending on our state.
5706            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5707            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5708        }
5709        boolean updatedPkgBetter = false;
5710        // First check if this is a system package that may involve an update
5711        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5712            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5713            // it needs to drop FLAG_PRIVILEGED.
5714            if (locationIsPrivileged(scanFile)) {
5715                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5716            } else {
5717                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5718            }
5719
5720            if (ps != null && !ps.codePath.equals(scanFile)) {
5721                // The path has changed from what was last scanned...  check the
5722                // version of the new path against what we have stored to determine
5723                // what to do.
5724                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5725                if (pkg.mVersionCode <= ps.versionCode) {
5726                    // The system package has been updated and the code path does not match
5727                    // Ignore entry. Skip it.
5728                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5729                            + " ignored: updated version " + ps.versionCode
5730                            + " better than this " + pkg.mVersionCode);
5731                    if (!updatedPkg.codePath.equals(scanFile)) {
5732                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5733                                + ps.name + " changing from " + updatedPkg.codePathString
5734                                + " to " + scanFile);
5735                        updatedPkg.codePath = scanFile;
5736                        updatedPkg.codePathString = scanFile.toString();
5737                        updatedPkg.resourcePath = scanFile;
5738                        updatedPkg.resourcePathString = scanFile.toString();
5739                    }
5740                    updatedPkg.pkg = pkg;
5741                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5742                            "Package " + ps.name + " at " + scanFile
5743                                    + " ignored: updated version " + ps.versionCode
5744                                    + " better than this " + pkg.mVersionCode);
5745                } else {
5746                    // The current app on the system partition is better than
5747                    // what we have updated to on the data partition; switch
5748                    // back to the system partition version.
5749                    // At this point, its safely assumed that package installation for
5750                    // apps in system partition will go through. If not there won't be a working
5751                    // version of the app
5752                    // writer
5753                    synchronized (mPackages) {
5754                        // Just remove the loaded entries from package lists.
5755                        mPackages.remove(ps.name);
5756                    }
5757
5758                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5759                            + " reverting from " + ps.codePathString
5760                            + ": new version " + pkg.mVersionCode
5761                            + " better than installed " + ps.versionCode);
5762
5763                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5764                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5765                    synchronized (mInstallLock) {
5766                        args.cleanUpResourcesLI();
5767                    }
5768                    synchronized (mPackages) {
5769                        mSettings.enableSystemPackageLPw(ps.name);
5770                    }
5771                    updatedPkgBetter = true;
5772                }
5773            }
5774        }
5775
5776        if (updatedPkg != null) {
5777            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5778            // initially
5779            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5780
5781            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5782            // flag set initially
5783            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5784                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5785            }
5786        }
5787
5788        // Verify certificates against what was last scanned
5789        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5790
5791        /*
5792         * A new system app appeared, but we already had a non-system one of the
5793         * same name installed earlier.
5794         */
5795        boolean shouldHideSystemApp = false;
5796        if (updatedPkg == null && ps != null
5797                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5798            /*
5799             * Check to make sure the signatures match first. If they don't,
5800             * wipe the installed application and its data.
5801             */
5802            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5803                    != PackageManager.SIGNATURE_MATCH) {
5804                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5805                        + " signatures don't match existing userdata copy; removing");
5806                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5807                ps = null;
5808            } else {
5809                /*
5810                 * If the newly-added system app is an older version than the
5811                 * already installed version, hide it. It will be scanned later
5812                 * and re-added like an update.
5813                 */
5814                if (pkg.mVersionCode <= ps.versionCode) {
5815                    shouldHideSystemApp = true;
5816                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5817                            + " but new version " + pkg.mVersionCode + " better than installed "
5818                            + ps.versionCode + "; hiding system");
5819                } else {
5820                    /*
5821                     * The newly found system app is a newer version that the
5822                     * one previously installed. Simply remove the
5823                     * already-installed application and replace it with our own
5824                     * while keeping the application data.
5825                     */
5826                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5827                            + " reverting from " + ps.codePathString + ": new version "
5828                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5829                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5830                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5831                    synchronized (mInstallLock) {
5832                        args.cleanUpResourcesLI();
5833                    }
5834                }
5835            }
5836        }
5837
5838        // The apk is forward locked (not public) if its code and resources
5839        // are kept in different files. (except for app in either system or
5840        // vendor path).
5841        // TODO grab this value from PackageSettings
5842        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5843            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5844                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5845            }
5846        }
5847
5848        // TODO: extend to support forward-locked splits
5849        String resourcePath = null;
5850        String baseResourcePath = null;
5851        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5852            if (ps != null && ps.resourcePathString != null) {
5853                resourcePath = ps.resourcePathString;
5854                baseResourcePath = ps.resourcePathString;
5855            } else {
5856                // Should not happen at all. Just log an error.
5857                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5858            }
5859        } else {
5860            resourcePath = pkg.codePath;
5861            baseResourcePath = pkg.baseCodePath;
5862        }
5863
5864        // Set application objects path explicitly.
5865        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5866        pkg.applicationInfo.setCodePath(pkg.codePath);
5867        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5868        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5869        pkg.applicationInfo.setResourcePath(resourcePath);
5870        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5871        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5872
5873        // Note that we invoke the following method only if we are about to unpack an application
5874        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5875                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5876
5877        /*
5878         * If the system app should be overridden by a previously installed
5879         * data, hide the system app now and let the /data/app scan pick it up
5880         * again.
5881         */
5882        if (shouldHideSystemApp) {
5883            synchronized (mPackages) {
5884                /*
5885                 * We have to grant systems permissions before we hide, because
5886                 * grantPermissions will assume the package update is trying to
5887                 * expand its permissions.
5888                 */
5889                grantPermissionsLPw(pkg, true, pkg.packageName);
5890                mSettings.disableSystemPackageLPw(pkg.packageName);
5891            }
5892        }
5893
5894        return scannedPkg;
5895    }
5896
5897    private static String fixProcessName(String defProcessName,
5898            String processName, int uid) {
5899        if (processName == null) {
5900            return defProcessName;
5901        }
5902        return processName;
5903    }
5904
5905    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5906            throws PackageManagerException {
5907        if (pkgSetting.signatures.mSignatures != null) {
5908            // Already existing package. Make sure signatures match
5909            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5910                    == PackageManager.SIGNATURE_MATCH;
5911            if (!match) {
5912                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5913                        == PackageManager.SIGNATURE_MATCH;
5914            }
5915            if (!match) {
5916                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5917                        == PackageManager.SIGNATURE_MATCH;
5918            }
5919            if (!match) {
5920                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5921                        + pkg.packageName + " signatures do not match the "
5922                        + "previously installed version; ignoring!");
5923            }
5924        }
5925
5926        // Check for shared user signatures
5927        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5928            // Already existing package. Make sure signatures match
5929            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5930                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5931            if (!match) {
5932                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5933                        == PackageManager.SIGNATURE_MATCH;
5934            }
5935            if (!match) {
5936                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5937                        == PackageManager.SIGNATURE_MATCH;
5938            }
5939            if (!match) {
5940                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5941                        "Package " + pkg.packageName
5942                        + " has no signatures that match those in shared user "
5943                        + pkgSetting.sharedUser.name + "; ignoring!");
5944            }
5945        }
5946    }
5947
5948    /**
5949     * Enforces that only the system UID or root's UID can call a method exposed
5950     * via Binder.
5951     *
5952     * @param message used as message if SecurityException is thrown
5953     * @throws SecurityException if the caller is not system or root
5954     */
5955    private static final void enforceSystemOrRoot(String message) {
5956        final int uid = Binder.getCallingUid();
5957        if (uid != Process.SYSTEM_UID && uid != 0) {
5958            throw new SecurityException(message);
5959        }
5960    }
5961
5962    @Override
5963    public void performBootDexOpt() {
5964        enforceSystemOrRoot("Only the system can request dexopt be performed");
5965
5966        // Before everything else, see whether we need to fstrim.
5967        try {
5968            IMountService ms = PackageHelper.getMountService();
5969            if (ms != null) {
5970                final boolean isUpgrade = isUpgrade();
5971                boolean doTrim = isUpgrade;
5972                if (doTrim) {
5973                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5974                } else {
5975                    final long interval = android.provider.Settings.Global.getLong(
5976                            mContext.getContentResolver(),
5977                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5978                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5979                    if (interval > 0) {
5980                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5981                        if (timeSinceLast > interval) {
5982                            doTrim = true;
5983                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5984                                    + "; running immediately");
5985                        }
5986                    }
5987                }
5988                if (doTrim) {
5989                    if (!isFirstBoot()) {
5990                        try {
5991                            ActivityManagerNative.getDefault().showBootMessage(
5992                                    mContext.getResources().getString(
5993                                            R.string.android_upgrading_fstrim), true);
5994                        } catch (RemoteException e) {
5995                        }
5996                    }
5997                    ms.runMaintenance();
5998                }
5999            } else {
6000                Slog.e(TAG, "Mount service unavailable!");
6001            }
6002        } catch (RemoteException e) {
6003            // Can't happen; MountService is local
6004        }
6005
6006        final ArraySet<PackageParser.Package> pkgs;
6007        synchronized (mPackages) {
6008            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6009        }
6010
6011        if (pkgs != null) {
6012            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6013            // in case the device runs out of space.
6014            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6015            // Give priority to core apps.
6016            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6017                PackageParser.Package pkg = it.next();
6018                if (pkg.coreApp) {
6019                    if (DEBUG_DEXOPT) {
6020                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6021                    }
6022                    sortedPkgs.add(pkg);
6023                    it.remove();
6024                }
6025            }
6026            // Give priority to system apps that listen for pre boot complete.
6027            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6028            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6029            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6030                PackageParser.Package pkg = it.next();
6031                if (pkgNames.contains(pkg.packageName)) {
6032                    if (DEBUG_DEXOPT) {
6033                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6034                    }
6035                    sortedPkgs.add(pkg);
6036                    it.remove();
6037                }
6038            }
6039            // Give priority to system apps.
6040            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6041                PackageParser.Package pkg = it.next();
6042                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6043                    if (DEBUG_DEXOPT) {
6044                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6045                    }
6046                    sortedPkgs.add(pkg);
6047                    it.remove();
6048                }
6049            }
6050            // Give priority to updated system apps.
6051            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6052                PackageParser.Package pkg = it.next();
6053                if (pkg.isUpdatedSystemApp()) {
6054                    if (DEBUG_DEXOPT) {
6055                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6056                    }
6057                    sortedPkgs.add(pkg);
6058                    it.remove();
6059                }
6060            }
6061            // Give priority to apps that listen for boot complete.
6062            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6063            pkgNames = getPackageNamesForIntent(intent);
6064            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6065                PackageParser.Package pkg = it.next();
6066                if (pkgNames.contains(pkg.packageName)) {
6067                    if (DEBUG_DEXOPT) {
6068                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6069                    }
6070                    sortedPkgs.add(pkg);
6071                    it.remove();
6072                }
6073            }
6074            // Filter out packages that aren't recently used.
6075            filterRecentlyUsedApps(pkgs);
6076            // Add all remaining apps.
6077            for (PackageParser.Package pkg : pkgs) {
6078                if (DEBUG_DEXOPT) {
6079                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6080                }
6081                sortedPkgs.add(pkg);
6082            }
6083
6084            // If we want to be lazy, filter everything that wasn't recently used.
6085            if (mLazyDexOpt) {
6086                filterRecentlyUsedApps(sortedPkgs);
6087            }
6088
6089            int i = 0;
6090            int total = sortedPkgs.size();
6091            File dataDir = Environment.getDataDirectory();
6092            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6093            if (lowThreshold == 0) {
6094                throw new IllegalStateException("Invalid low memory threshold");
6095            }
6096            for (PackageParser.Package pkg : sortedPkgs) {
6097                long usableSpace = dataDir.getUsableSpace();
6098                if (usableSpace < lowThreshold) {
6099                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6100                    break;
6101                }
6102                performBootDexOpt(pkg, ++i, total);
6103            }
6104        }
6105    }
6106
6107    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6108        // Filter out packages that aren't recently used.
6109        //
6110        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6111        // should do a full dexopt.
6112        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6113            int total = pkgs.size();
6114            int skipped = 0;
6115            long now = System.currentTimeMillis();
6116            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6117                PackageParser.Package pkg = i.next();
6118                long then = pkg.mLastPackageUsageTimeInMills;
6119                if (then + mDexOptLRUThresholdInMills < now) {
6120                    if (DEBUG_DEXOPT) {
6121                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6122                              ((then == 0) ? "never" : new Date(then)));
6123                    }
6124                    i.remove();
6125                    skipped++;
6126                }
6127            }
6128            if (DEBUG_DEXOPT) {
6129                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6130            }
6131        }
6132    }
6133
6134    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6135        List<ResolveInfo> ris = null;
6136        try {
6137            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6138                    intent, null, 0, UserHandle.USER_OWNER);
6139        } catch (RemoteException e) {
6140        }
6141        ArraySet<String> pkgNames = new ArraySet<String>();
6142        if (ris != null) {
6143            for (ResolveInfo ri : ris) {
6144                pkgNames.add(ri.activityInfo.packageName);
6145            }
6146        }
6147        return pkgNames;
6148    }
6149
6150    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6151        if (DEBUG_DEXOPT) {
6152            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6153        }
6154        if (!isFirstBoot()) {
6155            try {
6156                ActivityManagerNative.getDefault().showBootMessage(
6157                        mContext.getResources().getString(R.string.android_upgrading_apk,
6158                                curr, total), true);
6159            } catch (RemoteException e) {
6160            }
6161        }
6162        PackageParser.Package p = pkg;
6163        synchronized (mInstallLock) {
6164            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6165                    false /* force dex */, false /* defer */, true /* include dependencies */);
6166        }
6167    }
6168
6169    @Override
6170    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6171        return performDexOpt(packageName, instructionSet, false);
6172    }
6173
6174    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6175        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6176        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6177        if (!dexopt && !updateUsage) {
6178            // We aren't going to dexopt or update usage, so bail early.
6179            return false;
6180        }
6181        PackageParser.Package p;
6182        final String targetInstructionSet;
6183        synchronized (mPackages) {
6184            p = mPackages.get(packageName);
6185            if (p == null) {
6186                return false;
6187            }
6188            if (updateUsage) {
6189                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6190            }
6191            mPackageUsage.write(false);
6192            if (!dexopt) {
6193                // We aren't going to dexopt, so bail early.
6194                return false;
6195            }
6196
6197            targetInstructionSet = instructionSet != null ? instructionSet :
6198                    getPrimaryInstructionSet(p.applicationInfo);
6199            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6200                return false;
6201            }
6202        }
6203        long callingId = Binder.clearCallingIdentity();
6204        try {
6205            synchronized (mInstallLock) {
6206                final String[] instructionSets = new String[] { targetInstructionSet };
6207                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6208                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6209                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6210            }
6211        } finally {
6212            Binder.restoreCallingIdentity(callingId);
6213        }
6214    }
6215
6216    public ArraySet<String> getPackagesThatNeedDexOpt() {
6217        ArraySet<String> pkgs = null;
6218        synchronized (mPackages) {
6219            for (PackageParser.Package p : mPackages.values()) {
6220                if (DEBUG_DEXOPT) {
6221                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6222                }
6223                if (!p.mDexOptPerformed.isEmpty()) {
6224                    continue;
6225                }
6226                if (pkgs == null) {
6227                    pkgs = new ArraySet<String>();
6228                }
6229                pkgs.add(p.packageName);
6230            }
6231        }
6232        return pkgs;
6233    }
6234
6235    public void shutdown() {
6236        mPackageUsage.write(true);
6237    }
6238
6239    @Override
6240    public void forceDexOpt(String packageName) {
6241        enforceSystemOrRoot("forceDexOpt");
6242
6243        PackageParser.Package pkg;
6244        synchronized (mPackages) {
6245            pkg = mPackages.get(packageName);
6246            if (pkg == null) {
6247                throw new IllegalArgumentException("Missing package: " + packageName);
6248            }
6249        }
6250
6251        synchronized (mInstallLock) {
6252            final String[] instructionSets = new String[] {
6253                    getPrimaryInstructionSet(pkg.applicationInfo) };
6254            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6255                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6256            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6257                throw new IllegalStateException("Failed to dexopt: " + res);
6258            }
6259        }
6260    }
6261
6262    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6263        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6264            Slog.w(TAG, "Unable to update from " + oldPkg.name
6265                    + " to " + newPkg.packageName
6266                    + ": old package not in system partition");
6267            return false;
6268        } else if (mPackages.get(oldPkg.name) != null) {
6269            Slog.w(TAG, "Unable to update from " + oldPkg.name
6270                    + " to " + newPkg.packageName
6271                    + ": old package still exists");
6272            return false;
6273        }
6274        return true;
6275    }
6276
6277    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6278        int[] users = sUserManager.getUserIds();
6279        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6280        if (res < 0) {
6281            return res;
6282        }
6283        for (int user : users) {
6284            if (user != 0) {
6285                res = mInstaller.createUserData(volumeUuid, packageName,
6286                        UserHandle.getUid(user, uid), user, seinfo);
6287                if (res < 0) {
6288                    return res;
6289                }
6290            }
6291        }
6292        return res;
6293    }
6294
6295    private int removeDataDirsLI(String volumeUuid, String packageName) {
6296        int[] users = sUserManager.getUserIds();
6297        int res = 0;
6298        for (int user : users) {
6299            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6300            if (resInner < 0) {
6301                res = resInner;
6302            }
6303        }
6304
6305        return res;
6306    }
6307
6308    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6309        int[] users = sUserManager.getUserIds();
6310        int res = 0;
6311        for (int user : users) {
6312            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6313            if (resInner < 0) {
6314                res = resInner;
6315            }
6316        }
6317        return res;
6318    }
6319
6320    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6321            PackageParser.Package changingLib) {
6322        if (file.path != null) {
6323            usesLibraryFiles.add(file.path);
6324            return;
6325        }
6326        PackageParser.Package p = mPackages.get(file.apk);
6327        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6328            // If we are doing this while in the middle of updating a library apk,
6329            // then we need to make sure to use that new apk for determining the
6330            // dependencies here.  (We haven't yet finished committing the new apk
6331            // to the package manager state.)
6332            if (p == null || p.packageName.equals(changingLib.packageName)) {
6333                p = changingLib;
6334            }
6335        }
6336        if (p != null) {
6337            usesLibraryFiles.addAll(p.getAllCodePaths());
6338        }
6339    }
6340
6341    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6342            PackageParser.Package changingLib) throws PackageManagerException {
6343        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6344            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6345            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6346            for (int i=0; i<N; i++) {
6347                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6348                if (file == null) {
6349                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6350                            "Package " + pkg.packageName + " requires unavailable shared library "
6351                            + pkg.usesLibraries.get(i) + "; failing!");
6352                }
6353                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6354            }
6355            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6356            for (int i=0; i<N; i++) {
6357                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6358                if (file == null) {
6359                    Slog.w(TAG, "Package " + pkg.packageName
6360                            + " desires unavailable shared library "
6361                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6362                } else {
6363                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6364                }
6365            }
6366            N = usesLibraryFiles.size();
6367            if (N > 0) {
6368                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6369            } else {
6370                pkg.usesLibraryFiles = null;
6371            }
6372        }
6373    }
6374
6375    private static boolean hasString(List<String> list, List<String> which) {
6376        if (list == null) {
6377            return false;
6378        }
6379        for (int i=list.size()-1; i>=0; i--) {
6380            for (int j=which.size()-1; j>=0; j--) {
6381                if (which.get(j).equals(list.get(i))) {
6382                    return true;
6383                }
6384            }
6385        }
6386        return false;
6387    }
6388
6389    private void updateAllSharedLibrariesLPw() {
6390        for (PackageParser.Package pkg : mPackages.values()) {
6391            try {
6392                updateSharedLibrariesLPw(pkg, null);
6393            } catch (PackageManagerException e) {
6394                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6395            }
6396        }
6397    }
6398
6399    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6400            PackageParser.Package changingPkg) {
6401        ArrayList<PackageParser.Package> res = null;
6402        for (PackageParser.Package pkg : mPackages.values()) {
6403            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6404                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6405                if (res == null) {
6406                    res = new ArrayList<PackageParser.Package>();
6407                }
6408                res.add(pkg);
6409                try {
6410                    updateSharedLibrariesLPw(pkg, changingPkg);
6411                } catch (PackageManagerException e) {
6412                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6413                }
6414            }
6415        }
6416        return res;
6417    }
6418
6419    /**
6420     * Derive the value of the {@code cpuAbiOverride} based on the provided
6421     * value and an optional stored value from the package settings.
6422     */
6423    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6424        String cpuAbiOverride = null;
6425
6426        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6427            cpuAbiOverride = null;
6428        } else if (abiOverride != null) {
6429            cpuAbiOverride = abiOverride;
6430        } else if (settings != null) {
6431            cpuAbiOverride = settings.cpuAbiOverrideString;
6432        }
6433
6434        return cpuAbiOverride;
6435    }
6436
6437    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6438            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6439        boolean success = false;
6440        try {
6441            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6442                    currentTime, user);
6443            success = true;
6444            return res;
6445        } finally {
6446            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6447                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6448            }
6449        }
6450    }
6451
6452    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6453            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6454        final File scanFile = new File(pkg.codePath);
6455        if (pkg.applicationInfo.getCodePath() == null ||
6456                pkg.applicationInfo.getResourcePath() == null) {
6457            // Bail out. The resource and code paths haven't been set.
6458            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6459                    "Code and resource paths haven't been set correctly");
6460        }
6461
6462        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6463            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6464        } else {
6465            // Only allow system apps to be flagged as core apps.
6466            pkg.coreApp = false;
6467        }
6468
6469        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6470            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6471        }
6472
6473        if (mCustomResolverComponentName != null &&
6474                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6475            setUpCustomResolverActivity(pkg);
6476        }
6477
6478        if (pkg.packageName.equals("android")) {
6479            synchronized (mPackages) {
6480                if (mAndroidApplication != null) {
6481                    Slog.w(TAG, "*************************************************");
6482                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6483                    Slog.w(TAG, " file=" + scanFile);
6484                    Slog.w(TAG, "*************************************************");
6485                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6486                            "Core android package being redefined.  Skipping.");
6487                }
6488
6489                // Set up information for our fall-back user intent resolution activity.
6490                mPlatformPackage = pkg;
6491                pkg.mVersionCode = mSdkVersion;
6492                mAndroidApplication = pkg.applicationInfo;
6493
6494                if (!mResolverReplaced) {
6495                    mResolveActivity.applicationInfo = mAndroidApplication;
6496                    mResolveActivity.name = ResolverActivity.class.getName();
6497                    mResolveActivity.packageName = mAndroidApplication.packageName;
6498                    mResolveActivity.processName = "system:ui";
6499                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6500                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6501                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6502                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6503                    mResolveActivity.exported = true;
6504                    mResolveActivity.enabled = true;
6505                    mResolveInfo.activityInfo = mResolveActivity;
6506                    mResolveInfo.priority = 0;
6507                    mResolveInfo.preferredOrder = 0;
6508                    mResolveInfo.match = 0;
6509                    mResolveComponentName = new ComponentName(
6510                            mAndroidApplication.packageName, mResolveActivity.name);
6511                }
6512            }
6513        }
6514
6515        if (DEBUG_PACKAGE_SCANNING) {
6516            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6517                Log.d(TAG, "Scanning package " + pkg.packageName);
6518        }
6519
6520        if (mPackages.containsKey(pkg.packageName)
6521                || mSharedLibraries.containsKey(pkg.packageName)) {
6522            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6523                    "Application package " + pkg.packageName
6524                    + " already installed.  Skipping duplicate.");
6525        }
6526
6527        // If we're only installing presumed-existing packages, require that the
6528        // scanned APK is both already known and at the path previously established
6529        // for it.  Previously unknown packages we pick up normally, but if we have an
6530        // a priori expectation about this package's install presence, enforce it.
6531        // With a singular exception for new system packages. When an OTA contains
6532        // a new system package, we allow the codepath to change from a system location
6533        // to the user-installed location. If we don't allow this change, any newer,
6534        // user-installed version of the application will be ignored.
6535        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6536            if (mExpectingBetter.containsKey(pkg.packageName)) {
6537                logCriticalInfo(Log.WARN,
6538                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6539            } else {
6540                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6541                if (known != null) {
6542                    if (DEBUG_PACKAGE_SCANNING) {
6543                        Log.d(TAG, "Examining " + pkg.codePath
6544                                + " and requiring known paths " + known.codePathString
6545                                + " & " + known.resourcePathString);
6546                    }
6547                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6548                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6549                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6550                                "Application package " + pkg.packageName
6551                                + " found at " + pkg.applicationInfo.getCodePath()
6552                                + " but expected at " + known.codePathString + "; ignoring.");
6553                    }
6554                }
6555            }
6556        }
6557
6558        // Initialize package source and resource directories
6559        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6560        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6561
6562        SharedUserSetting suid = null;
6563        PackageSetting pkgSetting = null;
6564
6565        if (!isSystemApp(pkg)) {
6566            // Only system apps can use these features.
6567            pkg.mOriginalPackages = null;
6568            pkg.mRealPackage = null;
6569            pkg.mAdoptPermissions = null;
6570        }
6571
6572        // writer
6573        synchronized (mPackages) {
6574            if (pkg.mSharedUserId != null) {
6575                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6576                if (suid == null) {
6577                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6578                            "Creating application package " + pkg.packageName
6579                            + " for shared user failed");
6580                }
6581                if (DEBUG_PACKAGE_SCANNING) {
6582                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6583                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6584                                + "): packages=" + suid.packages);
6585                }
6586            }
6587
6588            // Check if we are renaming from an original package name.
6589            PackageSetting origPackage = null;
6590            String realName = null;
6591            if (pkg.mOriginalPackages != null) {
6592                // This package may need to be renamed to a previously
6593                // installed name.  Let's check on that...
6594                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6595                if (pkg.mOriginalPackages.contains(renamed)) {
6596                    // This package had originally been installed as the
6597                    // original name, and we have already taken care of
6598                    // transitioning to the new one.  Just update the new
6599                    // one to continue using the old name.
6600                    realName = pkg.mRealPackage;
6601                    if (!pkg.packageName.equals(renamed)) {
6602                        // Callers into this function may have already taken
6603                        // care of renaming the package; only do it here if
6604                        // it is not already done.
6605                        pkg.setPackageName(renamed);
6606                    }
6607
6608                } else {
6609                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6610                        if ((origPackage = mSettings.peekPackageLPr(
6611                                pkg.mOriginalPackages.get(i))) != null) {
6612                            // We do have the package already installed under its
6613                            // original name...  should we use it?
6614                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6615                                // New package is not compatible with original.
6616                                origPackage = null;
6617                                continue;
6618                            } else if (origPackage.sharedUser != null) {
6619                                // Make sure uid is compatible between packages.
6620                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6621                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6622                                            + " to " + pkg.packageName + ": old uid "
6623                                            + origPackage.sharedUser.name
6624                                            + " differs from " + pkg.mSharedUserId);
6625                                    origPackage = null;
6626                                    continue;
6627                                }
6628                            } else {
6629                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6630                                        + pkg.packageName + " to old name " + origPackage.name);
6631                            }
6632                            break;
6633                        }
6634                    }
6635                }
6636            }
6637
6638            if (mTransferedPackages.contains(pkg.packageName)) {
6639                Slog.w(TAG, "Package " + pkg.packageName
6640                        + " was transferred to another, but its .apk remains");
6641            }
6642
6643            // Just create the setting, don't add it yet. For already existing packages
6644            // the PkgSetting exists already and doesn't have to be created.
6645            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6646                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6647                    pkg.applicationInfo.primaryCpuAbi,
6648                    pkg.applicationInfo.secondaryCpuAbi,
6649                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6650                    user, false);
6651            if (pkgSetting == null) {
6652                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6653                        "Creating application package " + pkg.packageName + " failed");
6654            }
6655
6656            if (pkgSetting.origPackage != null) {
6657                // If we are first transitioning from an original package,
6658                // fix up the new package's name now.  We need to do this after
6659                // looking up the package under its new name, so getPackageLP
6660                // can take care of fiddling things correctly.
6661                pkg.setPackageName(origPackage.name);
6662
6663                // File a report about this.
6664                String msg = "New package " + pkgSetting.realName
6665                        + " renamed to replace old package " + pkgSetting.name;
6666                reportSettingsProblem(Log.WARN, msg);
6667
6668                // Make a note of it.
6669                mTransferedPackages.add(origPackage.name);
6670
6671                // No longer need to retain this.
6672                pkgSetting.origPackage = null;
6673            }
6674
6675            if (realName != null) {
6676                // Make a note of it.
6677                mTransferedPackages.add(pkg.packageName);
6678            }
6679
6680            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6681                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6682            }
6683
6684            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6685                // Check all shared libraries and map to their actual file path.
6686                // We only do this here for apps not on a system dir, because those
6687                // are the only ones that can fail an install due to this.  We
6688                // will take care of the system apps by updating all of their
6689                // library paths after the scan is done.
6690                updateSharedLibrariesLPw(pkg, null);
6691            }
6692
6693            if (mFoundPolicyFile) {
6694                SELinuxMMAC.assignSeinfoValue(pkg);
6695            }
6696
6697            pkg.applicationInfo.uid = pkgSetting.appId;
6698            pkg.mExtras = pkgSetting;
6699            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6700                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6701                    // We just determined the app is signed correctly, so bring
6702                    // over the latest parsed certs.
6703                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6704                } else {
6705                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6706                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6707                                "Package " + pkg.packageName + " upgrade keys do not match the "
6708                                + "previously installed version");
6709                    } else {
6710                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6711                        String msg = "System package " + pkg.packageName
6712                            + " signature changed; retaining data.";
6713                        reportSettingsProblem(Log.WARN, msg);
6714                    }
6715                }
6716            } else {
6717                try {
6718                    verifySignaturesLP(pkgSetting, pkg);
6719                    // We just determined the app is signed correctly, so bring
6720                    // over the latest parsed certs.
6721                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6722                } catch (PackageManagerException e) {
6723                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6724                        throw e;
6725                    }
6726                    // The signature has changed, but this package is in the system
6727                    // image...  let's recover!
6728                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6729                    // However...  if this package is part of a shared user, but it
6730                    // doesn't match the signature of the shared user, let's fail.
6731                    // What this means is that you can't change the signatures
6732                    // associated with an overall shared user, which doesn't seem all
6733                    // that unreasonable.
6734                    if (pkgSetting.sharedUser != null) {
6735                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6736                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6737                            throw new PackageManagerException(
6738                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6739                                            "Signature mismatch for shared user : "
6740                                            + pkgSetting.sharedUser);
6741                        }
6742                    }
6743                    // File a report about this.
6744                    String msg = "System package " + pkg.packageName
6745                        + " signature changed; retaining data.";
6746                    reportSettingsProblem(Log.WARN, msg);
6747                }
6748            }
6749            // Verify that this new package doesn't have any content providers
6750            // that conflict with existing packages.  Only do this if the
6751            // package isn't already installed, since we don't want to break
6752            // things that are installed.
6753            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6754                final int N = pkg.providers.size();
6755                int i;
6756                for (i=0; i<N; i++) {
6757                    PackageParser.Provider p = pkg.providers.get(i);
6758                    if (p.info.authority != null) {
6759                        String names[] = p.info.authority.split(";");
6760                        for (int j = 0; j < names.length; j++) {
6761                            if (mProvidersByAuthority.containsKey(names[j])) {
6762                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6763                                final String otherPackageName =
6764                                        ((other != null && other.getComponentName() != null) ?
6765                                                other.getComponentName().getPackageName() : "?");
6766                                throw new PackageManagerException(
6767                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6768                                                "Can't install because provider name " + names[j]
6769                                                + " (in package " + pkg.applicationInfo.packageName
6770                                                + ") is already used by " + otherPackageName);
6771                            }
6772                        }
6773                    }
6774                }
6775            }
6776
6777            if (pkg.mAdoptPermissions != null) {
6778                // This package wants to adopt ownership of permissions from
6779                // another package.
6780                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6781                    final String origName = pkg.mAdoptPermissions.get(i);
6782                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6783                    if (orig != null) {
6784                        if (verifyPackageUpdateLPr(orig, pkg)) {
6785                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6786                                    + pkg.packageName);
6787                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6788                        }
6789                    }
6790                }
6791            }
6792        }
6793
6794        final String pkgName = pkg.packageName;
6795
6796        final long scanFileTime = scanFile.lastModified();
6797        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6798        pkg.applicationInfo.processName = fixProcessName(
6799                pkg.applicationInfo.packageName,
6800                pkg.applicationInfo.processName,
6801                pkg.applicationInfo.uid);
6802
6803        File dataPath;
6804        if (mPlatformPackage == pkg) {
6805            // The system package is special.
6806            dataPath = new File(Environment.getDataDirectory(), "system");
6807
6808            pkg.applicationInfo.dataDir = dataPath.getPath();
6809
6810        } else {
6811            // This is a normal package, need to make its data directory.
6812            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6813                    UserHandle.USER_OWNER, pkg.packageName);
6814
6815            boolean uidError = false;
6816            if (dataPath.exists()) {
6817                int currentUid = 0;
6818                try {
6819                    StructStat stat = Os.stat(dataPath.getPath());
6820                    currentUid = stat.st_uid;
6821                } catch (ErrnoException e) {
6822                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6823                }
6824
6825                // If we have mismatched owners for the data path, we have a problem.
6826                if (currentUid != pkg.applicationInfo.uid) {
6827                    boolean recovered = false;
6828                    if (currentUid == 0) {
6829                        // The directory somehow became owned by root.  Wow.
6830                        // This is probably because the system was stopped while
6831                        // installd was in the middle of messing with its libs
6832                        // directory.  Ask installd to fix that.
6833                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6834                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6835                        if (ret >= 0) {
6836                            recovered = true;
6837                            String msg = "Package " + pkg.packageName
6838                                    + " unexpectedly changed to uid 0; recovered to " +
6839                                    + pkg.applicationInfo.uid;
6840                            reportSettingsProblem(Log.WARN, msg);
6841                        }
6842                    }
6843                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6844                            || (scanFlags&SCAN_BOOTING) != 0)) {
6845                        // If this is a system app, we can at least delete its
6846                        // current data so the application will still work.
6847                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6848                        if (ret >= 0) {
6849                            // TODO: Kill the processes first
6850                            // Old data gone!
6851                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6852                                    ? "System package " : "Third party package ";
6853                            String msg = prefix + pkg.packageName
6854                                    + " has changed from uid: "
6855                                    + currentUid + " to "
6856                                    + pkg.applicationInfo.uid + "; old data erased";
6857                            reportSettingsProblem(Log.WARN, msg);
6858                            recovered = true;
6859
6860                            // And now re-install the app.
6861                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6862                                    pkg.applicationInfo.seinfo);
6863                            if (ret == -1) {
6864                                // Ack should not happen!
6865                                msg = prefix + pkg.packageName
6866                                        + " could not have data directory re-created after delete.";
6867                                reportSettingsProblem(Log.WARN, msg);
6868                                throw new PackageManagerException(
6869                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6870                            }
6871                        }
6872                        if (!recovered) {
6873                            mHasSystemUidErrors = true;
6874                        }
6875                    } else if (!recovered) {
6876                        // If we allow this install to proceed, we will be broken.
6877                        // Abort, abort!
6878                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6879                                "scanPackageLI");
6880                    }
6881                    if (!recovered) {
6882                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6883                            + pkg.applicationInfo.uid + "/fs_"
6884                            + currentUid;
6885                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6886                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6887                        String msg = "Package " + pkg.packageName
6888                                + " has mismatched uid: "
6889                                + currentUid + " on disk, "
6890                                + pkg.applicationInfo.uid + " in settings";
6891                        // writer
6892                        synchronized (mPackages) {
6893                            mSettings.mReadMessages.append(msg);
6894                            mSettings.mReadMessages.append('\n');
6895                            uidError = true;
6896                            if (!pkgSetting.uidError) {
6897                                reportSettingsProblem(Log.ERROR, msg);
6898                            }
6899                        }
6900                    }
6901                }
6902                pkg.applicationInfo.dataDir = dataPath.getPath();
6903                if (mShouldRestoreconData) {
6904                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6905                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6906                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6907                }
6908            } else {
6909                if (DEBUG_PACKAGE_SCANNING) {
6910                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6911                        Log.v(TAG, "Want this data dir: " + dataPath);
6912                }
6913                //invoke installer to do the actual installation
6914                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6915                        pkg.applicationInfo.seinfo);
6916                if (ret < 0) {
6917                    // Error from installer
6918                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6919                            "Unable to create data dirs [errorCode=" + ret + "]");
6920                }
6921
6922                if (dataPath.exists()) {
6923                    pkg.applicationInfo.dataDir = dataPath.getPath();
6924                } else {
6925                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6926                    pkg.applicationInfo.dataDir = null;
6927                }
6928            }
6929
6930            pkgSetting.uidError = uidError;
6931        }
6932
6933        final String path = scanFile.getPath();
6934        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6935
6936        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6937            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6938
6939            // Some system apps still use directory structure for native libraries
6940            // in which case we might end up not detecting abi solely based on apk
6941            // structure. Try to detect abi based on directory structure.
6942            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6943                    pkg.applicationInfo.primaryCpuAbi == null) {
6944                setBundledAppAbisAndRoots(pkg, pkgSetting);
6945                setNativeLibraryPaths(pkg);
6946            }
6947
6948        } else {
6949            if ((scanFlags & SCAN_MOVE) != 0) {
6950                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6951                // but we already have this packages package info in the PackageSetting. We just
6952                // use that and derive the native library path based on the new codepath.
6953                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6954                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6955            }
6956
6957            // Set native library paths again. For moves, the path will be updated based on the
6958            // ABIs we've determined above. For non-moves, the path will be updated based on the
6959            // ABIs we determined during compilation, but the path will depend on the final
6960            // package path (after the rename away from the stage path).
6961            setNativeLibraryPaths(pkg);
6962        }
6963
6964        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6965        final int[] userIds = sUserManager.getUserIds();
6966        synchronized (mInstallLock) {
6967            // Make sure all user data directories are ready to roll; we're okay
6968            // if they already exist
6969            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6970                for (int userId : userIds) {
6971                    if (userId != 0) {
6972                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6973                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6974                                pkg.applicationInfo.seinfo);
6975                    }
6976                }
6977            }
6978
6979            // Create a native library symlink only if we have native libraries
6980            // and if the native libraries are 32 bit libraries. We do not provide
6981            // this symlink for 64 bit libraries.
6982            if (pkg.applicationInfo.primaryCpuAbi != null &&
6983                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6984                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6985                for (int userId : userIds) {
6986                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6987                            nativeLibPath, userId) < 0) {
6988                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6989                                "Failed linking native library dir (user=" + userId + ")");
6990                    }
6991                }
6992            }
6993        }
6994
6995        // This is a special case for the "system" package, where the ABI is
6996        // dictated by the zygote configuration (and init.rc). We should keep track
6997        // of this ABI so that we can deal with "normal" applications that run under
6998        // the same UID correctly.
6999        if (mPlatformPackage == pkg) {
7000            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7001                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7002        }
7003
7004        // If there's a mismatch between the abi-override in the package setting
7005        // and the abiOverride specified for the install. Warn about this because we
7006        // would've already compiled the app without taking the package setting into
7007        // account.
7008        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7009            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7010                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7011                        " for package: " + pkg.packageName);
7012            }
7013        }
7014
7015        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7016        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7017        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7018
7019        // Copy the derived override back to the parsed package, so that we can
7020        // update the package settings accordingly.
7021        pkg.cpuAbiOverride = cpuAbiOverride;
7022
7023        if (DEBUG_ABI_SELECTION) {
7024            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7025                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7026                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7027        }
7028
7029        // Push the derived path down into PackageSettings so we know what to
7030        // clean up at uninstall time.
7031        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7032
7033        if (DEBUG_ABI_SELECTION) {
7034            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7035                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7036                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7037        }
7038
7039        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7040            // We don't do this here during boot because we can do it all
7041            // at once after scanning all existing packages.
7042            //
7043            // We also do this *before* we perform dexopt on this package, so that
7044            // we can avoid redundant dexopts, and also to make sure we've got the
7045            // code and package path correct.
7046            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7047                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7048        }
7049
7050        if ((scanFlags & SCAN_NO_DEX) == 0) {
7051            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7052                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7053            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7054                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7055            }
7056        }
7057        if (mFactoryTest && pkg.requestedPermissions.contains(
7058                android.Manifest.permission.FACTORY_TEST)) {
7059            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7060        }
7061
7062        ArrayList<PackageParser.Package> clientLibPkgs = null;
7063
7064        // writer
7065        synchronized (mPackages) {
7066            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7067                // Only system apps can add new shared libraries.
7068                if (pkg.libraryNames != null) {
7069                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7070                        String name = pkg.libraryNames.get(i);
7071                        boolean allowed = false;
7072                        if (pkg.isUpdatedSystemApp()) {
7073                            // New library entries can only be added through the
7074                            // system image.  This is important to get rid of a lot
7075                            // of nasty edge cases: for example if we allowed a non-
7076                            // system update of the app to add a library, then uninstalling
7077                            // the update would make the library go away, and assumptions
7078                            // we made such as through app install filtering would now
7079                            // have allowed apps on the device which aren't compatible
7080                            // with it.  Better to just have the restriction here, be
7081                            // conservative, and create many fewer cases that can negatively
7082                            // impact the user experience.
7083                            final PackageSetting sysPs = mSettings
7084                                    .getDisabledSystemPkgLPr(pkg.packageName);
7085                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7086                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7087                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7088                                        allowed = true;
7089                                        allowed = true;
7090                                        break;
7091                                    }
7092                                }
7093                            }
7094                        } else {
7095                            allowed = true;
7096                        }
7097                        if (allowed) {
7098                            if (!mSharedLibraries.containsKey(name)) {
7099                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7100                            } else if (!name.equals(pkg.packageName)) {
7101                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7102                                        + name + " already exists; skipping");
7103                            }
7104                        } else {
7105                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7106                                    + name + " that is not declared on system image; skipping");
7107                        }
7108                    }
7109                    if ((scanFlags&SCAN_BOOTING) == 0) {
7110                        // If we are not booting, we need to update any applications
7111                        // that are clients of our shared library.  If we are booting,
7112                        // this will all be done once the scan is complete.
7113                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7114                    }
7115                }
7116            }
7117        }
7118
7119        // We also need to dexopt any apps that are dependent on this library.  Note that
7120        // if these fail, we should abort the install since installing the library will
7121        // result in some apps being broken.
7122        if (clientLibPkgs != null) {
7123            if ((scanFlags & SCAN_NO_DEX) == 0) {
7124                for (int i = 0; i < clientLibPkgs.size(); i++) {
7125                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7126                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7127                            null /* instruction sets */, forceDex,
7128                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7129                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7130                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7131                                "scanPackageLI failed to dexopt clientLibPkgs");
7132                    }
7133                }
7134            }
7135        }
7136
7137        // Request the ActivityManager to kill the process(only for existing packages)
7138        // so that we do not end up in a confused state while the user is still using the older
7139        // version of the application while the new one gets installed.
7140        if ((scanFlags & SCAN_REPLACING) != 0) {
7141            killApplication(pkg.applicationInfo.packageName,
7142                        pkg.applicationInfo.uid, "replace pkg");
7143        }
7144
7145        // Also need to kill any apps that are dependent on the library.
7146        if (clientLibPkgs != null) {
7147            for (int i=0; i<clientLibPkgs.size(); i++) {
7148                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7149                killApplication(clientPkg.applicationInfo.packageName,
7150                        clientPkg.applicationInfo.uid, "update lib");
7151            }
7152        }
7153
7154        // Make sure we're not adding any bogus keyset info
7155        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7156        ksms.assertScannedPackageValid(pkg);
7157
7158        // writer
7159        synchronized (mPackages) {
7160            // We don't expect installation to fail beyond this point
7161
7162            // Add the new setting to mSettings
7163            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7164            // Add the new setting to mPackages
7165            mPackages.put(pkg.applicationInfo.packageName, pkg);
7166            // Make sure we don't accidentally delete its data.
7167            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7168            while (iter.hasNext()) {
7169                PackageCleanItem item = iter.next();
7170                if (pkgName.equals(item.packageName)) {
7171                    iter.remove();
7172                }
7173            }
7174
7175            // Take care of first install / last update times.
7176            if (currentTime != 0) {
7177                if (pkgSetting.firstInstallTime == 0) {
7178                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7179                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7180                    pkgSetting.lastUpdateTime = currentTime;
7181                }
7182            } else if (pkgSetting.firstInstallTime == 0) {
7183                // We need *something*.  Take time time stamp of the file.
7184                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7185            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7186                if (scanFileTime != pkgSetting.timeStamp) {
7187                    // A package on the system image has changed; consider this
7188                    // to be an update.
7189                    pkgSetting.lastUpdateTime = scanFileTime;
7190                }
7191            }
7192
7193            // Add the package's KeySets to the global KeySetManagerService
7194            ksms.addScannedPackageLPw(pkg);
7195
7196            int N = pkg.providers.size();
7197            StringBuilder r = null;
7198            int i;
7199            for (i=0; i<N; i++) {
7200                PackageParser.Provider p = pkg.providers.get(i);
7201                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7202                        p.info.processName, pkg.applicationInfo.uid);
7203                mProviders.addProvider(p);
7204                p.syncable = p.info.isSyncable;
7205                if (p.info.authority != null) {
7206                    String names[] = p.info.authority.split(";");
7207                    p.info.authority = null;
7208                    for (int j = 0; j < names.length; j++) {
7209                        if (j == 1 && p.syncable) {
7210                            // We only want the first authority for a provider to possibly be
7211                            // syncable, so if we already added this provider using a different
7212                            // authority clear the syncable flag. We copy the provider before
7213                            // changing it because the mProviders object contains a reference
7214                            // to a provider that we don't want to change.
7215                            // Only do this for the second authority since the resulting provider
7216                            // object can be the same for all future authorities for this provider.
7217                            p = new PackageParser.Provider(p);
7218                            p.syncable = false;
7219                        }
7220                        if (!mProvidersByAuthority.containsKey(names[j])) {
7221                            mProvidersByAuthority.put(names[j], p);
7222                            if (p.info.authority == null) {
7223                                p.info.authority = names[j];
7224                            } else {
7225                                p.info.authority = p.info.authority + ";" + names[j];
7226                            }
7227                            if (DEBUG_PACKAGE_SCANNING) {
7228                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7229                                    Log.d(TAG, "Registered content provider: " + names[j]
7230                                            + ", className = " + p.info.name + ", isSyncable = "
7231                                            + p.info.isSyncable);
7232                            }
7233                        } else {
7234                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7235                            Slog.w(TAG, "Skipping provider name " + names[j] +
7236                                    " (in package " + pkg.applicationInfo.packageName +
7237                                    "): name already used by "
7238                                    + ((other != null && other.getComponentName() != null)
7239                                            ? other.getComponentName().getPackageName() : "?"));
7240                        }
7241                    }
7242                }
7243                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7244                    if (r == null) {
7245                        r = new StringBuilder(256);
7246                    } else {
7247                        r.append(' ');
7248                    }
7249                    r.append(p.info.name);
7250                }
7251            }
7252            if (r != null) {
7253                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7254            }
7255
7256            N = pkg.services.size();
7257            r = null;
7258            for (i=0; i<N; i++) {
7259                PackageParser.Service s = pkg.services.get(i);
7260                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7261                        s.info.processName, pkg.applicationInfo.uid);
7262                mServices.addService(s);
7263                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7264                    if (r == null) {
7265                        r = new StringBuilder(256);
7266                    } else {
7267                        r.append(' ');
7268                    }
7269                    r.append(s.info.name);
7270                }
7271            }
7272            if (r != null) {
7273                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7274            }
7275
7276            N = pkg.receivers.size();
7277            r = null;
7278            for (i=0; i<N; i++) {
7279                PackageParser.Activity a = pkg.receivers.get(i);
7280                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7281                        a.info.processName, pkg.applicationInfo.uid);
7282                mReceivers.addActivity(a, "receiver");
7283                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7284                    if (r == null) {
7285                        r = new StringBuilder(256);
7286                    } else {
7287                        r.append(' ');
7288                    }
7289                    r.append(a.info.name);
7290                }
7291            }
7292            if (r != null) {
7293                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7294            }
7295
7296            N = pkg.activities.size();
7297            r = null;
7298            for (i=0; i<N; i++) {
7299                PackageParser.Activity a = pkg.activities.get(i);
7300                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7301                        a.info.processName, pkg.applicationInfo.uid);
7302                mActivities.addActivity(a, "activity");
7303                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7304                    if (r == null) {
7305                        r = new StringBuilder(256);
7306                    } else {
7307                        r.append(' ');
7308                    }
7309                    r.append(a.info.name);
7310                }
7311            }
7312            if (r != null) {
7313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7314            }
7315
7316            N = pkg.permissionGroups.size();
7317            r = null;
7318            for (i=0; i<N; i++) {
7319                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7320                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7321                if (cur == null) {
7322                    mPermissionGroups.put(pg.info.name, pg);
7323                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7324                        if (r == null) {
7325                            r = new StringBuilder(256);
7326                        } else {
7327                            r.append(' ');
7328                        }
7329                        r.append(pg.info.name);
7330                    }
7331                } else {
7332                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7333                            + pg.info.packageName + " ignored: original from "
7334                            + cur.info.packageName);
7335                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7336                        if (r == null) {
7337                            r = new StringBuilder(256);
7338                        } else {
7339                            r.append(' ');
7340                        }
7341                        r.append("DUP:");
7342                        r.append(pg.info.name);
7343                    }
7344                }
7345            }
7346            if (r != null) {
7347                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7348            }
7349
7350            N = pkg.permissions.size();
7351            r = null;
7352            for (i=0; i<N; i++) {
7353                PackageParser.Permission p = pkg.permissions.get(i);
7354
7355                // Assume by default that we did not install this permission into the system.
7356                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7357
7358                // Now that permission groups have a special meaning, we ignore permission
7359                // groups for legacy apps to prevent unexpected behavior. In particular,
7360                // permissions for one app being granted to someone just becuase they happen
7361                // to be in a group defined by another app (before this had no implications).
7362                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7363                    p.group = mPermissionGroups.get(p.info.group);
7364                    // Warn for a permission in an unknown group.
7365                    if (p.info.group != null && p.group == null) {
7366                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7367                                + p.info.packageName + " in an unknown group " + p.info.group);
7368                    }
7369                }
7370
7371                ArrayMap<String, BasePermission> permissionMap =
7372                        p.tree ? mSettings.mPermissionTrees
7373                                : mSettings.mPermissions;
7374                BasePermission bp = permissionMap.get(p.info.name);
7375
7376                // Allow system apps to redefine non-system permissions
7377                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7378                    final boolean currentOwnerIsSystem = (bp.perm != null
7379                            && isSystemApp(bp.perm.owner));
7380                    if (isSystemApp(p.owner)) {
7381                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7382                            // It's a built-in permission and no owner, take ownership now
7383                            bp.packageSetting = pkgSetting;
7384                            bp.perm = p;
7385                            bp.uid = pkg.applicationInfo.uid;
7386                            bp.sourcePackage = p.info.packageName;
7387                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7388                        } else if (!currentOwnerIsSystem) {
7389                            String msg = "New decl " + p.owner + " of permission  "
7390                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7391                            reportSettingsProblem(Log.WARN, msg);
7392                            bp = null;
7393                        }
7394                    }
7395                }
7396
7397                if (bp == null) {
7398                    bp = new BasePermission(p.info.name, p.info.packageName,
7399                            BasePermission.TYPE_NORMAL);
7400                    permissionMap.put(p.info.name, bp);
7401                }
7402
7403                if (bp.perm == null) {
7404                    if (bp.sourcePackage == null
7405                            || bp.sourcePackage.equals(p.info.packageName)) {
7406                        BasePermission tree = findPermissionTreeLP(p.info.name);
7407                        if (tree == null
7408                                || tree.sourcePackage.equals(p.info.packageName)) {
7409                            bp.packageSetting = pkgSetting;
7410                            bp.perm = p;
7411                            bp.uid = pkg.applicationInfo.uid;
7412                            bp.sourcePackage = p.info.packageName;
7413                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7414                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7415                                if (r == null) {
7416                                    r = new StringBuilder(256);
7417                                } else {
7418                                    r.append(' ');
7419                                }
7420                                r.append(p.info.name);
7421                            }
7422                        } else {
7423                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7424                                    + p.info.packageName + " ignored: base tree "
7425                                    + tree.name + " is from package "
7426                                    + tree.sourcePackage);
7427                        }
7428                    } else {
7429                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7430                                + p.info.packageName + " ignored: original from "
7431                                + bp.sourcePackage);
7432                    }
7433                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7434                    if (r == null) {
7435                        r = new StringBuilder(256);
7436                    } else {
7437                        r.append(' ');
7438                    }
7439                    r.append("DUP:");
7440                    r.append(p.info.name);
7441                }
7442                if (bp.perm == p) {
7443                    bp.protectionLevel = p.info.protectionLevel;
7444                }
7445            }
7446
7447            if (r != null) {
7448                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7449            }
7450
7451            N = pkg.instrumentation.size();
7452            r = null;
7453            for (i=0; i<N; i++) {
7454                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7455                a.info.packageName = pkg.applicationInfo.packageName;
7456                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7457                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7458                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7459                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7460                a.info.dataDir = pkg.applicationInfo.dataDir;
7461
7462                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7463                // need other information about the application, like the ABI and what not ?
7464                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7465                mInstrumentation.put(a.getComponentName(), a);
7466                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7467                    if (r == null) {
7468                        r = new StringBuilder(256);
7469                    } else {
7470                        r.append(' ');
7471                    }
7472                    r.append(a.info.name);
7473                }
7474            }
7475            if (r != null) {
7476                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7477            }
7478
7479            if (pkg.protectedBroadcasts != null) {
7480                N = pkg.protectedBroadcasts.size();
7481                for (i=0; i<N; i++) {
7482                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7483                }
7484            }
7485
7486            pkgSetting.setTimeStamp(scanFileTime);
7487
7488            // Create idmap files for pairs of (packages, overlay packages).
7489            // Note: "android", ie framework-res.apk, is handled by native layers.
7490            if (pkg.mOverlayTarget != null) {
7491                // This is an overlay package.
7492                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7493                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7494                        mOverlays.put(pkg.mOverlayTarget,
7495                                new ArrayMap<String, PackageParser.Package>());
7496                    }
7497                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7498                    map.put(pkg.packageName, pkg);
7499                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7500                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7501                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7502                                "scanPackageLI failed to createIdmap");
7503                    }
7504                }
7505            } else if (mOverlays.containsKey(pkg.packageName) &&
7506                    !pkg.packageName.equals("android")) {
7507                // This is a regular package, with one or more known overlay packages.
7508                createIdmapsForPackageLI(pkg);
7509            }
7510        }
7511
7512        return pkg;
7513    }
7514
7515    /**
7516     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7517     * is derived purely on the basis of the contents of {@code scanFile} and
7518     * {@code cpuAbiOverride}.
7519     *
7520     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7521     */
7522    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7523                                 String cpuAbiOverride, boolean extractLibs)
7524            throws PackageManagerException {
7525        // TODO: We can probably be smarter about this stuff. For installed apps,
7526        // we can calculate this information at install time once and for all. For
7527        // system apps, we can probably assume that this information doesn't change
7528        // after the first boot scan. As things stand, we do lots of unnecessary work.
7529
7530        // Give ourselves some initial paths; we'll come back for another
7531        // pass once we've determined ABI below.
7532        setNativeLibraryPaths(pkg);
7533
7534        // We would never need to extract libs for forward-locked and external packages,
7535        // since the container service will do it for us. We shouldn't attempt to
7536        // extract libs from system app when it was not updated.
7537        if (pkg.isForwardLocked() || isExternal(pkg) ||
7538            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7539            extractLibs = false;
7540        }
7541
7542        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7543        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7544
7545        NativeLibraryHelper.Handle handle = null;
7546        try {
7547            handle = NativeLibraryHelper.Handle.create(scanFile);
7548            // TODO(multiArch): This can be null for apps that didn't go through the
7549            // usual installation process. We can calculate it again, like we
7550            // do during install time.
7551            //
7552            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7553            // unnecessary.
7554            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7555
7556            // Null out the abis so that they can be recalculated.
7557            pkg.applicationInfo.primaryCpuAbi = null;
7558            pkg.applicationInfo.secondaryCpuAbi = null;
7559            if (isMultiArch(pkg.applicationInfo)) {
7560                // Warn if we've set an abiOverride for multi-lib packages..
7561                // By definition, we need to copy both 32 and 64 bit libraries for
7562                // such packages.
7563                if (pkg.cpuAbiOverride != null
7564                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7565                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7566                }
7567
7568                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7569                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7570                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7571                    if (extractLibs) {
7572                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7573                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7574                                useIsaSpecificSubdirs);
7575                    } else {
7576                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7577                    }
7578                }
7579
7580                maybeThrowExceptionForMultiArchCopy(
7581                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7582
7583                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7584                    if (extractLibs) {
7585                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7586                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7587                                useIsaSpecificSubdirs);
7588                    } else {
7589                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7590                    }
7591                }
7592
7593                maybeThrowExceptionForMultiArchCopy(
7594                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7595
7596                if (abi64 >= 0) {
7597                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7598                }
7599
7600                if (abi32 >= 0) {
7601                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7602                    if (abi64 >= 0) {
7603                        pkg.applicationInfo.secondaryCpuAbi = abi;
7604                    } else {
7605                        pkg.applicationInfo.primaryCpuAbi = abi;
7606                    }
7607                }
7608            } else {
7609                String[] abiList = (cpuAbiOverride != null) ?
7610                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7611
7612                // Enable gross and lame hacks for apps that are built with old
7613                // SDK tools. We must scan their APKs for renderscript bitcode and
7614                // not launch them if it's present. Don't bother checking on devices
7615                // that don't have 64 bit support.
7616                boolean needsRenderScriptOverride = false;
7617                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7618                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7619                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7620                    needsRenderScriptOverride = true;
7621                }
7622
7623                final int copyRet;
7624                if (extractLibs) {
7625                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7626                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7627                } else {
7628                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7629                }
7630
7631                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7632                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7633                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7634                }
7635
7636                if (copyRet >= 0) {
7637                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7638                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7639                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7640                } else if (needsRenderScriptOverride) {
7641                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7642                }
7643            }
7644        } catch (IOException ioe) {
7645            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7646        } finally {
7647            IoUtils.closeQuietly(handle);
7648        }
7649
7650        // Now that we've calculated the ABIs and determined if it's an internal app,
7651        // we will go ahead and populate the nativeLibraryPath.
7652        setNativeLibraryPaths(pkg);
7653    }
7654
7655    /**
7656     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7657     * i.e, so that all packages can be run inside a single process if required.
7658     *
7659     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7660     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7661     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7662     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7663     * updating a package that belongs to a shared user.
7664     *
7665     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7666     * adds unnecessary complexity.
7667     */
7668    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7669            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7670        String requiredInstructionSet = null;
7671        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7672            requiredInstructionSet = VMRuntime.getInstructionSet(
7673                     scannedPackage.applicationInfo.primaryCpuAbi);
7674        }
7675
7676        PackageSetting requirer = null;
7677        for (PackageSetting ps : packagesForUser) {
7678            // If packagesForUser contains scannedPackage, we skip it. This will happen
7679            // when scannedPackage is an update of an existing package. Without this check,
7680            // we will never be able to change the ABI of any package belonging to a shared
7681            // user, even if it's compatible with other packages.
7682            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7683                if (ps.primaryCpuAbiString == null) {
7684                    continue;
7685                }
7686
7687                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7688                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7689                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7690                    // this but there's not much we can do.
7691                    String errorMessage = "Instruction set mismatch, "
7692                            + ((requirer == null) ? "[caller]" : requirer)
7693                            + " requires " + requiredInstructionSet + " whereas " + ps
7694                            + " requires " + instructionSet;
7695                    Slog.w(TAG, errorMessage);
7696                }
7697
7698                if (requiredInstructionSet == null) {
7699                    requiredInstructionSet = instructionSet;
7700                    requirer = ps;
7701                }
7702            }
7703        }
7704
7705        if (requiredInstructionSet != null) {
7706            String adjustedAbi;
7707            if (requirer != null) {
7708                // requirer != null implies that either scannedPackage was null or that scannedPackage
7709                // did not require an ABI, in which case we have to adjust scannedPackage to match
7710                // the ABI of the set (which is the same as requirer's ABI)
7711                adjustedAbi = requirer.primaryCpuAbiString;
7712                if (scannedPackage != null) {
7713                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7714                }
7715            } else {
7716                // requirer == null implies that we're updating all ABIs in the set to
7717                // match scannedPackage.
7718                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7719            }
7720
7721            for (PackageSetting ps : packagesForUser) {
7722                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7723                    if (ps.primaryCpuAbiString != null) {
7724                        continue;
7725                    }
7726
7727                    ps.primaryCpuAbiString = adjustedAbi;
7728                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7729                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7730                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7731
7732                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7733                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7734                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7735                            ps.primaryCpuAbiString = null;
7736                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7737                            return;
7738                        } else {
7739                            mInstaller.rmdex(ps.codePathString,
7740                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7741                        }
7742                    }
7743                }
7744            }
7745        }
7746    }
7747
7748    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7749        synchronized (mPackages) {
7750            mResolverReplaced = true;
7751            // Set up information for custom user intent resolution activity.
7752            mResolveActivity.applicationInfo = pkg.applicationInfo;
7753            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7754            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7755            mResolveActivity.processName = pkg.applicationInfo.packageName;
7756            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7757            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7758                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7759            mResolveActivity.theme = 0;
7760            mResolveActivity.exported = true;
7761            mResolveActivity.enabled = true;
7762            mResolveInfo.activityInfo = mResolveActivity;
7763            mResolveInfo.priority = 0;
7764            mResolveInfo.preferredOrder = 0;
7765            mResolveInfo.match = 0;
7766            mResolveComponentName = mCustomResolverComponentName;
7767            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7768                    mResolveComponentName);
7769        }
7770    }
7771
7772    private static String calculateBundledApkRoot(final String codePathString) {
7773        final File codePath = new File(codePathString);
7774        final File codeRoot;
7775        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7776            codeRoot = Environment.getRootDirectory();
7777        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7778            codeRoot = Environment.getOemDirectory();
7779        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7780            codeRoot = Environment.getVendorDirectory();
7781        } else {
7782            // Unrecognized code path; take its top real segment as the apk root:
7783            // e.g. /something/app/blah.apk => /something
7784            try {
7785                File f = codePath.getCanonicalFile();
7786                File parent = f.getParentFile();    // non-null because codePath is a file
7787                File tmp;
7788                while ((tmp = parent.getParentFile()) != null) {
7789                    f = parent;
7790                    parent = tmp;
7791                }
7792                codeRoot = f;
7793                Slog.w(TAG, "Unrecognized code path "
7794                        + codePath + " - using " + codeRoot);
7795            } catch (IOException e) {
7796                // Can't canonicalize the code path -- shenanigans?
7797                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7798                return Environment.getRootDirectory().getPath();
7799            }
7800        }
7801        return codeRoot.getPath();
7802    }
7803
7804    /**
7805     * Derive and set the location of native libraries for the given package,
7806     * which varies depending on where and how the package was installed.
7807     */
7808    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7809        final ApplicationInfo info = pkg.applicationInfo;
7810        final String codePath = pkg.codePath;
7811        final File codeFile = new File(codePath);
7812        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7813        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7814
7815        info.nativeLibraryRootDir = null;
7816        info.nativeLibraryRootRequiresIsa = false;
7817        info.nativeLibraryDir = null;
7818        info.secondaryNativeLibraryDir = null;
7819
7820        if (isApkFile(codeFile)) {
7821            // Monolithic install
7822            if (bundledApp) {
7823                // If "/system/lib64/apkname" exists, assume that is the per-package
7824                // native library directory to use; otherwise use "/system/lib/apkname".
7825                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7826                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7827                        getPrimaryInstructionSet(info));
7828
7829                // This is a bundled system app so choose the path based on the ABI.
7830                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7831                // is just the default path.
7832                final String apkName = deriveCodePathName(codePath);
7833                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7834                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7835                        apkName).getAbsolutePath();
7836
7837                if (info.secondaryCpuAbi != null) {
7838                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7839                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7840                            secondaryLibDir, apkName).getAbsolutePath();
7841                }
7842            } else if (asecApp) {
7843                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7844                        .getAbsolutePath();
7845            } else {
7846                final String apkName = deriveCodePathName(codePath);
7847                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7848                        .getAbsolutePath();
7849            }
7850
7851            info.nativeLibraryRootRequiresIsa = false;
7852            info.nativeLibraryDir = info.nativeLibraryRootDir;
7853        } else {
7854            // Cluster install
7855            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7856            info.nativeLibraryRootRequiresIsa = true;
7857
7858            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7859                    getPrimaryInstructionSet(info)).getAbsolutePath();
7860
7861            if (info.secondaryCpuAbi != null) {
7862                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7863                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7864            }
7865        }
7866    }
7867
7868    /**
7869     * Calculate the abis and roots for a bundled app. These can uniquely
7870     * be determined from the contents of the system partition, i.e whether
7871     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7872     * of this information, and instead assume that the system was built
7873     * sensibly.
7874     */
7875    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7876                                           PackageSetting pkgSetting) {
7877        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7878
7879        // If "/system/lib64/apkname" exists, assume that is the per-package
7880        // native library directory to use; otherwise use "/system/lib/apkname".
7881        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7882        setBundledAppAbi(pkg, apkRoot, apkName);
7883        // pkgSetting might be null during rescan following uninstall of updates
7884        // to a bundled app, so accommodate that possibility.  The settings in
7885        // that case will be established later from the parsed package.
7886        //
7887        // If the settings aren't null, sync them up with what we've just derived.
7888        // note that apkRoot isn't stored in the package settings.
7889        if (pkgSetting != null) {
7890            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7891            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7892        }
7893    }
7894
7895    /**
7896     * Deduces the ABI of a bundled app and sets the relevant fields on the
7897     * parsed pkg object.
7898     *
7899     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7900     *        under which system libraries are installed.
7901     * @param apkName the name of the installed package.
7902     */
7903    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7904        final File codeFile = new File(pkg.codePath);
7905
7906        final boolean has64BitLibs;
7907        final boolean has32BitLibs;
7908        if (isApkFile(codeFile)) {
7909            // Monolithic install
7910            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7911            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7912        } else {
7913            // Cluster install
7914            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7915            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7916                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7917                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7918                has64BitLibs = (new File(rootDir, isa)).exists();
7919            } else {
7920                has64BitLibs = false;
7921            }
7922            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7923                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7924                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7925                has32BitLibs = (new File(rootDir, isa)).exists();
7926            } else {
7927                has32BitLibs = false;
7928            }
7929        }
7930
7931        if (has64BitLibs && !has32BitLibs) {
7932            // The package has 64 bit libs, but not 32 bit libs. Its primary
7933            // ABI should be 64 bit. We can safely assume here that the bundled
7934            // native libraries correspond to the most preferred ABI in the list.
7935
7936            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7937            pkg.applicationInfo.secondaryCpuAbi = null;
7938        } else if (has32BitLibs && !has64BitLibs) {
7939            // The package has 32 bit libs but not 64 bit libs. Its primary
7940            // ABI should be 32 bit.
7941
7942            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7943            pkg.applicationInfo.secondaryCpuAbi = null;
7944        } else if (has32BitLibs && has64BitLibs) {
7945            // The application has both 64 and 32 bit bundled libraries. We check
7946            // here that the app declares multiArch support, and warn if it doesn't.
7947            //
7948            // We will be lenient here and record both ABIs. The primary will be the
7949            // ABI that's higher on the list, i.e, a device that's configured to prefer
7950            // 64 bit apps will see a 64 bit primary ABI,
7951
7952            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7953                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7954            }
7955
7956            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7957                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7958                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7959            } else {
7960                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7961                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7962            }
7963        } else {
7964            pkg.applicationInfo.primaryCpuAbi = null;
7965            pkg.applicationInfo.secondaryCpuAbi = null;
7966        }
7967    }
7968
7969    private void killApplication(String pkgName, int appId, String reason) {
7970        // Request the ActivityManager to kill the process(only for existing packages)
7971        // so that we do not end up in a confused state while the user is still using the older
7972        // version of the application while the new one gets installed.
7973        IActivityManager am = ActivityManagerNative.getDefault();
7974        if (am != null) {
7975            try {
7976                am.killApplicationWithAppId(pkgName, appId, reason);
7977            } catch (RemoteException e) {
7978            }
7979        }
7980    }
7981
7982    void removePackageLI(PackageSetting ps, boolean chatty) {
7983        if (DEBUG_INSTALL) {
7984            if (chatty)
7985                Log.d(TAG, "Removing package " + ps.name);
7986        }
7987
7988        // writer
7989        synchronized (mPackages) {
7990            mPackages.remove(ps.name);
7991            final PackageParser.Package pkg = ps.pkg;
7992            if (pkg != null) {
7993                cleanPackageDataStructuresLILPw(pkg, chatty);
7994            }
7995        }
7996    }
7997
7998    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7999        if (DEBUG_INSTALL) {
8000            if (chatty)
8001                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8002        }
8003
8004        // writer
8005        synchronized (mPackages) {
8006            mPackages.remove(pkg.applicationInfo.packageName);
8007            cleanPackageDataStructuresLILPw(pkg, chatty);
8008        }
8009    }
8010
8011    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8012        int N = pkg.providers.size();
8013        StringBuilder r = null;
8014        int i;
8015        for (i=0; i<N; i++) {
8016            PackageParser.Provider p = pkg.providers.get(i);
8017            mProviders.removeProvider(p);
8018            if (p.info.authority == null) {
8019
8020                /* There was another ContentProvider with this authority when
8021                 * this app was installed so this authority is null,
8022                 * Ignore it as we don't have to unregister the provider.
8023                 */
8024                continue;
8025            }
8026            String names[] = p.info.authority.split(";");
8027            for (int j = 0; j < names.length; j++) {
8028                if (mProvidersByAuthority.get(names[j]) == p) {
8029                    mProvidersByAuthority.remove(names[j]);
8030                    if (DEBUG_REMOVE) {
8031                        if (chatty)
8032                            Log.d(TAG, "Unregistered content provider: " + names[j]
8033                                    + ", className = " + p.info.name + ", isSyncable = "
8034                                    + p.info.isSyncable);
8035                    }
8036                }
8037            }
8038            if (DEBUG_REMOVE && chatty) {
8039                if (r == null) {
8040                    r = new StringBuilder(256);
8041                } else {
8042                    r.append(' ');
8043                }
8044                r.append(p.info.name);
8045            }
8046        }
8047        if (r != null) {
8048            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8049        }
8050
8051        N = pkg.services.size();
8052        r = null;
8053        for (i=0; i<N; i++) {
8054            PackageParser.Service s = pkg.services.get(i);
8055            mServices.removeService(s);
8056            if (chatty) {
8057                if (r == null) {
8058                    r = new StringBuilder(256);
8059                } else {
8060                    r.append(' ');
8061                }
8062                r.append(s.info.name);
8063            }
8064        }
8065        if (r != null) {
8066            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8067        }
8068
8069        N = pkg.receivers.size();
8070        r = null;
8071        for (i=0; i<N; i++) {
8072            PackageParser.Activity a = pkg.receivers.get(i);
8073            mReceivers.removeActivity(a, "receiver");
8074            if (DEBUG_REMOVE && chatty) {
8075                if (r == null) {
8076                    r = new StringBuilder(256);
8077                } else {
8078                    r.append(' ');
8079                }
8080                r.append(a.info.name);
8081            }
8082        }
8083        if (r != null) {
8084            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8085        }
8086
8087        N = pkg.activities.size();
8088        r = null;
8089        for (i=0; i<N; i++) {
8090            PackageParser.Activity a = pkg.activities.get(i);
8091            mActivities.removeActivity(a, "activity");
8092            if (DEBUG_REMOVE && chatty) {
8093                if (r == null) {
8094                    r = new StringBuilder(256);
8095                } else {
8096                    r.append(' ');
8097                }
8098                r.append(a.info.name);
8099            }
8100        }
8101        if (r != null) {
8102            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8103        }
8104
8105        N = pkg.permissions.size();
8106        r = null;
8107        for (i=0; i<N; i++) {
8108            PackageParser.Permission p = pkg.permissions.get(i);
8109            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8110            if (bp == null) {
8111                bp = mSettings.mPermissionTrees.get(p.info.name);
8112            }
8113            if (bp != null && bp.perm == p) {
8114                bp.perm = null;
8115                if (DEBUG_REMOVE && chatty) {
8116                    if (r == null) {
8117                        r = new StringBuilder(256);
8118                    } else {
8119                        r.append(' ');
8120                    }
8121                    r.append(p.info.name);
8122                }
8123            }
8124            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8125                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8126                if (appOpPerms != null) {
8127                    appOpPerms.remove(pkg.packageName);
8128                }
8129            }
8130        }
8131        if (r != null) {
8132            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8133        }
8134
8135        N = pkg.requestedPermissions.size();
8136        r = null;
8137        for (i=0; i<N; i++) {
8138            String perm = pkg.requestedPermissions.get(i);
8139            BasePermission bp = mSettings.mPermissions.get(perm);
8140            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8141                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8142                if (appOpPerms != null) {
8143                    appOpPerms.remove(pkg.packageName);
8144                    if (appOpPerms.isEmpty()) {
8145                        mAppOpPermissionPackages.remove(perm);
8146                    }
8147                }
8148            }
8149        }
8150        if (r != null) {
8151            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8152        }
8153
8154        N = pkg.instrumentation.size();
8155        r = null;
8156        for (i=0; i<N; i++) {
8157            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8158            mInstrumentation.remove(a.getComponentName());
8159            if (DEBUG_REMOVE && chatty) {
8160                if (r == null) {
8161                    r = new StringBuilder(256);
8162                } else {
8163                    r.append(' ');
8164                }
8165                r.append(a.info.name);
8166            }
8167        }
8168        if (r != null) {
8169            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8170        }
8171
8172        r = null;
8173        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8174            // Only system apps can hold shared libraries.
8175            if (pkg.libraryNames != null) {
8176                for (i=0; i<pkg.libraryNames.size(); i++) {
8177                    String name = pkg.libraryNames.get(i);
8178                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8179                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8180                        mSharedLibraries.remove(name);
8181                        if (DEBUG_REMOVE && chatty) {
8182                            if (r == null) {
8183                                r = new StringBuilder(256);
8184                            } else {
8185                                r.append(' ');
8186                            }
8187                            r.append(name);
8188                        }
8189                    }
8190                }
8191            }
8192        }
8193        if (r != null) {
8194            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8195        }
8196    }
8197
8198    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8199        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8200            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8201                return true;
8202            }
8203        }
8204        return false;
8205    }
8206
8207    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8208    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8209    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8210
8211    private void updatePermissionsLPw(String changingPkg,
8212            PackageParser.Package pkgInfo, int flags) {
8213        // Make sure there are no dangling permission trees.
8214        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8215        while (it.hasNext()) {
8216            final BasePermission bp = it.next();
8217            if (bp.packageSetting == null) {
8218                // We may not yet have parsed the package, so just see if
8219                // we still know about its settings.
8220                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8221            }
8222            if (bp.packageSetting == null) {
8223                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8224                        + " from package " + bp.sourcePackage);
8225                it.remove();
8226            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8227                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8228                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8229                            + " from package " + bp.sourcePackage);
8230                    flags |= UPDATE_PERMISSIONS_ALL;
8231                    it.remove();
8232                }
8233            }
8234        }
8235
8236        // Make sure all dynamic permissions have been assigned to a package,
8237        // and make sure there are no dangling permissions.
8238        it = mSettings.mPermissions.values().iterator();
8239        while (it.hasNext()) {
8240            final BasePermission bp = it.next();
8241            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8242                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8243                        + bp.name + " pkg=" + bp.sourcePackage
8244                        + " info=" + bp.pendingInfo);
8245                if (bp.packageSetting == null && bp.pendingInfo != null) {
8246                    final BasePermission tree = findPermissionTreeLP(bp.name);
8247                    if (tree != null && tree.perm != null) {
8248                        bp.packageSetting = tree.packageSetting;
8249                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8250                                new PermissionInfo(bp.pendingInfo));
8251                        bp.perm.info.packageName = tree.perm.info.packageName;
8252                        bp.perm.info.name = bp.name;
8253                        bp.uid = tree.uid;
8254                    }
8255                }
8256            }
8257            if (bp.packageSetting == null) {
8258                // We may not yet have parsed the package, so just see if
8259                // we still know about its settings.
8260                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8261            }
8262            if (bp.packageSetting == null) {
8263                Slog.w(TAG, "Removing dangling permission: " + bp.name
8264                        + " from package " + bp.sourcePackage);
8265                it.remove();
8266            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8267                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8268                    Slog.i(TAG, "Removing old permission: " + bp.name
8269                            + " from package " + bp.sourcePackage);
8270                    flags |= UPDATE_PERMISSIONS_ALL;
8271                    it.remove();
8272                }
8273            }
8274        }
8275
8276        // Now update the permissions for all packages, in particular
8277        // replace the granted permissions of the system packages.
8278        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8279            for (PackageParser.Package pkg : mPackages.values()) {
8280                if (pkg != pkgInfo) {
8281                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8282                            changingPkg);
8283                }
8284            }
8285        }
8286
8287        if (pkgInfo != null) {
8288            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8289        }
8290    }
8291
8292    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8293            String packageOfInterest) {
8294        // IMPORTANT: There are two types of permissions: install and runtime.
8295        // Install time permissions are granted when the app is installed to
8296        // all device users and users added in the future. Runtime permissions
8297        // are granted at runtime explicitly to specific users. Normal and signature
8298        // protected permissions are install time permissions. Dangerous permissions
8299        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8300        // otherwise they are runtime permissions. This function does not manage
8301        // runtime permissions except for the case an app targeting Lollipop MR1
8302        // being upgraded to target a newer SDK, in which case dangerous permissions
8303        // are transformed from install time to runtime ones.
8304
8305        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8306        if (ps == null) {
8307            return;
8308        }
8309
8310        PermissionsState permissionsState = ps.getPermissionsState();
8311        PermissionsState origPermissions = permissionsState;
8312
8313        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8314
8315        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8316
8317        boolean changedInstallPermission = false;
8318
8319        if (replace) {
8320            ps.installPermissionsFixed = false;
8321            if (!ps.isSharedUser()) {
8322                origPermissions = new PermissionsState(permissionsState);
8323                permissionsState.reset();
8324            }
8325        }
8326
8327        permissionsState.setGlobalGids(mGlobalGids);
8328
8329        final int N = pkg.requestedPermissions.size();
8330        for (int i=0; i<N; i++) {
8331            final String name = pkg.requestedPermissions.get(i);
8332            final BasePermission bp = mSettings.mPermissions.get(name);
8333
8334            if (DEBUG_INSTALL) {
8335                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8336            }
8337
8338            if (bp == null || bp.packageSetting == null) {
8339                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8340                    Slog.w(TAG, "Unknown permission " + name
8341                            + " in package " + pkg.packageName);
8342                }
8343                continue;
8344            }
8345
8346            final String perm = bp.name;
8347            boolean allowedSig = false;
8348            int grant = GRANT_DENIED;
8349
8350            // Keep track of app op permissions.
8351            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8352                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8353                if (pkgs == null) {
8354                    pkgs = new ArraySet<>();
8355                    mAppOpPermissionPackages.put(bp.name, pkgs);
8356                }
8357                pkgs.add(pkg.packageName);
8358            }
8359
8360            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8361            switch (level) {
8362                case PermissionInfo.PROTECTION_NORMAL: {
8363                    // For all apps normal permissions are install time ones.
8364                    grant = GRANT_INSTALL;
8365                } break;
8366
8367                case PermissionInfo.PROTECTION_DANGEROUS: {
8368                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8369                        // For legacy apps dangerous permissions are install time ones.
8370                        grant = GRANT_INSTALL_LEGACY;
8371                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8372                        // For legacy apps that became modern, install becomes runtime.
8373                        grant = GRANT_UPGRADE;
8374                    } else {
8375                        // For modern apps keep runtime permissions unchanged.
8376                        grant = GRANT_RUNTIME;
8377                    }
8378                } break;
8379
8380                case PermissionInfo.PROTECTION_SIGNATURE: {
8381                    // For all apps signature permissions are install time ones.
8382                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8383                    if (allowedSig) {
8384                        grant = GRANT_INSTALL;
8385                    }
8386                } break;
8387            }
8388
8389            if (DEBUG_INSTALL) {
8390                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8391            }
8392
8393            if (grant != GRANT_DENIED) {
8394                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8395                    // If this is an existing, non-system package, then
8396                    // we can't add any new permissions to it.
8397                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8398                        // Except...  if this is a permission that was added
8399                        // to the platform (note: need to only do this when
8400                        // updating the platform).
8401                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8402                            grant = GRANT_DENIED;
8403                        }
8404                    }
8405                }
8406
8407                switch (grant) {
8408                    case GRANT_INSTALL: {
8409                        // Revoke this as runtime permission to handle the case of
8410                        // a runtime permission being downgraded to an install one.
8411                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8412                            if (origPermissions.getRuntimePermissionState(
8413                                    bp.name, userId) != null) {
8414                                // Revoke the runtime permission and clear the flags.
8415                                origPermissions.revokeRuntimePermission(bp, userId);
8416                                origPermissions.updatePermissionFlags(bp, userId,
8417                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8418                                // If we revoked a permission permission, we have to write.
8419                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8420                                        changedRuntimePermissionUserIds, userId);
8421                            }
8422                        }
8423                        // Grant an install permission.
8424                        if (permissionsState.grantInstallPermission(bp) !=
8425                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8426                            changedInstallPermission = true;
8427                        }
8428                    } break;
8429
8430                    case GRANT_INSTALL_LEGACY: {
8431                        // Grant an install permission.
8432                        if (permissionsState.grantInstallPermission(bp) !=
8433                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8434                            changedInstallPermission = true;
8435                        }
8436                    } break;
8437
8438                    case GRANT_RUNTIME: {
8439                        // Grant previously granted runtime permissions.
8440                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8441                            PermissionState permissionState = origPermissions
8442                                    .getRuntimePermissionState(bp.name, userId);
8443                            final int flags = permissionState != null
8444                                    ? permissionState.getFlags() : 0;
8445                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8446                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8447                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8448                                    // If we cannot put the permission as it was, we have to write.
8449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8450                                            changedRuntimePermissionUserIds, userId);
8451                                }
8452                            }
8453                            // Propagate the permission flags.
8454                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8455                        }
8456                    } break;
8457
8458                    case GRANT_UPGRADE: {
8459                        // Grant runtime permissions for a previously held install permission.
8460                        PermissionState permissionState = origPermissions
8461                                .getInstallPermissionState(bp.name);
8462                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8463
8464                        if (origPermissions.revokeInstallPermission(bp)
8465                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8466                            // We will be transferring the permission flags, so clear them.
8467                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8468                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8469                            changedInstallPermission = true;
8470                        }
8471
8472                        // If the permission is not to be promoted to runtime we ignore it and
8473                        // also its other flags as they are not applicable to install permissions.
8474                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8475                            for (int userId : currentUserIds) {
8476                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8477                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8478                                    // Transfer the permission flags.
8479                                    permissionsState.updatePermissionFlags(bp, userId,
8480                                            flags, flags);
8481                                    // If we granted the permission, we have to write.
8482                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8483                                            changedRuntimePermissionUserIds, userId);
8484                                }
8485                            }
8486                        }
8487                    } break;
8488
8489                    default: {
8490                        if (packageOfInterest == null
8491                                || packageOfInterest.equals(pkg.packageName)) {
8492                            Slog.w(TAG, "Not granting permission " + perm
8493                                    + " to package " + pkg.packageName
8494                                    + " because it was previously installed without");
8495                        }
8496                    } break;
8497                }
8498            } else {
8499                if (permissionsState.revokeInstallPermission(bp) !=
8500                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8501                    // Also drop the permission flags.
8502                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8503                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8504                    changedInstallPermission = true;
8505                    Slog.i(TAG, "Un-granting permission " + perm
8506                            + " from package " + pkg.packageName
8507                            + " (protectionLevel=" + bp.protectionLevel
8508                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8509                            + ")");
8510                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8511                    // Don't print warning for app op permissions, since it is fine for them
8512                    // not to be granted, there is a UI for the user to decide.
8513                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8514                        Slog.w(TAG, "Not granting permission " + perm
8515                                + " to package " + pkg.packageName
8516                                + " (protectionLevel=" + bp.protectionLevel
8517                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8518                                + ")");
8519                    }
8520                }
8521            }
8522        }
8523
8524        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8525                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8526            // This is the first that we have heard about this package, so the
8527            // permissions we have now selected are fixed until explicitly
8528            // changed.
8529            ps.installPermissionsFixed = true;
8530        }
8531
8532        // Persist the runtime permissions state for users with changes.
8533        for (int userId : changedRuntimePermissionUserIds) {
8534            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8535        }
8536    }
8537
8538    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8539        boolean allowed = false;
8540        final int NP = PackageParser.NEW_PERMISSIONS.length;
8541        for (int ip=0; ip<NP; ip++) {
8542            final PackageParser.NewPermissionInfo npi
8543                    = PackageParser.NEW_PERMISSIONS[ip];
8544            if (npi.name.equals(perm)
8545                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8546                allowed = true;
8547                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8548                        + pkg.packageName);
8549                break;
8550            }
8551        }
8552        return allowed;
8553    }
8554
8555    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8556            BasePermission bp, PermissionsState origPermissions) {
8557        boolean allowed;
8558        allowed = (compareSignatures(
8559                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8560                        == PackageManager.SIGNATURE_MATCH)
8561                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8562                        == PackageManager.SIGNATURE_MATCH);
8563        if (!allowed && (bp.protectionLevel
8564                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8565            if (isSystemApp(pkg)) {
8566                // For updated system applications, a system permission
8567                // is granted only if it had been defined by the original application.
8568                if (pkg.isUpdatedSystemApp()) {
8569                    final PackageSetting sysPs = mSettings
8570                            .getDisabledSystemPkgLPr(pkg.packageName);
8571                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8572                        // If the original was granted this permission, we take
8573                        // that grant decision as read and propagate it to the
8574                        // update.
8575                        if (sysPs.isPrivileged()) {
8576                            allowed = true;
8577                        }
8578                    } else {
8579                        // The system apk may have been updated with an older
8580                        // version of the one on the data partition, but which
8581                        // granted a new system permission that it didn't have
8582                        // before.  In this case we do want to allow the app to
8583                        // now get the new permission if the ancestral apk is
8584                        // privileged to get it.
8585                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8586                            for (int j=0;
8587                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8588                                if (perm.equals(
8589                                        sysPs.pkg.requestedPermissions.get(j))) {
8590                                    allowed = true;
8591                                    break;
8592                                }
8593                            }
8594                        }
8595                    }
8596                } else {
8597                    allowed = isPrivilegedApp(pkg);
8598                }
8599            }
8600        }
8601        if (!allowed) {
8602            if (!allowed && (bp.protectionLevel
8603                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8604                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8605                // If this was a previously normal/dangerous permission that got moved
8606                // to a system permission as part of the runtime permission redesign, then
8607                // we still want to blindly grant it to old apps.
8608                allowed = true;
8609            }
8610            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8611                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8612                // If this permission is to be granted to the system installer and
8613                // this app is an installer, then it gets the permission.
8614                allowed = true;
8615            }
8616            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8617                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8618                // If this permission is to be granted to the system verifier and
8619                // this app is a verifier, then it gets the permission.
8620                allowed = true;
8621            }
8622            if (!allowed && (bp.protectionLevel
8623                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8624                    && isSystemApp(pkg)) {
8625                // Any pre-installed system app is allowed to get this permission.
8626                allowed = true;
8627            }
8628            if (!allowed && (bp.protectionLevel
8629                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8630                // For development permissions, a development permission
8631                // is granted only if it was already granted.
8632                allowed = origPermissions.hasInstallPermission(perm);
8633            }
8634        }
8635        return allowed;
8636    }
8637
8638    final class ActivityIntentResolver
8639            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8640        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8641                boolean defaultOnly, int userId) {
8642            if (!sUserManager.exists(userId)) return null;
8643            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8644            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8645        }
8646
8647        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8648                int userId) {
8649            if (!sUserManager.exists(userId)) return null;
8650            mFlags = flags;
8651            return super.queryIntent(intent, resolvedType,
8652                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8653        }
8654
8655        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8656                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8657            if (!sUserManager.exists(userId)) return null;
8658            if (packageActivities == null) {
8659                return null;
8660            }
8661            mFlags = flags;
8662            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8663            final int N = packageActivities.size();
8664            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8665                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8666
8667            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8668            for (int i = 0; i < N; ++i) {
8669                intentFilters = packageActivities.get(i).intents;
8670                if (intentFilters != null && intentFilters.size() > 0) {
8671                    PackageParser.ActivityIntentInfo[] array =
8672                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8673                    intentFilters.toArray(array);
8674                    listCut.add(array);
8675                }
8676            }
8677            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8678        }
8679
8680        public final void addActivity(PackageParser.Activity a, String type) {
8681            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8682            mActivities.put(a.getComponentName(), a);
8683            if (DEBUG_SHOW_INFO)
8684                Log.v(
8685                TAG, "  " + type + " " +
8686                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8687            if (DEBUG_SHOW_INFO)
8688                Log.v(TAG, "    Class=" + a.info.name);
8689            final int NI = a.intents.size();
8690            for (int j=0; j<NI; j++) {
8691                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8692                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8693                    intent.setPriority(0);
8694                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8695                            + a.className + " with priority > 0, forcing to 0");
8696                }
8697                if (DEBUG_SHOW_INFO) {
8698                    Log.v(TAG, "    IntentFilter:");
8699                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8700                }
8701                if (!intent.debugCheck()) {
8702                    Log.w(TAG, "==> For Activity " + a.info.name);
8703                }
8704                addFilter(intent);
8705            }
8706        }
8707
8708        public final void removeActivity(PackageParser.Activity a, String type) {
8709            mActivities.remove(a.getComponentName());
8710            if (DEBUG_SHOW_INFO) {
8711                Log.v(TAG, "  " + type + " "
8712                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8713                                : a.info.name) + ":");
8714                Log.v(TAG, "    Class=" + a.info.name);
8715            }
8716            final int NI = a.intents.size();
8717            for (int j=0; j<NI; j++) {
8718                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8719                if (DEBUG_SHOW_INFO) {
8720                    Log.v(TAG, "    IntentFilter:");
8721                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8722                }
8723                removeFilter(intent);
8724            }
8725        }
8726
8727        @Override
8728        protected boolean allowFilterResult(
8729                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8730            ActivityInfo filterAi = filter.activity.info;
8731            for (int i=dest.size()-1; i>=0; i--) {
8732                ActivityInfo destAi = dest.get(i).activityInfo;
8733                if (destAi.name == filterAi.name
8734                        && destAi.packageName == filterAi.packageName) {
8735                    return false;
8736                }
8737            }
8738            return true;
8739        }
8740
8741        @Override
8742        protected ActivityIntentInfo[] newArray(int size) {
8743            return new ActivityIntentInfo[size];
8744        }
8745
8746        @Override
8747        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8748            if (!sUserManager.exists(userId)) return true;
8749            PackageParser.Package p = filter.activity.owner;
8750            if (p != null) {
8751                PackageSetting ps = (PackageSetting)p.mExtras;
8752                if (ps != null) {
8753                    // System apps are never considered stopped for purposes of
8754                    // filtering, because there may be no way for the user to
8755                    // actually re-launch them.
8756                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8757                            && ps.getStopped(userId);
8758                }
8759            }
8760            return false;
8761        }
8762
8763        @Override
8764        protected boolean isPackageForFilter(String packageName,
8765                PackageParser.ActivityIntentInfo info) {
8766            return packageName.equals(info.activity.owner.packageName);
8767        }
8768
8769        @Override
8770        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8771                int match, int userId) {
8772            if (!sUserManager.exists(userId)) return null;
8773            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8774                return null;
8775            }
8776            final PackageParser.Activity activity = info.activity;
8777            if (mSafeMode && (activity.info.applicationInfo.flags
8778                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8779                return null;
8780            }
8781            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8782            if (ps == null) {
8783                return null;
8784            }
8785            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8786                    ps.readUserState(userId), userId);
8787            if (ai == null) {
8788                return null;
8789            }
8790            final ResolveInfo res = new ResolveInfo();
8791            res.activityInfo = ai;
8792            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8793                res.filter = info;
8794            }
8795            if (info != null) {
8796                res.handleAllWebDataURI = info.handleAllWebDataURI();
8797            }
8798            res.priority = info.getPriority();
8799            res.preferredOrder = activity.owner.mPreferredOrder;
8800            //System.out.println("Result: " + res.activityInfo.className +
8801            //                   " = " + res.priority);
8802            res.match = match;
8803            res.isDefault = info.hasDefault;
8804            res.labelRes = info.labelRes;
8805            res.nonLocalizedLabel = info.nonLocalizedLabel;
8806            if (userNeedsBadging(userId)) {
8807                res.noResourceId = true;
8808            } else {
8809                res.icon = info.icon;
8810            }
8811            res.iconResourceId = info.icon;
8812            res.system = res.activityInfo.applicationInfo.isSystemApp();
8813            return res;
8814        }
8815
8816        @Override
8817        protected void sortResults(List<ResolveInfo> results) {
8818            Collections.sort(results, mResolvePrioritySorter);
8819        }
8820
8821        @Override
8822        protected void dumpFilter(PrintWriter out, String prefix,
8823                PackageParser.ActivityIntentInfo filter) {
8824            out.print(prefix); out.print(
8825                    Integer.toHexString(System.identityHashCode(filter.activity)));
8826                    out.print(' ');
8827                    filter.activity.printComponentShortName(out);
8828                    out.print(" filter ");
8829                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8830        }
8831
8832        @Override
8833        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8834            return filter.activity;
8835        }
8836
8837        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8838            PackageParser.Activity activity = (PackageParser.Activity)label;
8839            out.print(prefix); out.print(
8840                    Integer.toHexString(System.identityHashCode(activity)));
8841                    out.print(' ');
8842                    activity.printComponentShortName(out);
8843            if (count > 1) {
8844                out.print(" ("); out.print(count); out.print(" filters)");
8845            }
8846            out.println();
8847        }
8848
8849//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8850//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8851//            final List<ResolveInfo> retList = Lists.newArrayList();
8852//            while (i.hasNext()) {
8853//                final ResolveInfo resolveInfo = i.next();
8854//                if (isEnabledLP(resolveInfo.activityInfo)) {
8855//                    retList.add(resolveInfo);
8856//                }
8857//            }
8858//            return retList;
8859//        }
8860
8861        // Keys are String (activity class name), values are Activity.
8862        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8863                = new ArrayMap<ComponentName, PackageParser.Activity>();
8864        private int mFlags;
8865    }
8866
8867    private final class ServiceIntentResolver
8868            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8869        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8870                boolean defaultOnly, int userId) {
8871            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8872            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8873        }
8874
8875        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8876                int userId) {
8877            if (!sUserManager.exists(userId)) return null;
8878            mFlags = flags;
8879            return super.queryIntent(intent, resolvedType,
8880                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8881        }
8882
8883        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8884                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8885            if (!sUserManager.exists(userId)) return null;
8886            if (packageServices == null) {
8887                return null;
8888            }
8889            mFlags = flags;
8890            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8891            final int N = packageServices.size();
8892            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8893                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8894
8895            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8896            for (int i = 0; i < N; ++i) {
8897                intentFilters = packageServices.get(i).intents;
8898                if (intentFilters != null && intentFilters.size() > 0) {
8899                    PackageParser.ServiceIntentInfo[] array =
8900                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8901                    intentFilters.toArray(array);
8902                    listCut.add(array);
8903                }
8904            }
8905            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8906        }
8907
8908        public final void addService(PackageParser.Service s) {
8909            mServices.put(s.getComponentName(), s);
8910            if (DEBUG_SHOW_INFO) {
8911                Log.v(TAG, "  "
8912                        + (s.info.nonLocalizedLabel != null
8913                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8914                Log.v(TAG, "    Class=" + s.info.name);
8915            }
8916            final int NI = s.intents.size();
8917            int j;
8918            for (j=0; j<NI; j++) {
8919                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8920                if (DEBUG_SHOW_INFO) {
8921                    Log.v(TAG, "    IntentFilter:");
8922                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8923                }
8924                if (!intent.debugCheck()) {
8925                    Log.w(TAG, "==> For Service " + s.info.name);
8926                }
8927                addFilter(intent);
8928            }
8929        }
8930
8931        public final void removeService(PackageParser.Service s) {
8932            mServices.remove(s.getComponentName());
8933            if (DEBUG_SHOW_INFO) {
8934                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8935                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8936                Log.v(TAG, "    Class=" + s.info.name);
8937            }
8938            final int NI = s.intents.size();
8939            int j;
8940            for (j=0; j<NI; j++) {
8941                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8942                if (DEBUG_SHOW_INFO) {
8943                    Log.v(TAG, "    IntentFilter:");
8944                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8945                }
8946                removeFilter(intent);
8947            }
8948        }
8949
8950        @Override
8951        protected boolean allowFilterResult(
8952                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8953            ServiceInfo filterSi = filter.service.info;
8954            for (int i=dest.size()-1; i>=0; i--) {
8955                ServiceInfo destAi = dest.get(i).serviceInfo;
8956                if (destAi.name == filterSi.name
8957                        && destAi.packageName == filterSi.packageName) {
8958                    return false;
8959                }
8960            }
8961            return true;
8962        }
8963
8964        @Override
8965        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8966            return new PackageParser.ServiceIntentInfo[size];
8967        }
8968
8969        @Override
8970        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8971            if (!sUserManager.exists(userId)) return true;
8972            PackageParser.Package p = filter.service.owner;
8973            if (p != null) {
8974                PackageSetting ps = (PackageSetting)p.mExtras;
8975                if (ps != null) {
8976                    // System apps are never considered stopped for purposes of
8977                    // filtering, because there may be no way for the user to
8978                    // actually re-launch them.
8979                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8980                            && ps.getStopped(userId);
8981                }
8982            }
8983            return false;
8984        }
8985
8986        @Override
8987        protected boolean isPackageForFilter(String packageName,
8988                PackageParser.ServiceIntentInfo info) {
8989            return packageName.equals(info.service.owner.packageName);
8990        }
8991
8992        @Override
8993        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8994                int match, int userId) {
8995            if (!sUserManager.exists(userId)) return null;
8996            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8997            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8998                return null;
8999            }
9000            final PackageParser.Service service = info.service;
9001            if (mSafeMode && (service.info.applicationInfo.flags
9002                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9003                return null;
9004            }
9005            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9006            if (ps == null) {
9007                return null;
9008            }
9009            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9010                    ps.readUserState(userId), userId);
9011            if (si == null) {
9012                return null;
9013            }
9014            final ResolveInfo res = new ResolveInfo();
9015            res.serviceInfo = si;
9016            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9017                res.filter = filter;
9018            }
9019            res.priority = info.getPriority();
9020            res.preferredOrder = service.owner.mPreferredOrder;
9021            res.match = match;
9022            res.isDefault = info.hasDefault;
9023            res.labelRes = info.labelRes;
9024            res.nonLocalizedLabel = info.nonLocalizedLabel;
9025            res.icon = info.icon;
9026            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9027            return res;
9028        }
9029
9030        @Override
9031        protected void sortResults(List<ResolveInfo> results) {
9032            Collections.sort(results, mResolvePrioritySorter);
9033        }
9034
9035        @Override
9036        protected void dumpFilter(PrintWriter out, String prefix,
9037                PackageParser.ServiceIntentInfo filter) {
9038            out.print(prefix); out.print(
9039                    Integer.toHexString(System.identityHashCode(filter.service)));
9040                    out.print(' ');
9041                    filter.service.printComponentShortName(out);
9042                    out.print(" filter ");
9043                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9044        }
9045
9046        @Override
9047        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9048            return filter.service;
9049        }
9050
9051        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9052            PackageParser.Service service = (PackageParser.Service)label;
9053            out.print(prefix); out.print(
9054                    Integer.toHexString(System.identityHashCode(service)));
9055                    out.print(' ');
9056                    service.printComponentShortName(out);
9057            if (count > 1) {
9058                out.print(" ("); out.print(count); out.print(" filters)");
9059            }
9060            out.println();
9061        }
9062
9063//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9064//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9065//            final List<ResolveInfo> retList = Lists.newArrayList();
9066//            while (i.hasNext()) {
9067//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9068//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9069//                    retList.add(resolveInfo);
9070//                }
9071//            }
9072//            return retList;
9073//        }
9074
9075        // Keys are String (activity class name), values are Activity.
9076        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9077                = new ArrayMap<ComponentName, PackageParser.Service>();
9078        private int mFlags;
9079    };
9080
9081    private final class ProviderIntentResolver
9082            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9083        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9084                boolean defaultOnly, int userId) {
9085            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9086            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9087        }
9088
9089        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9090                int userId) {
9091            if (!sUserManager.exists(userId))
9092                return null;
9093            mFlags = flags;
9094            return super.queryIntent(intent, resolvedType,
9095                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9096        }
9097
9098        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9099                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9100            if (!sUserManager.exists(userId))
9101                return null;
9102            if (packageProviders == null) {
9103                return null;
9104            }
9105            mFlags = flags;
9106            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9107            final int N = packageProviders.size();
9108            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9109                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9110
9111            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9112            for (int i = 0; i < N; ++i) {
9113                intentFilters = packageProviders.get(i).intents;
9114                if (intentFilters != null && intentFilters.size() > 0) {
9115                    PackageParser.ProviderIntentInfo[] array =
9116                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9117                    intentFilters.toArray(array);
9118                    listCut.add(array);
9119                }
9120            }
9121            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9122        }
9123
9124        public final void addProvider(PackageParser.Provider p) {
9125            if (mProviders.containsKey(p.getComponentName())) {
9126                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9127                return;
9128            }
9129
9130            mProviders.put(p.getComponentName(), p);
9131            if (DEBUG_SHOW_INFO) {
9132                Log.v(TAG, "  "
9133                        + (p.info.nonLocalizedLabel != null
9134                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9135                Log.v(TAG, "    Class=" + p.info.name);
9136            }
9137            final int NI = p.intents.size();
9138            int j;
9139            for (j = 0; j < NI; j++) {
9140                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9141                if (DEBUG_SHOW_INFO) {
9142                    Log.v(TAG, "    IntentFilter:");
9143                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9144                }
9145                if (!intent.debugCheck()) {
9146                    Log.w(TAG, "==> For Provider " + p.info.name);
9147                }
9148                addFilter(intent);
9149            }
9150        }
9151
9152        public final void removeProvider(PackageParser.Provider p) {
9153            mProviders.remove(p.getComponentName());
9154            if (DEBUG_SHOW_INFO) {
9155                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9156                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9157                Log.v(TAG, "    Class=" + p.info.name);
9158            }
9159            final int NI = p.intents.size();
9160            int j;
9161            for (j = 0; j < NI; j++) {
9162                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9163                if (DEBUG_SHOW_INFO) {
9164                    Log.v(TAG, "    IntentFilter:");
9165                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9166                }
9167                removeFilter(intent);
9168            }
9169        }
9170
9171        @Override
9172        protected boolean allowFilterResult(
9173                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9174            ProviderInfo filterPi = filter.provider.info;
9175            for (int i = dest.size() - 1; i >= 0; i--) {
9176                ProviderInfo destPi = dest.get(i).providerInfo;
9177                if (destPi.name == filterPi.name
9178                        && destPi.packageName == filterPi.packageName) {
9179                    return false;
9180                }
9181            }
9182            return true;
9183        }
9184
9185        @Override
9186        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9187            return new PackageParser.ProviderIntentInfo[size];
9188        }
9189
9190        @Override
9191        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9192            if (!sUserManager.exists(userId))
9193                return true;
9194            PackageParser.Package p = filter.provider.owner;
9195            if (p != null) {
9196                PackageSetting ps = (PackageSetting) p.mExtras;
9197                if (ps != null) {
9198                    // System apps are never considered stopped for purposes of
9199                    // filtering, because there may be no way for the user to
9200                    // actually re-launch them.
9201                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9202                            && ps.getStopped(userId);
9203                }
9204            }
9205            return false;
9206        }
9207
9208        @Override
9209        protected boolean isPackageForFilter(String packageName,
9210                PackageParser.ProviderIntentInfo info) {
9211            return packageName.equals(info.provider.owner.packageName);
9212        }
9213
9214        @Override
9215        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9216                int match, int userId) {
9217            if (!sUserManager.exists(userId))
9218                return null;
9219            final PackageParser.ProviderIntentInfo info = filter;
9220            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9221                return null;
9222            }
9223            final PackageParser.Provider provider = info.provider;
9224            if (mSafeMode && (provider.info.applicationInfo.flags
9225                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9226                return null;
9227            }
9228            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9229            if (ps == null) {
9230                return null;
9231            }
9232            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9233                    ps.readUserState(userId), userId);
9234            if (pi == null) {
9235                return null;
9236            }
9237            final ResolveInfo res = new ResolveInfo();
9238            res.providerInfo = pi;
9239            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9240                res.filter = filter;
9241            }
9242            res.priority = info.getPriority();
9243            res.preferredOrder = provider.owner.mPreferredOrder;
9244            res.match = match;
9245            res.isDefault = info.hasDefault;
9246            res.labelRes = info.labelRes;
9247            res.nonLocalizedLabel = info.nonLocalizedLabel;
9248            res.icon = info.icon;
9249            res.system = res.providerInfo.applicationInfo.isSystemApp();
9250            return res;
9251        }
9252
9253        @Override
9254        protected void sortResults(List<ResolveInfo> results) {
9255            Collections.sort(results, mResolvePrioritySorter);
9256        }
9257
9258        @Override
9259        protected void dumpFilter(PrintWriter out, String prefix,
9260                PackageParser.ProviderIntentInfo filter) {
9261            out.print(prefix);
9262            out.print(
9263                    Integer.toHexString(System.identityHashCode(filter.provider)));
9264            out.print(' ');
9265            filter.provider.printComponentShortName(out);
9266            out.print(" filter ");
9267            out.println(Integer.toHexString(System.identityHashCode(filter)));
9268        }
9269
9270        @Override
9271        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9272            return filter.provider;
9273        }
9274
9275        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9276            PackageParser.Provider provider = (PackageParser.Provider)label;
9277            out.print(prefix); out.print(
9278                    Integer.toHexString(System.identityHashCode(provider)));
9279                    out.print(' ');
9280                    provider.printComponentShortName(out);
9281            if (count > 1) {
9282                out.print(" ("); out.print(count); out.print(" filters)");
9283            }
9284            out.println();
9285        }
9286
9287        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9288                = new ArrayMap<ComponentName, PackageParser.Provider>();
9289        private int mFlags;
9290    };
9291
9292    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9293            new Comparator<ResolveInfo>() {
9294        public int compare(ResolveInfo r1, ResolveInfo r2) {
9295            int v1 = r1.priority;
9296            int v2 = r2.priority;
9297            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9298            if (v1 != v2) {
9299                return (v1 > v2) ? -1 : 1;
9300            }
9301            v1 = r1.preferredOrder;
9302            v2 = r2.preferredOrder;
9303            if (v1 != v2) {
9304                return (v1 > v2) ? -1 : 1;
9305            }
9306            if (r1.isDefault != r2.isDefault) {
9307                return r1.isDefault ? -1 : 1;
9308            }
9309            v1 = r1.match;
9310            v2 = r2.match;
9311            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9312            if (v1 != v2) {
9313                return (v1 > v2) ? -1 : 1;
9314            }
9315            if (r1.system != r2.system) {
9316                return r1.system ? -1 : 1;
9317            }
9318            return 0;
9319        }
9320    };
9321
9322    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9323            new Comparator<ProviderInfo>() {
9324        public int compare(ProviderInfo p1, ProviderInfo p2) {
9325            final int v1 = p1.initOrder;
9326            final int v2 = p2.initOrder;
9327            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9328        }
9329    };
9330
9331    final void sendPackageBroadcast(final String action, final String pkg,
9332            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9333            final int[] userIds) {
9334        mHandler.post(new Runnable() {
9335            @Override
9336            public void run() {
9337                try {
9338                    final IActivityManager am = ActivityManagerNative.getDefault();
9339                    if (am == null) return;
9340                    final int[] resolvedUserIds;
9341                    if (userIds == null) {
9342                        resolvedUserIds = am.getRunningUserIds();
9343                    } else {
9344                        resolvedUserIds = userIds;
9345                    }
9346                    for (int id : resolvedUserIds) {
9347                        final Intent intent = new Intent(action,
9348                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9349                        if (extras != null) {
9350                            intent.putExtras(extras);
9351                        }
9352                        if (targetPkg != null) {
9353                            intent.setPackage(targetPkg);
9354                        }
9355                        // Modify the UID when posting to other users
9356                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9357                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9358                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9359                            intent.putExtra(Intent.EXTRA_UID, uid);
9360                        }
9361                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9362                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9363                        if (DEBUG_BROADCASTS) {
9364                            RuntimeException here = new RuntimeException("here");
9365                            here.fillInStackTrace();
9366                            Slog.d(TAG, "Sending to user " + id + ": "
9367                                    + intent.toShortString(false, true, false, false)
9368                                    + " " + intent.getExtras(), here);
9369                        }
9370                        am.broadcastIntent(null, intent, null, finishedReceiver,
9371                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9372                                null, finishedReceiver != null, false, id);
9373                    }
9374                } catch (RemoteException ex) {
9375                }
9376            }
9377        });
9378    }
9379
9380    /**
9381     * Check if the external storage media is available. This is true if there
9382     * is a mounted external storage medium or if the external storage is
9383     * emulated.
9384     */
9385    private boolean isExternalMediaAvailable() {
9386        return mMediaMounted || Environment.isExternalStorageEmulated();
9387    }
9388
9389    @Override
9390    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9391        // writer
9392        synchronized (mPackages) {
9393            if (!isExternalMediaAvailable()) {
9394                // If the external storage is no longer mounted at this point,
9395                // the caller may not have been able to delete all of this
9396                // packages files and can not delete any more.  Bail.
9397                return null;
9398            }
9399            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9400            if (lastPackage != null) {
9401                pkgs.remove(lastPackage);
9402            }
9403            if (pkgs.size() > 0) {
9404                return pkgs.get(0);
9405            }
9406        }
9407        return null;
9408    }
9409
9410    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9411        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9412                userId, andCode ? 1 : 0, packageName);
9413        if (mSystemReady) {
9414            msg.sendToTarget();
9415        } else {
9416            if (mPostSystemReadyMessages == null) {
9417                mPostSystemReadyMessages = new ArrayList<>();
9418            }
9419            mPostSystemReadyMessages.add(msg);
9420        }
9421    }
9422
9423    void startCleaningPackages() {
9424        // reader
9425        synchronized (mPackages) {
9426            if (!isExternalMediaAvailable()) {
9427                return;
9428            }
9429            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9430                return;
9431            }
9432        }
9433        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9434        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9435        IActivityManager am = ActivityManagerNative.getDefault();
9436        if (am != null) {
9437            try {
9438                am.startService(null, intent, null, mContext.getOpPackageName(),
9439                        UserHandle.USER_OWNER);
9440            } catch (RemoteException e) {
9441            }
9442        }
9443    }
9444
9445    @Override
9446    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9447            int installFlags, String installerPackageName, VerificationParams verificationParams,
9448            String packageAbiOverride) {
9449        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9450                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9451    }
9452
9453    @Override
9454    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9455            int installFlags, String installerPackageName, VerificationParams verificationParams,
9456            String packageAbiOverride, int userId) {
9457        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9458
9459        final int callingUid = Binder.getCallingUid();
9460        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9461
9462        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9463            try {
9464                if (observer != null) {
9465                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9466                }
9467            } catch (RemoteException re) {
9468            }
9469            return;
9470        }
9471
9472        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9473            installFlags |= PackageManager.INSTALL_FROM_ADB;
9474
9475        } else {
9476            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9477            // about installerPackageName.
9478
9479            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9480            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9481        }
9482
9483        UserHandle user;
9484        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9485            user = UserHandle.ALL;
9486        } else {
9487            user = new UserHandle(userId);
9488        }
9489
9490        // Only system components can circumvent runtime permissions when installing.
9491        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9492                && mContext.checkCallingOrSelfPermission(Manifest.permission
9493                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9494            throw new SecurityException("You need the "
9495                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9496                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9497        }
9498
9499        verificationParams.setInstallerUid(callingUid);
9500
9501        final File originFile = new File(originPath);
9502        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9503
9504        final Message msg = mHandler.obtainMessage(INIT_COPY);
9505        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9506                null, verificationParams, user, packageAbiOverride, null);
9507        mHandler.sendMessage(msg);
9508    }
9509
9510    void installStage(String packageName, File stagedDir, String stagedCid,
9511            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9512            String installerPackageName, int installerUid, UserHandle user) {
9513        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9514                params.referrerUri, installerUid, null);
9515        verifParams.setInstallerUid(installerUid);
9516
9517        final OriginInfo origin;
9518        if (stagedDir != null) {
9519            origin = OriginInfo.fromStagedFile(stagedDir);
9520        } else {
9521            origin = OriginInfo.fromStagedContainer(stagedCid);
9522        }
9523
9524        final Message msg = mHandler.obtainMessage(INIT_COPY);
9525        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9526                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9527                params.grantedRuntimePermissions);
9528        mHandler.sendMessage(msg);
9529    }
9530
9531    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9532        Bundle extras = new Bundle(1);
9533        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9534
9535        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9536                packageName, extras, null, null, new int[] {userId});
9537        try {
9538            IActivityManager am = ActivityManagerNative.getDefault();
9539            final boolean isSystem =
9540                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9541            if (isSystem && am.isUserRunning(userId, false)) {
9542                // The just-installed/enabled app is bundled on the system, so presumed
9543                // to be able to run automatically without needing an explicit launch.
9544                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9545                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9546                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9547                        .setPackage(packageName);
9548                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9549                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9550            }
9551        } catch (RemoteException e) {
9552            // shouldn't happen
9553            Slog.w(TAG, "Unable to bootstrap installed package", e);
9554        }
9555    }
9556
9557    @Override
9558    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9559            int userId) {
9560        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9561        PackageSetting pkgSetting;
9562        final int uid = Binder.getCallingUid();
9563        enforceCrossUserPermission(uid, userId, true, true,
9564                "setApplicationHiddenSetting for user " + userId);
9565
9566        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9567            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9568            return false;
9569        }
9570
9571        long callingId = Binder.clearCallingIdentity();
9572        try {
9573            boolean sendAdded = false;
9574            boolean sendRemoved = false;
9575            // writer
9576            synchronized (mPackages) {
9577                pkgSetting = mSettings.mPackages.get(packageName);
9578                if (pkgSetting == null) {
9579                    return false;
9580                }
9581                if (pkgSetting.getHidden(userId) != hidden) {
9582                    pkgSetting.setHidden(hidden, userId);
9583                    mSettings.writePackageRestrictionsLPr(userId);
9584                    if (hidden) {
9585                        sendRemoved = true;
9586                    } else {
9587                        sendAdded = true;
9588                    }
9589                }
9590            }
9591            if (sendAdded) {
9592                sendPackageAddedForUser(packageName, pkgSetting, userId);
9593                return true;
9594            }
9595            if (sendRemoved) {
9596                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9597                        "hiding pkg");
9598                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9599            }
9600        } finally {
9601            Binder.restoreCallingIdentity(callingId);
9602        }
9603        return false;
9604    }
9605
9606    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9607            int userId) {
9608        final PackageRemovedInfo info = new PackageRemovedInfo();
9609        info.removedPackage = packageName;
9610        info.removedUsers = new int[] {userId};
9611        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9612        info.sendBroadcast(false, false, false);
9613    }
9614
9615    /**
9616     * Returns true if application is not found or there was an error. Otherwise it returns
9617     * the hidden state of the package for the given user.
9618     */
9619    @Override
9620    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9622        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9623                false, "getApplicationHidden for user " + userId);
9624        PackageSetting pkgSetting;
9625        long callingId = Binder.clearCallingIdentity();
9626        try {
9627            // writer
9628            synchronized (mPackages) {
9629                pkgSetting = mSettings.mPackages.get(packageName);
9630                if (pkgSetting == null) {
9631                    return true;
9632                }
9633                return pkgSetting.getHidden(userId);
9634            }
9635        } finally {
9636            Binder.restoreCallingIdentity(callingId);
9637        }
9638    }
9639
9640    /**
9641     * @hide
9642     */
9643    @Override
9644    public int installExistingPackageAsUser(String packageName, int userId) {
9645        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9646                null);
9647        PackageSetting pkgSetting;
9648        final int uid = Binder.getCallingUid();
9649        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9650                + userId);
9651        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9652            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9653        }
9654
9655        long callingId = Binder.clearCallingIdentity();
9656        try {
9657            boolean sendAdded = false;
9658
9659            // writer
9660            synchronized (mPackages) {
9661                pkgSetting = mSettings.mPackages.get(packageName);
9662                if (pkgSetting == null) {
9663                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9664                }
9665                if (!pkgSetting.getInstalled(userId)) {
9666                    pkgSetting.setInstalled(true, userId);
9667                    pkgSetting.setHidden(false, userId);
9668                    mSettings.writePackageRestrictionsLPr(userId);
9669                    sendAdded = true;
9670                }
9671            }
9672
9673            if (sendAdded) {
9674                sendPackageAddedForUser(packageName, pkgSetting, userId);
9675            }
9676        } finally {
9677            Binder.restoreCallingIdentity(callingId);
9678        }
9679
9680        return PackageManager.INSTALL_SUCCEEDED;
9681    }
9682
9683    boolean isUserRestricted(int userId, String restrictionKey) {
9684        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9685        if (restrictions.getBoolean(restrictionKey, false)) {
9686            Log.w(TAG, "User is restricted: " + restrictionKey);
9687            return true;
9688        }
9689        return false;
9690    }
9691
9692    @Override
9693    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9694        mContext.enforceCallingOrSelfPermission(
9695                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9696                "Only package verification agents can verify applications");
9697
9698        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9699        final PackageVerificationResponse response = new PackageVerificationResponse(
9700                verificationCode, Binder.getCallingUid());
9701        msg.arg1 = id;
9702        msg.obj = response;
9703        mHandler.sendMessage(msg);
9704    }
9705
9706    @Override
9707    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9708            long millisecondsToDelay) {
9709        mContext.enforceCallingOrSelfPermission(
9710                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9711                "Only package verification agents can extend verification timeouts");
9712
9713        final PackageVerificationState state = mPendingVerification.get(id);
9714        final PackageVerificationResponse response = new PackageVerificationResponse(
9715                verificationCodeAtTimeout, Binder.getCallingUid());
9716
9717        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9718            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9719        }
9720        if (millisecondsToDelay < 0) {
9721            millisecondsToDelay = 0;
9722        }
9723        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9724                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9725            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9726        }
9727
9728        if ((state != null) && !state.timeoutExtended()) {
9729            state.extendTimeout();
9730
9731            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9732            msg.arg1 = id;
9733            msg.obj = response;
9734            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9735        }
9736    }
9737
9738    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9739            int verificationCode, UserHandle user) {
9740        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9741        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9742        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9743        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9744        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9745
9746        mContext.sendBroadcastAsUser(intent, user,
9747                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9748    }
9749
9750    private ComponentName matchComponentForVerifier(String packageName,
9751            List<ResolveInfo> receivers) {
9752        ActivityInfo targetReceiver = null;
9753
9754        final int NR = receivers.size();
9755        for (int i = 0; i < NR; i++) {
9756            final ResolveInfo info = receivers.get(i);
9757            if (info.activityInfo == null) {
9758                continue;
9759            }
9760
9761            if (packageName.equals(info.activityInfo.packageName)) {
9762                targetReceiver = info.activityInfo;
9763                break;
9764            }
9765        }
9766
9767        if (targetReceiver == null) {
9768            return null;
9769        }
9770
9771        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9772    }
9773
9774    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9775            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9776        if (pkgInfo.verifiers.length == 0) {
9777            return null;
9778        }
9779
9780        final int N = pkgInfo.verifiers.length;
9781        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9782        for (int i = 0; i < N; i++) {
9783            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9784
9785            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9786                    receivers);
9787            if (comp == null) {
9788                continue;
9789            }
9790
9791            final int verifierUid = getUidForVerifier(verifierInfo);
9792            if (verifierUid == -1) {
9793                continue;
9794            }
9795
9796            if (DEBUG_VERIFY) {
9797                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9798                        + " with the correct signature");
9799            }
9800            sufficientVerifiers.add(comp);
9801            verificationState.addSufficientVerifier(verifierUid);
9802        }
9803
9804        return sufficientVerifiers;
9805    }
9806
9807    private int getUidForVerifier(VerifierInfo verifierInfo) {
9808        synchronized (mPackages) {
9809            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9810            if (pkg == null) {
9811                return -1;
9812            } else if (pkg.mSignatures.length != 1) {
9813                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9814                        + " has more than one signature; ignoring");
9815                return -1;
9816            }
9817
9818            /*
9819             * If the public key of the package's signature does not match
9820             * our expected public key, then this is a different package and
9821             * we should skip.
9822             */
9823
9824            final byte[] expectedPublicKey;
9825            try {
9826                final Signature verifierSig = pkg.mSignatures[0];
9827                final PublicKey publicKey = verifierSig.getPublicKey();
9828                expectedPublicKey = publicKey.getEncoded();
9829            } catch (CertificateException e) {
9830                return -1;
9831            }
9832
9833            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9834
9835            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9836                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9837                        + " does not have the expected public key; ignoring");
9838                return -1;
9839            }
9840
9841            return pkg.applicationInfo.uid;
9842        }
9843    }
9844
9845    @Override
9846    public void finishPackageInstall(int token) {
9847        enforceSystemOrRoot("Only the system is allowed to finish installs");
9848
9849        if (DEBUG_INSTALL) {
9850            Slog.v(TAG, "BM finishing package install for " + token);
9851        }
9852
9853        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9854        mHandler.sendMessage(msg);
9855    }
9856
9857    /**
9858     * Get the verification agent timeout.
9859     *
9860     * @return verification timeout in milliseconds
9861     */
9862    private long getVerificationTimeout() {
9863        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9864                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9865                DEFAULT_VERIFICATION_TIMEOUT);
9866    }
9867
9868    /**
9869     * Get the default verification agent response code.
9870     *
9871     * @return default verification response code
9872     */
9873    private int getDefaultVerificationResponse() {
9874        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9875                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9876                DEFAULT_VERIFICATION_RESPONSE);
9877    }
9878
9879    /**
9880     * Check whether or not package verification has been enabled.
9881     *
9882     * @return true if verification should be performed
9883     */
9884    private boolean isVerificationEnabled(int userId, int installFlags) {
9885        if (!DEFAULT_VERIFY_ENABLE) {
9886            return false;
9887        }
9888
9889        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9890
9891        // Check if installing from ADB
9892        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9893            // Do not run verification in a test harness environment
9894            if (ActivityManager.isRunningInTestHarness()) {
9895                return false;
9896            }
9897            if (ensureVerifyAppsEnabled) {
9898                return true;
9899            }
9900            // Check if the developer does not want package verification for ADB installs
9901            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9902                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9903                return false;
9904            }
9905        }
9906
9907        if (ensureVerifyAppsEnabled) {
9908            return true;
9909        }
9910
9911        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9912                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9913    }
9914
9915    @Override
9916    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9917            throws RemoteException {
9918        mContext.enforceCallingOrSelfPermission(
9919                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9920                "Only intentfilter verification agents can verify applications");
9921
9922        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9923        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9924                Binder.getCallingUid(), verificationCode, failedDomains);
9925        msg.arg1 = id;
9926        msg.obj = response;
9927        mHandler.sendMessage(msg);
9928    }
9929
9930    @Override
9931    public int getIntentVerificationStatus(String packageName, int userId) {
9932        synchronized (mPackages) {
9933            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9934        }
9935    }
9936
9937    @Override
9938    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9939        mContext.enforceCallingOrSelfPermission(
9940                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9941
9942        boolean result = false;
9943        synchronized (mPackages) {
9944            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9945        }
9946        if (result) {
9947            scheduleWritePackageRestrictionsLocked(userId);
9948        }
9949        return result;
9950    }
9951
9952    @Override
9953    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9954        synchronized (mPackages) {
9955            return mSettings.getIntentFilterVerificationsLPr(packageName);
9956        }
9957    }
9958
9959    @Override
9960    public List<IntentFilter> getAllIntentFilters(String packageName) {
9961        if (TextUtils.isEmpty(packageName)) {
9962            return Collections.<IntentFilter>emptyList();
9963        }
9964        synchronized (mPackages) {
9965            PackageParser.Package pkg = mPackages.get(packageName);
9966            if (pkg == null || pkg.activities == null) {
9967                return Collections.<IntentFilter>emptyList();
9968            }
9969            final int count = pkg.activities.size();
9970            ArrayList<IntentFilter> result = new ArrayList<>();
9971            for (int n=0; n<count; n++) {
9972                PackageParser.Activity activity = pkg.activities.get(n);
9973                if (activity.intents != null || activity.intents.size() > 0) {
9974                    result.addAll(activity.intents);
9975                }
9976            }
9977            return result;
9978        }
9979    }
9980
9981    @Override
9982    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9983        mContext.enforceCallingOrSelfPermission(
9984                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9985
9986        synchronized (mPackages) {
9987            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9988            if (packageName != null) {
9989                result |= updateIntentVerificationStatus(packageName,
9990                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9991                        userId);
9992                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9993                        packageName, userId);
9994            }
9995            return result;
9996        }
9997    }
9998
9999    @Override
10000    public String getDefaultBrowserPackageName(int userId) {
10001        synchronized (mPackages) {
10002            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10003        }
10004    }
10005
10006    /**
10007     * Get the "allow unknown sources" setting.
10008     *
10009     * @return the current "allow unknown sources" setting
10010     */
10011    private int getUnknownSourcesSettings() {
10012        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10013                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10014                -1);
10015    }
10016
10017    @Override
10018    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10019        final int uid = Binder.getCallingUid();
10020        // writer
10021        synchronized (mPackages) {
10022            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10023            if (targetPackageSetting == null) {
10024                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10025            }
10026
10027            PackageSetting installerPackageSetting;
10028            if (installerPackageName != null) {
10029                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10030                if (installerPackageSetting == null) {
10031                    throw new IllegalArgumentException("Unknown installer package: "
10032                            + installerPackageName);
10033                }
10034            } else {
10035                installerPackageSetting = null;
10036            }
10037
10038            Signature[] callerSignature;
10039            Object obj = mSettings.getUserIdLPr(uid);
10040            if (obj != null) {
10041                if (obj instanceof SharedUserSetting) {
10042                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10043                } else if (obj instanceof PackageSetting) {
10044                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10045                } else {
10046                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10047                }
10048            } else {
10049                throw new SecurityException("Unknown calling uid " + uid);
10050            }
10051
10052            // Verify: can't set installerPackageName to a package that is
10053            // not signed with the same cert as the caller.
10054            if (installerPackageSetting != null) {
10055                if (compareSignatures(callerSignature,
10056                        installerPackageSetting.signatures.mSignatures)
10057                        != PackageManager.SIGNATURE_MATCH) {
10058                    throw new SecurityException(
10059                            "Caller does not have same cert as new installer package "
10060                            + installerPackageName);
10061                }
10062            }
10063
10064            // Verify: if target already has an installer package, it must
10065            // be signed with the same cert as the caller.
10066            if (targetPackageSetting.installerPackageName != null) {
10067                PackageSetting setting = mSettings.mPackages.get(
10068                        targetPackageSetting.installerPackageName);
10069                // If the currently set package isn't valid, then it's always
10070                // okay to change it.
10071                if (setting != null) {
10072                    if (compareSignatures(callerSignature,
10073                            setting.signatures.mSignatures)
10074                            != PackageManager.SIGNATURE_MATCH) {
10075                        throw new SecurityException(
10076                                "Caller does not have same cert as old installer package "
10077                                + targetPackageSetting.installerPackageName);
10078                    }
10079                }
10080            }
10081
10082            // Okay!
10083            targetPackageSetting.installerPackageName = installerPackageName;
10084            scheduleWriteSettingsLocked();
10085        }
10086    }
10087
10088    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10089        // Queue up an async operation since the package installation may take a little while.
10090        mHandler.post(new Runnable() {
10091            public void run() {
10092                mHandler.removeCallbacks(this);
10093                 // Result object to be returned
10094                PackageInstalledInfo res = new PackageInstalledInfo();
10095                res.returnCode = currentStatus;
10096                res.uid = -1;
10097                res.pkg = null;
10098                res.removedInfo = new PackageRemovedInfo();
10099                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10100                    args.doPreInstall(res.returnCode);
10101                    synchronized (mInstallLock) {
10102                        installPackageLI(args, res);
10103                    }
10104                    args.doPostInstall(res.returnCode, res.uid);
10105                }
10106
10107                // A restore should be performed at this point if (a) the install
10108                // succeeded, (b) the operation is not an update, and (c) the new
10109                // package has not opted out of backup participation.
10110                final boolean update = res.removedInfo.removedPackage != null;
10111                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10112                boolean doRestore = !update
10113                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10114
10115                // Set up the post-install work request bookkeeping.  This will be used
10116                // and cleaned up by the post-install event handling regardless of whether
10117                // there's a restore pass performed.  Token values are >= 1.
10118                int token;
10119                if (mNextInstallToken < 0) mNextInstallToken = 1;
10120                token = mNextInstallToken++;
10121
10122                PostInstallData data = new PostInstallData(args, res);
10123                mRunningInstalls.put(token, data);
10124                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10125
10126                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10127                    // Pass responsibility to the Backup Manager.  It will perform a
10128                    // restore if appropriate, then pass responsibility back to the
10129                    // Package Manager to run the post-install observer callbacks
10130                    // and broadcasts.
10131                    IBackupManager bm = IBackupManager.Stub.asInterface(
10132                            ServiceManager.getService(Context.BACKUP_SERVICE));
10133                    if (bm != null) {
10134                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10135                                + " to BM for possible restore");
10136                        try {
10137                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10138                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10139                            } else {
10140                                doRestore = false;
10141                            }
10142                        } catch (RemoteException e) {
10143                            // can't happen; the backup manager is local
10144                        } catch (Exception e) {
10145                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10146                            doRestore = false;
10147                        }
10148                    } else {
10149                        Slog.e(TAG, "Backup Manager not found!");
10150                        doRestore = false;
10151                    }
10152                }
10153
10154                if (!doRestore) {
10155                    // No restore possible, or the Backup Manager was mysteriously not
10156                    // available -- just fire the post-install work request directly.
10157                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10158                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10159                    mHandler.sendMessage(msg);
10160                }
10161            }
10162        });
10163    }
10164
10165    private abstract class HandlerParams {
10166        private static final int MAX_RETRIES = 4;
10167
10168        /**
10169         * Number of times startCopy() has been attempted and had a non-fatal
10170         * error.
10171         */
10172        private int mRetries = 0;
10173
10174        /** User handle for the user requesting the information or installation. */
10175        private final UserHandle mUser;
10176
10177        HandlerParams(UserHandle user) {
10178            mUser = user;
10179        }
10180
10181        UserHandle getUser() {
10182            return mUser;
10183        }
10184
10185        final boolean startCopy() {
10186            boolean res;
10187            try {
10188                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10189
10190                if (++mRetries > MAX_RETRIES) {
10191                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10192                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10193                    handleServiceError();
10194                    return false;
10195                } else {
10196                    handleStartCopy();
10197                    res = true;
10198                }
10199            } catch (RemoteException e) {
10200                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10201                mHandler.sendEmptyMessage(MCS_RECONNECT);
10202                res = false;
10203            }
10204            handleReturnCode();
10205            return res;
10206        }
10207
10208        final void serviceError() {
10209            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10210            handleServiceError();
10211            handleReturnCode();
10212        }
10213
10214        abstract void handleStartCopy() throws RemoteException;
10215        abstract void handleServiceError();
10216        abstract void handleReturnCode();
10217    }
10218
10219    class MeasureParams extends HandlerParams {
10220        private final PackageStats mStats;
10221        private boolean mSuccess;
10222
10223        private final IPackageStatsObserver mObserver;
10224
10225        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10226            super(new UserHandle(stats.userHandle));
10227            mObserver = observer;
10228            mStats = stats;
10229        }
10230
10231        @Override
10232        public String toString() {
10233            return "MeasureParams{"
10234                + Integer.toHexString(System.identityHashCode(this))
10235                + " " + mStats.packageName + "}";
10236        }
10237
10238        @Override
10239        void handleStartCopy() throws RemoteException {
10240            synchronized (mInstallLock) {
10241                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10242            }
10243
10244            if (mSuccess) {
10245                final boolean mounted;
10246                if (Environment.isExternalStorageEmulated()) {
10247                    mounted = true;
10248                } else {
10249                    final String status = Environment.getExternalStorageState();
10250                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10251                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10252                }
10253
10254                if (mounted) {
10255                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10256
10257                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10258                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10259
10260                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10261                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10262
10263                    // Always subtract cache size, since it's a subdirectory
10264                    mStats.externalDataSize -= mStats.externalCacheSize;
10265
10266                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10267                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10268
10269                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10270                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10271                }
10272            }
10273        }
10274
10275        @Override
10276        void handleReturnCode() {
10277            if (mObserver != null) {
10278                try {
10279                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10280                } catch (RemoteException e) {
10281                    Slog.i(TAG, "Observer no longer exists.");
10282                }
10283            }
10284        }
10285
10286        @Override
10287        void handleServiceError() {
10288            Slog.e(TAG, "Could not measure application " + mStats.packageName
10289                            + " external storage");
10290        }
10291    }
10292
10293    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10294            throws RemoteException {
10295        long result = 0;
10296        for (File path : paths) {
10297            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10298        }
10299        return result;
10300    }
10301
10302    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10303        for (File path : paths) {
10304            try {
10305                mcs.clearDirectory(path.getAbsolutePath());
10306            } catch (RemoteException e) {
10307            }
10308        }
10309    }
10310
10311    static class OriginInfo {
10312        /**
10313         * Location where install is coming from, before it has been
10314         * copied/renamed into place. This could be a single monolithic APK
10315         * file, or a cluster directory. This location may be untrusted.
10316         */
10317        final File file;
10318        final String cid;
10319
10320        /**
10321         * Flag indicating that {@link #file} or {@link #cid} has already been
10322         * staged, meaning downstream users don't need to defensively copy the
10323         * contents.
10324         */
10325        final boolean staged;
10326
10327        /**
10328         * Flag indicating that {@link #file} or {@link #cid} is an already
10329         * installed app that is being moved.
10330         */
10331        final boolean existing;
10332
10333        final String resolvedPath;
10334        final File resolvedFile;
10335
10336        static OriginInfo fromNothing() {
10337            return new OriginInfo(null, null, false, false);
10338        }
10339
10340        static OriginInfo fromUntrustedFile(File file) {
10341            return new OriginInfo(file, null, false, false);
10342        }
10343
10344        static OriginInfo fromExistingFile(File file) {
10345            return new OriginInfo(file, null, false, true);
10346        }
10347
10348        static OriginInfo fromStagedFile(File file) {
10349            return new OriginInfo(file, null, true, false);
10350        }
10351
10352        static OriginInfo fromStagedContainer(String cid) {
10353            return new OriginInfo(null, cid, true, false);
10354        }
10355
10356        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10357            this.file = file;
10358            this.cid = cid;
10359            this.staged = staged;
10360            this.existing = existing;
10361
10362            if (cid != null) {
10363                resolvedPath = PackageHelper.getSdDir(cid);
10364                resolvedFile = new File(resolvedPath);
10365            } else if (file != null) {
10366                resolvedPath = file.getAbsolutePath();
10367                resolvedFile = file;
10368            } else {
10369                resolvedPath = null;
10370                resolvedFile = null;
10371            }
10372        }
10373    }
10374
10375    class MoveInfo {
10376        final int moveId;
10377        final String fromUuid;
10378        final String toUuid;
10379        final String packageName;
10380        final String dataAppName;
10381        final int appId;
10382        final String seinfo;
10383
10384        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10385                String dataAppName, int appId, String seinfo) {
10386            this.moveId = moveId;
10387            this.fromUuid = fromUuid;
10388            this.toUuid = toUuid;
10389            this.packageName = packageName;
10390            this.dataAppName = dataAppName;
10391            this.appId = appId;
10392            this.seinfo = seinfo;
10393        }
10394    }
10395
10396    class InstallParams extends HandlerParams {
10397        final OriginInfo origin;
10398        final MoveInfo move;
10399        final IPackageInstallObserver2 observer;
10400        int installFlags;
10401        final String installerPackageName;
10402        final String volumeUuid;
10403        final VerificationParams verificationParams;
10404        private InstallArgs mArgs;
10405        private int mRet;
10406        final String packageAbiOverride;
10407        final String[] grantedRuntimePermissions;
10408
10409
10410        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10411                int installFlags, String installerPackageName, String volumeUuid,
10412                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10413                String[] grantedPermissions) {
10414            super(user);
10415            this.origin = origin;
10416            this.move = move;
10417            this.observer = observer;
10418            this.installFlags = installFlags;
10419            this.installerPackageName = installerPackageName;
10420            this.volumeUuid = volumeUuid;
10421            this.verificationParams = verificationParams;
10422            this.packageAbiOverride = packageAbiOverride;
10423            this.grantedRuntimePermissions = grantedPermissions;
10424        }
10425
10426        @Override
10427        public String toString() {
10428            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10429                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10430        }
10431
10432        public ManifestDigest getManifestDigest() {
10433            if (verificationParams == null) {
10434                return null;
10435            }
10436            return verificationParams.getManifestDigest();
10437        }
10438
10439        private int installLocationPolicy(PackageInfoLite pkgLite) {
10440            String packageName = pkgLite.packageName;
10441            int installLocation = pkgLite.installLocation;
10442            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10443            // reader
10444            synchronized (mPackages) {
10445                PackageParser.Package pkg = mPackages.get(packageName);
10446                if (pkg != null) {
10447                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10448                        // Check for downgrading.
10449                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10450                            try {
10451                                checkDowngrade(pkg, pkgLite);
10452                            } catch (PackageManagerException e) {
10453                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10454                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10455                            }
10456                        }
10457                        // Check for updated system application.
10458                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10459                            if (onSd) {
10460                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10461                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10462                            }
10463                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10464                        } else {
10465                            if (onSd) {
10466                                // Install flag overrides everything.
10467                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10468                            }
10469                            // If current upgrade specifies particular preference
10470                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10471                                // Application explicitly specified internal.
10472                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10473                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10474                                // App explictly prefers external. Let policy decide
10475                            } else {
10476                                // Prefer previous location
10477                                if (isExternal(pkg)) {
10478                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10479                                }
10480                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10481                            }
10482                        }
10483                    } else {
10484                        // Invalid install. Return error code
10485                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10486                    }
10487                }
10488            }
10489            // All the special cases have been taken care of.
10490            // Return result based on recommended install location.
10491            if (onSd) {
10492                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10493            }
10494            return pkgLite.recommendedInstallLocation;
10495        }
10496
10497        /*
10498         * Invoke remote method to get package information and install
10499         * location values. Override install location based on default
10500         * policy if needed and then create install arguments based
10501         * on the install location.
10502         */
10503        public void handleStartCopy() throws RemoteException {
10504            int ret = PackageManager.INSTALL_SUCCEEDED;
10505
10506            // If we're already staged, we've firmly committed to an install location
10507            if (origin.staged) {
10508                if (origin.file != null) {
10509                    installFlags |= PackageManager.INSTALL_INTERNAL;
10510                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10511                } else if (origin.cid != null) {
10512                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10513                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10514                } else {
10515                    throw new IllegalStateException("Invalid stage location");
10516                }
10517            }
10518
10519            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10520            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10521
10522            PackageInfoLite pkgLite = null;
10523
10524            if (onInt && onSd) {
10525                // Check if both bits are set.
10526                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10527                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10528            } else {
10529                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10530                        packageAbiOverride);
10531
10532                /*
10533                 * If we have too little free space, try to free cache
10534                 * before giving up.
10535                 */
10536                if (!origin.staged && pkgLite.recommendedInstallLocation
10537                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10538                    // TODO: focus freeing disk space on the target device
10539                    final StorageManager storage = StorageManager.from(mContext);
10540                    final long lowThreshold = storage.getStorageLowBytes(
10541                            Environment.getDataDirectory());
10542
10543                    final long sizeBytes = mContainerService.calculateInstalledSize(
10544                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10545
10546                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10547                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10548                                installFlags, packageAbiOverride);
10549                    }
10550
10551                    /*
10552                     * The cache free must have deleted the file we
10553                     * downloaded to install.
10554                     *
10555                     * TODO: fix the "freeCache" call to not delete
10556                     *       the file we care about.
10557                     */
10558                    if (pkgLite.recommendedInstallLocation
10559                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10560                        pkgLite.recommendedInstallLocation
10561                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10562                    }
10563                }
10564            }
10565
10566            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10567                int loc = pkgLite.recommendedInstallLocation;
10568                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10569                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10570                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10571                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10572                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10573                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10574                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10575                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10576                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10577                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10578                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10579                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10580                } else {
10581                    // Override with defaults if needed.
10582                    loc = installLocationPolicy(pkgLite);
10583                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10584                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10585                    } else if (!onSd && !onInt) {
10586                        // Override install location with flags
10587                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10588                            // Set the flag to install on external media.
10589                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10590                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10591                        } else {
10592                            // Make sure the flag for installing on external
10593                            // media is unset
10594                            installFlags |= PackageManager.INSTALL_INTERNAL;
10595                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10596                        }
10597                    }
10598                }
10599            }
10600
10601            final InstallArgs args = createInstallArgs(this);
10602            mArgs = args;
10603
10604            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10605                 /*
10606                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10607                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10608                 */
10609                int userIdentifier = getUser().getIdentifier();
10610                if (userIdentifier == UserHandle.USER_ALL
10611                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10612                    userIdentifier = UserHandle.USER_OWNER;
10613                }
10614
10615                /*
10616                 * Determine if we have any installed package verifiers. If we
10617                 * do, then we'll defer to them to verify the packages.
10618                 */
10619                final int requiredUid = mRequiredVerifierPackage == null ? -1
10620                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10621                if (!origin.existing && requiredUid != -1
10622                        && isVerificationEnabled(userIdentifier, installFlags)) {
10623                    final Intent verification = new Intent(
10624                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10625                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10626                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10627                            PACKAGE_MIME_TYPE);
10628                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10629
10630                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10631                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10632                            0 /* TODO: Which userId? */);
10633
10634                    if (DEBUG_VERIFY) {
10635                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10636                                + verification.toString() + " with " + pkgLite.verifiers.length
10637                                + " optional verifiers");
10638                    }
10639
10640                    final int verificationId = mPendingVerificationToken++;
10641
10642                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10643
10644                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10645                            installerPackageName);
10646
10647                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10648                            installFlags);
10649
10650                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10651                            pkgLite.packageName);
10652
10653                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10654                            pkgLite.versionCode);
10655
10656                    if (verificationParams != null) {
10657                        if (verificationParams.getVerificationURI() != null) {
10658                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10659                                 verificationParams.getVerificationURI());
10660                        }
10661                        if (verificationParams.getOriginatingURI() != null) {
10662                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10663                                  verificationParams.getOriginatingURI());
10664                        }
10665                        if (verificationParams.getReferrer() != null) {
10666                            verification.putExtra(Intent.EXTRA_REFERRER,
10667                                  verificationParams.getReferrer());
10668                        }
10669                        if (verificationParams.getOriginatingUid() >= 0) {
10670                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10671                                  verificationParams.getOriginatingUid());
10672                        }
10673                        if (verificationParams.getInstallerUid() >= 0) {
10674                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10675                                  verificationParams.getInstallerUid());
10676                        }
10677                    }
10678
10679                    final PackageVerificationState verificationState = new PackageVerificationState(
10680                            requiredUid, args);
10681
10682                    mPendingVerification.append(verificationId, verificationState);
10683
10684                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10685                            receivers, verificationState);
10686
10687                    // Apps installed for "all" users use the device owner to verify the app
10688                    UserHandle verifierUser = getUser();
10689                    if (verifierUser == UserHandle.ALL) {
10690                        verifierUser = UserHandle.OWNER;
10691                    }
10692
10693                    /*
10694                     * If any sufficient verifiers were listed in the package
10695                     * manifest, attempt to ask them.
10696                     */
10697                    if (sufficientVerifiers != null) {
10698                        final int N = sufficientVerifiers.size();
10699                        if (N == 0) {
10700                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10701                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10702                        } else {
10703                            for (int i = 0; i < N; i++) {
10704                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10705
10706                                final Intent sufficientIntent = new Intent(verification);
10707                                sufficientIntent.setComponent(verifierComponent);
10708                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10709                            }
10710                        }
10711                    }
10712
10713                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10714                            mRequiredVerifierPackage, receivers);
10715                    if (ret == PackageManager.INSTALL_SUCCEEDED
10716                            && mRequiredVerifierPackage != null) {
10717                        /*
10718                         * Send the intent to the required verification agent,
10719                         * but only start the verification timeout after the
10720                         * target BroadcastReceivers have run.
10721                         */
10722                        verification.setComponent(requiredVerifierComponent);
10723                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10724                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10725                                new BroadcastReceiver() {
10726                                    @Override
10727                                    public void onReceive(Context context, Intent intent) {
10728                                        final Message msg = mHandler
10729                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10730                                        msg.arg1 = verificationId;
10731                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10732                                    }
10733                                }, null, 0, null, null);
10734
10735                        /*
10736                         * We don't want the copy to proceed until verification
10737                         * succeeds, so null out this field.
10738                         */
10739                        mArgs = null;
10740                    }
10741                } else {
10742                    /*
10743                     * No package verification is enabled, so immediately start
10744                     * the remote call to initiate copy using temporary file.
10745                     */
10746                    ret = args.copyApk(mContainerService, true);
10747                }
10748            }
10749
10750            mRet = ret;
10751        }
10752
10753        @Override
10754        void handleReturnCode() {
10755            // If mArgs is null, then MCS couldn't be reached. When it
10756            // reconnects, it will try again to install. At that point, this
10757            // will succeed.
10758            if (mArgs != null) {
10759                processPendingInstall(mArgs, mRet);
10760            }
10761        }
10762
10763        @Override
10764        void handleServiceError() {
10765            mArgs = createInstallArgs(this);
10766            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10767        }
10768
10769        public boolean isForwardLocked() {
10770            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10771        }
10772    }
10773
10774    /**
10775     * Used during creation of InstallArgs
10776     *
10777     * @param installFlags package installation flags
10778     * @return true if should be installed on external storage
10779     */
10780    private static boolean installOnExternalAsec(int installFlags) {
10781        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10782            return false;
10783        }
10784        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10785            return true;
10786        }
10787        return false;
10788    }
10789
10790    /**
10791     * Used during creation of InstallArgs
10792     *
10793     * @param installFlags package installation flags
10794     * @return true if should be installed as forward locked
10795     */
10796    private static boolean installForwardLocked(int installFlags) {
10797        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10798    }
10799
10800    private InstallArgs createInstallArgs(InstallParams params) {
10801        if (params.move != null) {
10802            return new MoveInstallArgs(params);
10803        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10804            return new AsecInstallArgs(params);
10805        } else {
10806            return new FileInstallArgs(params);
10807        }
10808    }
10809
10810    /**
10811     * Create args that describe an existing installed package. Typically used
10812     * when cleaning up old installs, or used as a move source.
10813     */
10814    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10815            String resourcePath, String[] instructionSets) {
10816        final boolean isInAsec;
10817        if (installOnExternalAsec(installFlags)) {
10818            /* Apps on SD card are always in ASEC containers. */
10819            isInAsec = true;
10820        } else if (installForwardLocked(installFlags)
10821                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10822            /*
10823             * Forward-locked apps are only in ASEC containers if they're the
10824             * new style
10825             */
10826            isInAsec = true;
10827        } else {
10828            isInAsec = false;
10829        }
10830
10831        if (isInAsec) {
10832            return new AsecInstallArgs(codePath, instructionSets,
10833                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10834        } else {
10835            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10836        }
10837    }
10838
10839    static abstract class InstallArgs {
10840        /** @see InstallParams#origin */
10841        final OriginInfo origin;
10842        /** @see InstallParams#move */
10843        final MoveInfo move;
10844
10845        final IPackageInstallObserver2 observer;
10846        // Always refers to PackageManager flags only
10847        final int installFlags;
10848        final String installerPackageName;
10849        final String volumeUuid;
10850        final ManifestDigest manifestDigest;
10851        final UserHandle user;
10852        final String abiOverride;
10853        final String[] installGrantPermissions;
10854
10855        // The list of instruction sets supported by this app. This is currently
10856        // only used during the rmdex() phase to clean up resources. We can get rid of this
10857        // if we move dex files under the common app path.
10858        /* nullable */ String[] instructionSets;
10859
10860        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10861                int installFlags, String installerPackageName, String volumeUuid,
10862                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10863                String abiOverride, String[] installGrantPermissions) {
10864            this.origin = origin;
10865            this.move = move;
10866            this.installFlags = installFlags;
10867            this.observer = observer;
10868            this.installerPackageName = installerPackageName;
10869            this.volumeUuid = volumeUuid;
10870            this.manifestDigest = manifestDigest;
10871            this.user = user;
10872            this.instructionSets = instructionSets;
10873            this.abiOverride = abiOverride;
10874            this.installGrantPermissions = installGrantPermissions;
10875        }
10876
10877        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10878        abstract int doPreInstall(int status);
10879
10880        /**
10881         * Rename package into final resting place. All paths on the given
10882         * scanned package should be updated to reflect the rename.
10883         */
10884        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10885        abstract int doPostInstall(int status, int uid);
10886
10887        /** @see PackageSettingBase#codePathString */
10888        abstract String getCodePath();
10889        /** @see PackageSettingBase#resourcePathString */
10890        abstract String getResourcePath();
10891
10892        // Need installer lock especially for dex file removal.
10893        abstract void cleanUpResourcesLI();
10894        abstract boolean doPostDeleteLI(boolean delete);
10895
10896        /**
10897         * Called before the source arguments are copied. This is used mostly
10898         * for MoveParams when it needs to read the source file to put it in the
10899         * destination.
10900         */
10901        int doPreCopy() {
10902            return PackageManager.INSTALL_SUCCEEDED;
10903        }
10904
10905        /**
10906         * Called after the source arguments are copied. This is used mostly for
10907         * MoveParams when it needs to read the source file to put it in the
10908         * destination.
10909         *
10910         * @return
10911         */
10912        int doPostCopy(int uid) {
10913            return PackageManager.INSTALL_SUCCEEDED;
10914        }
10915
10916        protected boolean isFwdLocked() {
10917            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10918        }
10919
10920        protected boolean isExternalAsec() {
10921            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10922        }
10923
10924        UserHandle getUser() {
10925            return user;
10926        }
10927    }
10928
10929    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10930        if (!allCodePaths.isEmpty()) {
10931            if (instructionSets == null) {
10932                throw new IllegalStateException("instructionSet == null");
10933            }
10934            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10935            for (String codePath : allCodePaths) {
10936                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10937                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10938                    if (retCode < 0) {
10939                        Slog.w(TAG, "Couldn't remove dex file for package: "
10940                                + " at location " + codePath + ", retcode=" + retCode);
10941                        // we don't consider this to be a failure of the core package deletion
10942                    }
10943                }
10944            }
10945        }
10946    }
10947
10948    /**
10949     * Logic to handle installation of non-ASEC applications, including copying
10950     * and renaming logic.
10951     */
10952    class FileInstallArgs extends InstallArgs {
10953        private File codeFile;
10954        private File resourceFile;
10955
10956        // Example topology:
10957        // /data/app/com.example/base.apk
10958        // /data/app/com.example/split_foo.apk
10959        // /data/app/com.example/lib/arm/libfoo.so
10960        // /data/app/com.example/lib/arm64/libfoo.so
10961        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10962
10963        /** New install */
10964        FileInstallArgs(InstallParams params) {
10965            super(params.origin, params.move, params.observer, params.installFlags,
10966                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10967                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10968                    params.grantedRuntimePermissions);
10969            if (isFwdLocked()) {
10970                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10971            }
10972        }
10973
10974        /** Existing install */
10975        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10976            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10977                    null, null);
10978            this.codeFile = (codePath != null) ? new File(codePath) : null;
10979            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10980        }
10981
10982        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10983            if (origin.staged) {
10984                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10985                codeFile = origin.file;
10986                resourceFile = origin.file;
10987                return PackageManager.INSTALL_SUCCEEDED;
10988            }
10989
10990            try {
10991                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10992                codeFile = tempDir;
10993                resourceFile = tempDir;
10994            } catch (IOException e) {
10995                Slog.w(TAG, "Failed to create copy file: " + e);
10996                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10997            }
10998
10999            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11000                @Override
11001                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11002                    if (!FileUtils.isValidExtFilename(name)) {
11003                        throw new IllegalArgumentException("Invalid filename: " + name);
11004                    }
11005                    try {
11006                        final File file = new File(codeFile, name);
11007                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11008                                O_RDWR | O_CREAT, 0644);
11009                        Os.chmod(file.getAbsolutePath(), 0644);
11010                        return new ParcelFileDescriptor(fd);
11011                    } catch (ErrnoException e) {
11012                        throw new RemoteException("Failed to open: " + e.getMessage());
11013                    }
11014                }
11015            };
11016
11017            int ret = PackageManager.INSTALL_SUCCEEDED;
11018            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11019            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11020                Slog.e(TAG, "Failed to copy package");
11021                return ret;
11022            }
11023
11024            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11025            NativeLibraryHelper.Handle handle = null;
11026            try {
11027                handle = NativeLibraryHelper.Handle.create(codeFile);
11028                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11029                        abiOverride);
11030            } catch (IOException e) {
11031                Slog.e(TAG, "Copying native libraries failed", e);
11032                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11033            } finally {
11034                IoUtils.closeQuietly(handle);
11035            }
11036
11037            return ret;
11038        }
11039
11040        int doPreInstall(int status) {
11041            if (status != PackageManager.INSTALL_SUCCEEDED) {
11042                cleanUp();
11043            }
11044            return status;
11045        }
11046
11047        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11048            if (status != PackageManager.INSTALL_SUCCEEDED) {
11049                cleanUp();
11050                return false;
11051            }
11052
11053            final File targetDir = codeFile.getParentFile();
11054            final File beforeCodeFile = codeFile;
11055            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11056
11057            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11058            try {
11059                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11060            } catch (ErrnoException e) {
11061                Slog.w(TAG, "Failed to rename", e);
11062                return false;
11063            }
11064
11065            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11066                Slog.w(TAG, "Failed to restorecon");
11067                return false;
11068            }
11069
11070            // Reflect the rename internally
11071            codeFile = afterCodeFile;
11072            resourceFile = afterCodeFile;
11073
11074            // Reflect the rename in scanned details
11075            pkg.codePath = afterCodeFile.getAbsolutePath();
11076            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11077                    pkg.baseCodePath);
11078            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11079                    pkg.splitCodePaths);
11080
11081            // Reflect the rename in app info
11082            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11083            pkg.applicationInfo.setCodePath(pkg.codePath);
11084            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11085            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11086            pkg.applicationInfo.setResourcePath(pkg.codePath);
11087            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11088            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11089
11090            return true;
11091        }
11092
11093        int doPostInstall(int status, int uid) {
11094            if (status != PackageManager.INSTALL_SUCCEEDED) {
11095                cleanUp();
11096            }
11097            return status;
11098        }
11099
11100        @Override
11101        String getCodePath() {
11102            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11103        }
11104
11105        @Override
11106        String getResourcePath() {
11107            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11108        }
11109
11110        private boolean cleanUp() {
11111            if (codeFile == null || !codeFile.exists()) {
11112                return false;
11113            }
11114
11115            if (codeFile.isDirectory()) {
11116                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11117            } else {
11118                codeFile.delete();
11119            }
11120
11121            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11122                resourceFile.delete();
11123            }
11124
11125            return true;
11126        }
11127
11128        void cleanUpResourcesLI() {
11129            // Try enumerating all code paths before deleting
11130            List<String> allCodePaths = Collections.EMPTY_LIST;
11131            if (codeFile != null && codeFile.exists()) {
11132                try {
11133                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11134                    allCodePaths = pkg.getAllCodePaths();
11135                } catch (PackageParserException e) {
11136                    // Ignored; we tried our best
11137                }
11138            }
11139
11140            cleanUp();
11141            removeDexFiles(allCodePaths, instructionSets);
11142        }
11143
11144        boolean doPostDeleteLI(boolean delete) {
11145            // XXX err, shouldn't we respect the delete flag?
11146            cleanUpResourcesLI();
11147            return true;
11148        }
11149    }
11150
11151    private boolean isAsecExternal(String cid) {
11152        final String asecPath = PackageHelper.getSdFilesystem(cid);
11153        return !asecPath.startsWith(mAsecInternalPath);
11154    }
11155
11156    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11157            PackageManagerException {
11158        if (copyRet < 0) {
11159            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11160                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11161                throw new PackageManagerException(copyRet, message);
11162            }
11163        }
11164    }
11165
11166    /**
11167     * Extract the MountService "container ID" from the full code path of an
11168     * .apk.
11169     */
11170    static String cidFromCodePath(String fullCodePath) {
11171        int eidx = fullCodePath.lastIndexOf("/");
11172        String subStr1 = fullCodePath.substring(0, eidx);
11173        int sidx = subStr1.lastIndexOf("/");
11174        return subStr1.substring(sidx+1, eidx);
11175    }
11176
11177    /**
11178     * Logic to handle installation of ASEC applications, including copying and
11179     * renaming logic.
11180     */
11181    class AsecInstallArgs extends InstallArgs {
11182        static final String RES_FILE_NAME = "pkg.apk";
11183        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11184
11185        String cid;
11186        String packagePath;
11187        String resourcePath;
11188
11189        /** New install */
11190        AsecInstallArgs(InstallParams params) {
11191            super(params.origin, params.move, params.observer, params.installFlags,
11192                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11193                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11194                    params.grantedRuntimePermissions);
11195        }
11196
11197        /** Existing install */
11198        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11199                        boolean isExternal, boolean isForwardLocked) {
11200            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11201                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11202                    instructionSets, null, null);
11203            // Hackily pretend we're still looking at a full code path
11204            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11205                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11206            }
11207
11208            // Extract cid from fullCodePath
11209            int eidx = fullCodePath.lastIndexOf("/");
11210            String subStr1 = fullCodePath.substring(0, eidx);
11211            int sidx = subStr1.lastIndexOf("/");
11212            cid = subStr1.substring(sidx+1, eidx);
11213            setMountPath(subStr1);
11214        }
11215
11216        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11217            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11218                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11219                    instructionSets, null, null);
11220            this.cid = cid;
11221            setMountPath(PackageHelper.getSdDir(cid));
11222        }
11223
11224        void createCopyFile() {
11225            cid = mInstallerService.allocateExternalStageCidLegacy();
11226        }
11227
11228        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11229            if (origin.staged) {
11230                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11231                cid = origin.cid;
11232                setMountPath(PackageHelper.getSdDir(cid));
11233                return PackageManager.INSTALL_SUCCEEDED;
11234            }
11235
11236            if (temp) {
11237                createCopyFile();
11238            } else {
11239                /*
11240                 * Pre-emptively destroy the container since it's destroyed if
11241                 * copying fails due to it existing anyway.
11242                 */
11243                PackageHelper.destroySdDir(cid);
11244            }
11245
11246            final String newMountPath = imcs.copyPackageToContainer(
11247                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11248                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11249
11250            if (newMountPath != null) {
11251                setMountPath(newMountPath);
11252                return PackageManager.INSTALL_SUCCEEDED;
11253            } else {
11254                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11255            }
11256        }
11257
11258        @Override
11259        String getCodePath() {
11260            return packagePath;
11261        }
11262
11263        @Override
11264        String getResourcePath() {
11265            return resourcePath;
11266        }
11267
11268        int doPreInstall(int status) {
11269            if (status != PackageManager.INSTALL_SUCCEEDED) {
11270                // Destroy container
11271                PackageHelper.destroySdDir(cid);
11272            } else {
11273                boolean mounted = PackageHelper.isContainerMounted(cid);
11274                if (!mounted) {
11275                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11276                            Process.SYSTEM_UID);
11277                    if (newMountPath != null) {
11278                        setMountPath(newMountPath);
11279                    } else {
11280                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11281                    }
11282                }
11283            }
11284            return status;
11285        }
11286
11287        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11288            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11289            String newMountPath = null;
11290            if (PackageHelper.isContainerMounted(cid)) {
11291                // Unmount the container
11292                if (!PackageHelper.unMountSdDir(cid)) {
11293                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11294                    return false;
11295                }
11296            }
11297            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11298                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11299                        " which might be stale. Will try to clean up.");
11300                // Clean up the stale container and proceed to recreate.
11301                if (!PackageHelper.destroySdDir(newCacheId)) {
11302                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11303                    return false;
11304                }
11305                // Successfully cleaned up stale container. Try to rename again.
11306                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11307                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11308                            + " inspite of cleaning it up.");
11309                    return false;
11310                }
11311            }
11312            if (!PackageHelper.isContainerMounted(newCacheId)) {
11313                Slog.w(TAG, "Mounting container " + newCacheId);
11314                newMountPath = PackageHelper.mountSdDir(newCacheId,
11315                        getEncryptKey(), Process.SYSTEM_UID);
11316            } else {
11317                newMountPath = PackageHelper.getSdDir(newCacheId);
11318            }
11319            if (newMountPath == null) {
11320                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11321                return false;
11322            }
11323            Log.i(TAG, "Succesfully renamed " + cid +
11324                    " to " + newCacheId +
11325                    " at new path: " + newMountPath);
11326            cid = newCacheId;
11327
11328            final File beforeCodeFile = new File(packagePath);
11329            setMountPath(newMountPath);
11330            final File afterCodeFile = new File(packagePath);
11331
11332            // Reflect the rename in scanned details
11333            pkg.codePath = afterCodeFile.getAbsolutePath();
11334            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11335                    pkg.baseCodePath);
11336            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11337                    pkg.splitCodePaths);
11338
11339            // Reflect the rename in app info
11340            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11341            pkg.applicationInfo.setCodePath(pkg.codePath);
11342            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11343            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11344            pkg.applicationInfo.setResourcePath(pkg.codePath);
11345            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11346            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11347
11348            return true;
11349        }
11350
11351        private void setMountPath(String mountPath) {
11352            final File mountFile = new File(mountPath);
11353
11354            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11355            if (monolithicFile.exists()) {
11356                packagePath = monolithicFile.getAbsolutePath();
11357                if (isFwdLocked()) {
11358                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11359                } else {
11360                    resourcePath = packagePath;
11361                }
11362            } else {
11363                packagePath = mountFile.getAbsolutePath();
11364                resourcePath = packagePath;
11365            }
11366        }
11367
11368        int doPostInstall(int status, int uid) {
11369            if (status != PackageManager.INSTALL_SUCCEEDED) {
11370                cleanUp();
11371            } else {
11372                final int groupOwner;
11373                final String protectedFile;
11374                if (isFwdLocked()) {
11375                    groupOwner = UserHandle.getSharedAppGid(uid);
11376                    protectedFile = RES_FILE_NAME;
11377                } else {
11378                    groupOwner = -1;
11379                    protectedFile = null;
11380                }
11381
11382                if (uid < Process.FIRST_APPLICATION_UID
11383                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11384                    Slog.e(TAG, "Failed to finalize " + cid);
11385                    PackageHelper.destroySdDir(cid);
11386                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11387                }
11388
11389                boolean mounted = PackageHelper.isContainerMounted(cid);
11390                if (!mounted) {
11391                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11392                }
11393            }
11394            return status;
11395        }
11396
11397        private void cleanUp() {
11398            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11399
11400            // Destroy secure container
11401            PackageHelper.destroySdDir(cid);
11402        }
11403
11404        private List<String> getAllCodePaths() {
11405            final File codeFile = new File(getCodePath());
11406            if (codeFile != null && codeFile.exists()) {
11407                try {
11408                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11409                    return pkg.getAllCodePaths();
11410                } catch (PackageParserException e) {
11411                    // Ignored; we tried our best
11412                }
11413            }
11414            return Collections.EMPTY_LIST;
11415        }
11416
11417        void cleanUpResourcesLI() {
11418            // Enumerate all code paths before deleting
11419            cleanUpResourcesLI(getAllCodePaths());
11420        }
11421
11422        private void cleanUpResourcesLI(List<String> allCodePaths) {
11423            cleanUp();
11424            removeDexFiles(allCodePaths, instructionSets);
11425        }
11426
11427        String getPackageName() {
11428            return getAsecPackageName(cid);
11429        }
11430
11431        boolean doPostDeleteLI(boolean delete) {
11432            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11433            final List<String> allCodePaths = getAllCodePaths();
11434            boolean mounted = PackageHelper.isContainerMounted(cid);
11435            if (mounted) {
11436                // Unmount first
11437                if (PackageHelper.unMountSdDir(cid)) {
11438                    mounted = false;
11439                }
11440            }
11441            if (!mounted && delete) {
11442                cleanUpResourcesLI(allCodePaths);
11443            }
11444            return !mounted;
11445        }
11446
11447        @Override
11448        int doPreCopy() {
11449            if (isFwdLocked()) {
11450                if (!PackageHelper.fixSdPermissions(cid,
11451                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11452                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11453                }
11454            }
11455
11456            return PackageManager.INSTALL_SUCCEEDED;
11457        }
11458
11459        @Override
11460        int doPostCopy(int uid) {
11461            if (isFwdLocked()) {
11462                if (uid < Process.FIRST_APPLICATION_UID
11463                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11464                                RES_FILE_NAME)) {
11465                    Slog.e(TAG, "Failed to finalize " + cid);
11466                    PackageHelper.destroySdDir(cid);
11467                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11468                }
11469            }
11470
11471            return PackageManager.INSTALL_SUCCEEDED;
11472        }
11473    }
11474
11475    /**
11476     * Logic to handle movement of existing installed applications.
11477     */
11478    class MoveInstallArgs extends InstallArgs {
11479        private File codeFile;
11480        private File resourceFile;
11481
11482        /** New install */
11483        MoveInstallArgs(InstallParams params) {
11484            super(params.origin, params.move, params.observer, params.installFlags,
11485                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11486                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11487                    params.grantedRuntimePermissions);
11488        }
11489
11490        int copyApk(IMediaContainerService imcs, boolean temp) {
11491            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11492                    + move.fromUuid + " to " + move.toUuid);
11493            synchronized (mInstaller) {
11494                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11495                        move.dataAppName, move.appId, move.seinfo) != 0) {
11496                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11497                }
11498            }
11499
11500            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11501            resourceFile = codeFile;
11502            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11503
11504            return PackageManager.INSTALL_SUCCEEDED;
11505        }
11506
11507        int doPreInstall(int status) {
11508            if (status != PackageManager.INSTALL_SUCCEEDED) {
11509                cleanUp(move.toUuid);
11510            }
11511            return status;
11512        }
11513
11514        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11515            if (status != PackageManager.INSTALL_SUCCEEDED) {
11516                cleanUp(move.toUuid);
11517                return false;
11518            }
11519
11520            // Reflect the move in app info
11521            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11522            pkg.applicationInfo.setCodePath(pkg.codePath);
11523            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11524            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11525            pkg.applicationInfo.setResourcePath(pkg.codePath);
11526            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11527            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11528
11529            return true;
11530        }
11531
11532        int doPostInstall(int status, int uid) {
11533            if (status == PackageManager.INSTALL_SUCCEEDED) {
11534                cleanUp(move.fromUuid);
11535            } else {
11536                cleanUp(move.toUuid);
11537            }
11538            return status;
11539        }
11540
11541        @Override
11542        String getCodePath() {
11543            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11544        }
11545
11546        @Override
11547        String getResourcePath() {
11548            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11549        }
11550
11551        private boolean cleanUp(String volumeUuid) {
11552            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11553                    move.dataAppName);
11554            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11555            synchronized (mInstallLock) {
11556                // Clean up both app data and code
11557                removeDataDirsLI(volumeUuid, move.packageName);
11558                if (codeFile.isDirectory()) {
11559                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11560                } else {
11561                    codeFile.delete();
11562                }
11563            }
11564            return true;
11565        }
11566
11567        void cleanUpResourcesLI() {
11568            throw new UnsupportedOperationException();
11569        }
11570
11571        boolean doPostDeleteLI(boolean delete) {
11572            throw new UnsupportedOperationException();
11573        }
11574    }
11575
11576    static String getAsecPackageName(String packageCid) {
11577        int idx = packageCid.lastIndexOf("-");
11578        if (idx == -1) {
11579            return packageCid;
11580        }
11581        return packageCid.substring(0, idx);
11582    }
11583
11584    // Utility method used to create code paths based on package name and available index.
11585    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11586        String idxStr = "";
11587        int idx = 1;
11588        // Fall back to default value of idx=1 if prefix is not
11589        // part of oldCodePath
11590        if (oldCodePath != null) {
11591            String subStr = oldCodePath;
11592            // Drop the suffix right away
11593            if (suffix != null && subStr.endsWith(suffix)) {
11594                subStr = subStr.substring(0, subStr.length() - suffix.length());
11595            }
11596            // If oldCodePath already contains prefix find out the
11597            // ending index to either increment or decrement.
11598            int sidx = subStr.lastIndexOf(prefix);
11599            if (sidx != -1) {
11600                subStr = subStr.substring(sidx + prefix.length());
11601                if (subStr != null) {
11602                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11603                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11604                    }
11605                    try {
11606                        idx = Integer.parseInt(subStr);
11607                        if (idx <= 1) {
11608                            idx++;
11609                        } else {
11610                            idx--;
11611                        }
11612                    } catch(NumberFormatException e) {
11613                    }
11614                }
11615            }
11616        }
11617        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11618        return prefix + idxStr;
11619    }
11620
11621    private File getNextCodePath(File targetDir, String packageName) {
11622        int suffix = 1;
11623        File result;
11624        do {
11625            result = new File(targetDir, packageName + "-" + suffix);
11626            suffix++;
11627        } while (result.exists());
11628        return result;
11629    }
11630
11631    // Utility method that returns the relative package path with respect
11632    // to the installation directory. Like say for /data/data/com.test-1.apk
11633    // string com.test-1 is returned.
11634    static String deriveCodePathName(String codePath) {
11635        if (codePath == null) {
11636            return null;
11637        }
11638        final File codeFile = new File(codePath);
11639        final String name = codeFile.getName();
11640        if (codeFile.isDirectory()) {
11641            return name;
11642        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11643            final int lastDot = name.lastIndexOf('.');
11644            return name.substring(0, lastDot);
11645        } else {
11646            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11647            return null;
11648        }
11649    }
11650
11651    class PackageInstalledInfo {
11652        String name;
11653        int uid;
11654        // The set of users that originally had this package installed.
11655        int[] origUsers;
11656        // The set of users that now have this package installed.
11657        int[] newUsers;
11658        PackageParser.Package pkg;
11659        int returnCode;
11660        String returnMsg;
11661        PackageRemovedInfo removedInfo;
11662
11663        public void setError(int code, String msg) {
11664            returnCode = code;
11665            returnMsg = msg;
11666            Slog.w(TAG, msg);
11667        }
11668
11669        public void setError(String msg, PackageParserException e) {
11670            returnCode = e.error;
11671            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11672            Slog.w(TAG, msg, e);
11673        }
11674
11675        public void setError(String msg, PackageManagerException e) {
11676            returnCode = e.error;
11677            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11678            Slog.w(TAG, msg, e);
11679        }
11680
11681        // In some error cases we want to convey more info back to the observer
11682        String origPackage;
11683        String origPermission;
11684    }
11685
11686    /*
11687     * Install a non-existing package.
11688     */
11689    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11690            UserHandle user, String installerPackageName, String volumeUuid,
11691            PackageInstalledInfo res) {
11692        // Remember this for later, in case we need to rollback this install
11693        String pkgName = pkg.packageName;
11694
11695        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11696        final boolean dataDirExists = Environment
11697                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11698        synchronized(mPackages) {
11699            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11700                // A package with the same name is already installed, though
11701                // it has been renamed to an older name.  The package we
11702                // are trying to install should be installed as an update to
11703                // the existing one, but that has not been requested, so bail.
11704                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11705                        + " without first uninstalling package running as "
11706                        + mSettings.mRenamedPackages.get(pkgName));
11707                return;
11708            }
11709            if (mPackages.containsKey(pkgName)) {
11710                // Don't allow installation over an existing package with the same name.
11711                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11712                        + " without first uninstalling.");
11713                return;
11714            }
11715        }
11716
11717        try {
11718            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11719                    System.currentTimeMillis(), user);
11720
11721            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11722            // delete the partially installed application. the data directory will have to be
11723            // restored if it was already existing
11724            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11725                // remove package from internal structures.  Note that we want deletePackageX to
11726                // delete the package data and cache directories that it created in
11727                // scanPackageLocked, unless those directories existed before we even tried to
11728                // install.
11729                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11730                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11731                                res.removedInfo, true);
11732            }
11733
11734        } catch (PackageManagerException e) {
11735            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11736        }
11737    }
11738
11739    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11740        // Can't rotate keys during boot or if sharedUser.
11741        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11742                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11743            return false;
11744        }
11745        // app is using upgradeKeySets; make sure all are valid
11746        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11747        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11748        for (int i = 0; i < upgradeKeySets.length; i++) {
11749            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11750                Slog.wtf(TAG, "Package "
11751                         + (oldPs.name != null ? oldPs.name : "<null>")
11752                         + " contains upgrade-key-set reference to unknown key-set: "
11753                         + upgradeKeySets[i]
11754                         + " reverting to signatures check.");
11755                return false;
11756            }
11757        }
11758        return true;
11759    }
11760
11761    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11762        // Upgrade keysets are being used.  Determine if new package has a superset of the
11763        // required keys.
11764        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11765        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11766        for (int i = 0; i < upgradeKeySets.length; i++) {
11767            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11768            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11769                return true;
11770            }
11771        }
11772        return false;
11773    }
11774
11775    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11776            UserHandle user, String installerPackageName, String volumeUuid,
11777            PackageInstalledInfo res) {
11778        final PackageParser.Package oldPackage;
11779        final String pkgName = pkg.packageName;
11780        final int[] allUsers;
11781        final boolean[] perUserInstalled;
11782
11783        // First find the old package info and check signatures
11784        synchronized(mPackages) {
11785            oldPackage = mPackages.get(pkgName);
11786            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11787            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11788            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11789                if(!checkUpgradeKeySetLP(ps, pkg)) {
11790                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11791                            "New package not signed by keys specified by upgrade-keysets: "
11792                            + pkgName);
11793                    return;
11794                }
11795            } else {
11796                // default to original signature matching
11797                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11798                    != PackageManager.SIGNATURE_MATCH) {
11799                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11800                            "New package has a different signature: " + pkgName);
11801                    return;
11802                }
11803            }
11804
11805            // In case of rollback, remember per-user/profile install state
11806            allUsers = sUserManager.getUserIds();
11807            perUserInstalled = new boolean[allUsers.length];
11808            for (int i = 0; i < allUsers.length; i++) {
11809                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11810            }
11811        }
11812
11813        boolean sysPkg = (isSystemApp(oldPackage));
11814        if (sysPkg) {
11815            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11816                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11817        } else {
11818            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11819                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11820        }
11821    }
11822
11823    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11824            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11825            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11826            String volumeUuid, PackageInstalledInfo res) {
11827        String pkgName = deletedPackage.packageName;
11828        boolean deletedPkg = true;
11829        boolean updatedSettings = false;
11830
11831        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11832                + deletedPackage);
11833        long origUpdateTime;
11834        if (pkg.mExtras != null) {
11835            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11836        } else {
11837            origUpdateTime = 0;
11838        }
11839
11840        // First delete the existing package while retaining the data directory
11841        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11842                res.removedInfo, true)) {
11843            // If the existing package wasn't successfully deleted
11844            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11845            deletedPkg = false;
11846        } else {
11847            // Successfully deleted the old package; proceed with replace.
11848
11849            // If deleted package lived in a container, give users a chance to
11850            // relinquish resources before killing.
11851            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11852                if (DEBUG_INSTALL) {
11853                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11854                }
11855                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11856                final ArrayList<String> pkgList = new ArrayList<String>(1);
11857                pkgList.add(deletedPackage.applicationInfo.packageName);
11858                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11859            }
11860
11861            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11862            try {
11863                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11864                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11865                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11866                        perUserInstalled, res, user);
11867                updatedSettings = true;
11868            } catch (PackageManagerException e) {
11869                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11870            }
11871        }
11872
11873        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11874            // remove package from internal structures.  Note that we want deletePackageX to
11875            // delete the package data and cache directories that it created in
11876            // scanPackageLocked, unless those directories existed before we even tried to
11877            // install.
11878            if(updatedSettings) {
11879                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11880                deletePackageLI(
11881                        pkgName, null, true, allUsers, perUserInstalled,
11882                        PackageManager.DELETE_KEEP_DATA,
11883                                res.removedInfo, true);
11884            }
11885            // Since we failed to install the new package we need to restore the old
11886            // package that we deleted.
11887            if (deletedPkg) {
11888                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11889                File restoreFile = new File(deletedPackage.codePath);
11890                // Parse old package
11891                boolean oldExternal = isExternal(deletedPackage);
11892                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11893                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11894                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11895                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11896                try {
11897                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11898                } catch (PackageManagerException e) {
11899                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11900                            + e.getMessage());
11901                    return;
11902                }
11903                // Restore of old package succeeded. Update permissions.
11904                // writer
11905                synchronized (mPackages) {
11906                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11907                            UPDATE_PERMISSIONS_ALL);
11908                    // can downgrade to reader
11909                    mSettings.writeLPr();
11910                }
11911                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11912            }
11913        }
11914    }
11915
11916    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11917            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11918            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11919            String volumeUuid, PackageInstalledInfo res) {
11920        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11921                + ", old=" + deletedPackage);
11922        boolean disabledSystem = false;
11923        boolean updatedSettings = false;
11924        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11925        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11926                != 0) {
11927            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11928        }
11929        String packageName = deletedPackage.packageName;
11930        if (packageName == null) {
11931            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11932                    "Attempt to delete null packageName.");
11933            return;
11934        }
11935        PackageParser.Package oldPkg;
11936        PackageSetting oldPkgSetting;
11937        // reader
11938        synchronized (mPackages) {
11939            oldPkg = mPackages.get(packageName);
11940            oldPkgSetting = mSettings.mPackages.get(packageName);
11941            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11942                    (oldPkgSetting == null)) {
11943                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11944                        "Couldn't find package:" + packageName + " information");
11945                return;
11946            }
11947        }
11948
11949        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11950
11951        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11952        res.removedInfo.removedPackage = packageName;
11953        // Remove existing system package
11954        removePackageLI(oldPkgSetting, true);
11955        // writer
11956        synchronized (mPackages) {
11957            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11958            if (!disabledSystem && deletedPackage != null) {
11959                // We didn't need to disable the .apk as a current system package,
11960                // which means we are replacing another update that is already
11961                // installed.  We need to make sure to delete the older one's .apk.
11962                res.removedInfo.args = createInstallArgsForExisting(0,
11963                        deletedPackage.applicationInfo.getCodePath(),
11964                        deletedPackage.applicationInfo.getResourcePath(),
11965                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11966            } else {
11967                res.removedInfo.args = null;
11968            }
11969        }
11970
11971        // Successfully disabled the old package. Now proceed with re-installation
11972        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11973
11974        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11975        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11976
11977        PackageParser.Package newPackage = null;
11978        try {
11979            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11980            if (newPackage.mExtras != null) {
11981                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11982                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11983                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11984
11985                // is the update attempting to change shared user? that isn't going to work...
11986                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11987                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11988                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11989                            + " to " + newPkgSetting.sharedUser);
11990                    updatedSettings = true;
11991                }
11992            }
11993
11994            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11995                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11996                        perUserInstalled, res, user);
11997                updatedSettings = true;
11998            }
11999
12000        } catch (PackageManagerException e) {
12001            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12002        }
12003
12004        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12005            // Re installation failed. Restore old information
12006            // Remove new pkg information
12007            if (newPackage != null) {
12008                removeInstalledPackageLI(newPackage, true);
12009            }
12010            // Add back the old system package
12011            try {
12012                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12013            } catch (PackageManagerException e) {
12014                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12015            }
12016            // Restore the old system information in Settings
12017            synchronized (mPackages) {
12018                if (disabledSystem) {
12019                    mSettings.enableSystemPackageLPw(packageName);
12020                }
12021                if (updatedSettings) {
12022                    mSettings.setInstallerPackageName(packageName,
12023                            oldPkgSetting.installerPackageName);
12024                }
12025                mSettings.writeLPr();
12026            }
12027        }
12028    }
12029
12030    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12031            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12032            UserHandle user) {
12033        String pkgName = newPackage.packageName;
12034        synchronized (mPackages) {
12035            //write settings. the installStatus will be incomplete at this stage.
12036            //note that the new package setting would have already been
12037            //added to mPackages. It hasn't been persisted yet.
12038            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12039            mSettings.writeLPr();
12040        }
12041
12042        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12043
12044        synchronized (mPackages) {
12045            updatePermissionsLPw(newPackage.packageName, newPackage,
12046                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12047                            ? UPDATE_PERMISSIONS_ALL : 0));
12048            // For system-bundled packages, we assume that installing an upgraded version
12049            // of the package implies that the user actually wants to run that new code,
12050            // so we enable the package.
12051            PackageSetting ps = mSettings.mPackages.get(pkgName);
12052            if (ps != null) {
12053                if (isSystemApp(newPackage)) {
12054                    // NB: implicit assumption that system package upgrades apply to all users
12055                    if (DEBUG_INSTALL) {
12056                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12057                    }
12058                    if (res.origUsers != null) {
12059                        for (int userHandle : res.origUsers) {
12060                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12061                                    userHandle, installerPackageName);
12062                        }
12063                    }
12064                    // Also convey the prior install/uninstall state
12065                    if (allUsers != null && perUserInstalled != null) {
12066                        for (int i = 0; i < allUsers.length; i++) {
12067                            if (DEBUG_INSTALL) {
12068                                Slog.d(TAG, "    user " + allUsers[i]
12069                                        + " => " + perUserInstalled[i]);
12070                            }
12071                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12072                        }
12073                        // these install state changes will be persisted in the
12074                        // upcoming call to mSettings.writeLPr().
12075                    }
12076                }
12077                // It's implied that when a user requests installation, they want the app to be
12078                // installed and enabled.
12079                int userId = user.getIdentifier();
12080                if (userId != UserHandle.USER_ALL) {
12081                    ps.setInstalled(true, userId);
12082                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12083                }
12084            }
12085            res.name = pkgName;
12086            res.uid = newPackage.applicationInfo.uid;
12087            res.pkg = newPackage;
12088            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12089            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12090            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12091            //to update install status
12092            mSettings.writeLPr();
12093        }
12094    }
12095
12096    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12097        final int installFlags = args.installFlags;
12098        final String installerPackageName = args.installerPackageName;
12099        final String volumeUuid = args.volumeUuid;
12100        final File tmpPackageFile = new File(args.getCodePath());
12101        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12102        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12103                || (args.volumeUuid != null));
12104        boolean replace = false;
12105        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12106        if (args.move != null) {
12107            // moving a complete application; perfom an initial scan on the new install location
12108            scanFlags |= SCAN_INITIAL;
12109        }
12110        // Result object to be returned
12111        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12112
12113        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12114        // Retrieve PackageSettings and parse package
12115        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12116                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12117                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12118        PackageParser pp = new PackageParser();
12119        pp.setSeparateProcesses(mSeparateProcesses);
12120        pp.setDisplayMetrics(mMetrics);
12121
12122        final PackageParser.Package pkg;
12123        try {
12124            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12125        } catch (PackageParserException e) {
12126            res.setError("Failed parse during installPackageLI", e);
12127            return;
12128        }
12129
12130        // Mark that we have an install time CPU ABI override.
12131        pkg.cpuAbiOverride = args.abiOverride;
12132
12133        String pkgName = res.name = pkg.packageName;
12134        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12135            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12136                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12137                return;
12138            }
12139        }
12140
12141        try {
12142            pp.collectCertificates(pkg, parseFlags);
12143            pp.collectManifestDigest(pkg);
12144        } catch (PackageParserException e) {
12145            res.setError("Failed collect during installPackageLI", e);
12146            return;
12147        }
12148
12149        /* If the installer passed in a manifest digest, compare it now. */
12150        if (args.manifestDigest != null) {
12151            if (DEBUG_INSTALL) {
12152                final String parsedManifest = pkg.manifestDigest == null ? "null"
12153                        : pkg.manifestDigest.toString();
12154                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12155                        + parsedManifest);
12156            }
12157
12158            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12159                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12160                return;
12161            }
12162        } else if (DEBUG_INSTALL) {
12163            final String parsedManifest = pkg.manifestDigest == null
12164                    ? "null" : pkg.manifestDigest.toString();
12165            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12166        }
12167
12168        // Get rid of all references to package scan path via parser.
12169        pp = null;
12170        String oldCodePath = null;
12171        boolean systemApp = false;
12172        synchronized (mPackages) {
12173            // Check if installing already existing package
12174            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12175                String oldName = mSettings.mRenamedPackages.get(pkgName);
12176                if (pkg.mOriginalPackages != null
12177                        && pkg.mOriginalPackages.contains(oldName)
12178                        && mPackages.containsKey(oldName)) {
12179                    // This package is derived from an original package,
12180                    // and this device has been updating from that original
12181                    // name.  We must continue using the original name, so
12182                    // rename the new package here.
12183                    pkg.setPackageName(oldName);
12184                    pkgName = pkg.packageName;
12185                    replace = true;
12186                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12187                            + oldName + " pkgName=" + pkgName);
12188                } else if (mPackages.containsKey(pkgName)) {
12189                    // This package, under its official name, already exists
12190                    // on the device; we should replace it.
12191                    replace = true;
12192                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12193                }
12194
12195                // Prevent apps opting out from runtime permissions
12196                if (replace) {
12197                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12198                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12199                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12200                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12201                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12202                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12203                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12204                                        + " doesn't support runtime permissions but the old"
12205                                        + " target SDK " + oldTargetSdk + " does.");
12206                        return;
12207                    }
12208                }
12209            }
12210
12211            PackageSetting ps = mSettings.mPackages.get(pkgName);
12212            if (ps != null) {
12213                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12214
12215                // Quick sanity check that we're signed correctly if updating;
12216                // we'll check this again later when scanning, but we want to
12217                // bail early here before tripping over redefined permissions.
12218                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12219                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12220                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12221                                + pkg.packageName + " upgrade keys do not match the "
12222                                + "previously installed version");
12223                        return;
12224                    }
12225                } else {
12226                    try {
12227                        verifySignaturesLP(ps, pkg);
12228                    } catch (PackageManagerException e) {
12229                        res.setError(e.error, e.getMessage());
12230                        return;
12231                    }
12232                }
12233
12234                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12235                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12236                    systemApp = (ps.pkg.applicationInfo.flags &
12237                            ApplicationInfo.FLAG_SYSTEM) != 0;
12238                }
12239                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12240            }
12241
12242            // Check whether the newly-scanned package wants to define an already-defined perm
12243            int N = pkg.permissions.size();
12244            for (int i = N-1; i >= 0; i--) {
12245                PackageParser.Permission perm = pkg.permissions.get(i);
12246                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12247                if (bp != null) {
12248                    // If the defining package is signed with our cert, it's okay.  This
12249                    // also includes the "updating the same package" case, of course.
12250                    // "updating same package" could also involve key-rotation.
12251                    final boolean sigsOk;
12252                    if (bp.sourcePackage.equals(pkg.packageName)
12253                            && (bp.packageSetting instanceof PackageSetting)
12254                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12255                                    scanFlags))) {
12256                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12257                    } else {
12258                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12259                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12260                    }
12261                    if (!sigsOk) {
12262                        // If the owning package is the system itself, we log but allow
12263                        // install to proceed; we fail the install on all other permission
12264                        // redefinitions.
12265                        if (!bp.sourcePackage.equals("android")) {
12266                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12267                                    + pkg.packageName + " attempting to redeclare permission "
12268                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12269                            res.origPermission = perm.info.name;
12270                            res.origPackage = bp.sourcePackage;
12271                            return;
12272                        } else {
12273                            Slog.w(TAG, "Package " + pkg.packageName
12274                                    + " attempting to redeclare system permission "
12275                                    + perm.info.name + "; ignoring new declaration");
12276                            pkg.permissions.remove(i);
12277                        }
12278                    }
12279                }
12280            }
12281
12282        }
12283
12284        if (systemApp && onExternal) {
12285            // Disable updates to system apps on sdcard
12286            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12287                    "Cannot install updates to system apps on sdcard");
12288            return;
12289        }
12290
12291        if (args.move != null) {
12292            // We did an in-place move, so dex is ready to roll
12293            scanFlags |= SCAN_NO_DEX;
12294            scanFlags |= SCAN_MOVE;
12295
12296            synchronized (mPackages) {
12297                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12298                if (ps == null) {
12299                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12300                            "Missing settings for moved package " + pkgName);
12301                }
12302
12303                // We moved the entire application as-is, so bring over the
12304                // previously derived ABI information.
12305                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12306                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12307            }
12308
12309        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12310            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12311            scanFlags |= SCAN_NO_DEX;
12312
12313            try {
12314                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12315                        true /* extract libs */);
12316            } catch (PackageManagerException pme) {
12317                Slog.e(TAG, "Error deriving application ABI", pme);
12318                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12319                return;
12320            }
12321
12322            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12323            int result = mPackageDexOptimizer
12324                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12325                            false /* defer */, false /* inclDependencies */);
12326            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12327                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12328                return;
12329            }
12330        }
12331
12332        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12333            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12334            return;
12335        }
12336
12337        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12338
12339        if (replace) {
12340            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12341                    installerPackageName, volumeUuid, res);
12342        } else {
12343            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12344                    args.user, installerPackageName, volumeUuid, res);
12345        }
12346        synchronized (mPackages) {
12347            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12348            if (ps != null) {
12349                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12350            }
12351        }
12352    }
12353
12354    private void startIntentFilterVerifications(int userId, boolean replacing,
12355            PackageParser.Package pkg) {
12356        if (mIntentFilterVerifierComponent == null) {
12357            Slog.w(TAG, "No IntentFilter verification will not be done as "
12358                    + "there is no IntentFilterVerifier available!");
12359            return;
12360        }
12361
12362        final int verifierUid = getPackageUid(
12363                mIntentFilterVerifierComponent.getPackageName(),
12364                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12365
12366        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12367        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12368        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12369        mHandler.sendMessage(msg);
12370    }
12371
12372    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12373            PackageParser.Package pkg) {
12374        int size = pkg.activities.size();
12375        if (size == 0) {
12376            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12377                    "No activity, so no need to verify any IntentFilter!");
12378            return;
12379        }
12380
12381        final boolean hasDomainURLs = hasDomainURLs(pkg);
12382        if (!hasDomainURLs) {
12383            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12384                    "No domain URLs, so no need to verify any IntentFilter!");
12385            return;
12386        }
12387
12388        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12389                + " if any IntentFilter from the " + size
12390                + " Activities needs verification ...");
12391
12392        int count = 0;
12393        final String packageName = pkg.packageName;
12394
12395        synchronized (mPackages) {
12396            // If this is a new install and we see that we've already run verification for this
12397            // package, we have nothing to do: it means the state was restored from backup.
12398            if (!replacing) {
12399                IntentFilterVerificationInfo ivi =
12400                        mSettings.getIntentFilterVerificationLPr(packageName);
12401                if (ivi != null) {
12402                    if (DEBUG_DOMAIN_VERIFICATION) {
12403                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12404                                + ivi.getStatusString());
12405                    }
12406                    return;
12407                }
12408            }
12409
12410            // If any filters need to be verified, then all need to be.
12411            boolean needToVerify = false;
12412            for (PackageParser.Activity a : pkg.activities) {
12413                for (ActivityIntentInfo filter : a.intents) {
12414                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12415                        if (DEBUG_DOMAIN_VERIFICATION) {
12416                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12417                        }
12418                        needToVerify = true;
12419                        break;
12420                    }
12421                }
12422            }
12423
12424            if (needToVerify) {
12425                final int verificationId = mIntentFilterVerificationToken++;
12426                for (PackageParser.Activity a : pkg.activities) {
12427                    for (ActivityIntentInfo filter : a.intents) {
12428                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12429                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12430                                    "Verification needed for IntentFilter:" + filter.toString());
12431                            mIntentFilterVerifier.addOneIntentFilterVerification(
12432                                    verifierUid, userId, verificationId, filter, packageName);
12433                            count++;
12434                        }
12435                    }
12436                }
12437            }
12438        }
12439
12440        if (count > 0) {
12441            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12442                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12443                    +  " for userId:" + userId);
12444            mIntentFilterVerifier.startVerifications(userId);
12445        } else {
12446            if (DEBUG_DOMAIN_VERIFICATION) {
12447                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12448            }
12449        }
12450    }
12451
12452    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12453        final ComponentName cn  = filter.activity.getComponentName();
12454        final String packageName = cn.getPackageName();
12455
12456        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12457                packageName);
12458        if (ivi == null) {
12459            return true;
12460        }
12461        int status = ivi.getStatus();
12462        switch (status) {
12463            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12464            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12465                return true;
12466
12467            default:
12468                // Nothing to do
12469                return false;
12470        }
12471    }
12472
12473    private static boolean isMultiArch(PackageSetting ps) {
12474        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12475    }
12476
12477    private static boolean isMultiArch(ApplicationInfo info) {
12478        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12479    }
12480
12481    private static boolean isExternal(PackageParser.Package pkg) {
12482        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12483    }
12484
12485    private static boolean isExternal(PackageSetting ps) {
12486        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12487    }
12488
12489    private static boolean isExternal(ApplicationInfo info) {
12490        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12491    }
12492
12493    private static boolean isSystemApp(PackageParser.Package pkg) {
12494        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12495    }
12496
12497    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12498        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12499    }
12500
12501    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12502        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12503    }
12504
12505    private static boolean isSystemApp(PackageSetting ps) {
12506        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12507    }
12508
12509    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12510        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12511    }
12512
12513    private int packageFlagsToInstallFlags(PackageSetting ps) {
12514        int installFlags = 0;
12515        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12516            // This existing package was an external ASEC install when we have
12517            // the external flag without a UUID
12518            installFlags |= PackageManager.INSTALL_EXTERNAL;
12519        }
12520        if (ps.isForwardLocked()) {
12521            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12522        }
12523        return installFlags;
12524    }
12525
12526    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12527        if (isExternal(pkg)) {
12528            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12529                return mSettings.getExternalVersion();
12530            } else {
12531                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12532            }
12533        } else {
12534            return mSettings.getInternalVersion();
12535        }
12536    }
12537
12538    private void deleteTempPackageFiles() {
12539        final FilenameFilter filter = new FilenameFilter() {
12540            public boolean accept(File dir, String name) {
12541                return name.startsWith("vmdl") && name.endsWith(".tmp");
12542            }
12543        };
12544        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12545            file.delete();
12546        }
12547    }
12548
12549    @Override
12550    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12551            int flags) {
12552        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12553                flags);
12554    }
12555
12556    @Override
12557    public void deletePackage(final String packageName,
12558            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12559        mContext.enforceCallingOrSelfPermission(
12560                android.Manifest.permission.DELETE_PACKAGES, null);
12561        Preconditions.checkNotNull(packageName);
12562        Preconditions.checkNotNull(observer);
12563        final int uid = Binder.getCallingUid();
12564        if (UserHandle.getUserId(uid) != userId) {
12565            mContext.enforceCallingPermission(
12566                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12567                    "deletePackage for user " + userId);
12568        }
12569        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12570            try {
12571                observer.onPackageDeleted(packageName,
12572                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12573            } catch (RemoteException re) {
12574            }
12575            return;
12576        }
12577
12578        boolean uninstallBlocked = false;
12579        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12580            int[] users = sUserManager.getUserIds();
12581            for (int i = 0; i < users.length; ++i) {
12582                if (getBlockUninstallForUser(packageName, users[i])) {
12583                    uninstallBlocked = true;
12584                    break;
12585                }
12586            }
12587        } else {
12588            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12589        }
12590        if (uninstallBlocked) {
12591            try {
12592                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12593                        null);
12594            } catch (RemoteException re) {
12595            }
12596            return;
12597        }
12598
12599        if (DEBUG_REMOVE) {
12600            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12601        }
12602        // Queue up an async operation since the package deletion may take a little while.
12603        mHandler.post(new Runnable() {
12604            public void run() {
12605                mHandler.removeCallbacks(this);
12606                final int returnCode = deletePackageX(packageName, userId, flags);
12607                if (observer != null) {
12608                    try {
12609                        observer.onPackageDeleted(packageName, returnCode, null);
12610                    } catch (RemoteException e) {
12611                        Log.i(TAG, "Observer no longer exists.");
12612                    } //end catch
12613                } //end if
12614            } //end run
12615        });
12616    }
12617
12618    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12619        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12620                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12621        try {
12622            if (dpm != null) {
12623                if (dpm.isDeviceOwner(packageName)) {
12624                    return true;
12625                }
12626                int[] users;
12627                if (userId == UserHandle.USER_ALL) {
12628                    users = sUserManager.getUserIds();
12629                } else {
12630                    users = new int[]{userId};
12631                }
12632                for (int i = 0; i < users.length; ++i) {
12633                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12634                        return true;
12635                    }
12636                }
12637            }
12638        } catch (RemoteException e) {
12639        }
12640        return false;
12641    }
12642
12643    /**
12644     *  This method is an internal method that could be get invoked either
12645     *  to delete an installed package or to clean up a failed installation.
12646     *  After deleting an installed package, a broadcast is sent to notify any
12647     *  listeners that the package has been installed. For cleaning up a failed
12648     *  installation, the broadcast is not necessary since the package's
12649     *  installation wouldn't have sent the initial broadcast either
12650     *  The key steps in deleting a package are
12651     *  deleting the package information in internal structures like mPackages,
12652     *  deleting the packages base directories through installd
12653     *  updating mSettings to reflect current status
12654     *  persisting settings for later use
12655     *  sending a broadcast if necessary
12656     */
12657    private int deletePackageX(String packageName, int userId, int flags) {
12658        final PackageRemovedInfo info = new PackageRemovedInfo();
12659        final boolean res;
12660
12661        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12662                ? UserHandle.ALL : new UserHandle(userId);
12663
12664        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12665            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12666            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12667        }
12668
12669        boolean removedForAllUsers = false;
12670        boolean systemUpdate = false;
12671
12672        // for the uninstall-updates case and restricted profiles, remember the per-
12673        // userhandle installed state
12674        int[] allUsers;
12675        boolean[] perUserInstalled;
12676        synchronized (mPackages) {
12677            PackageSetting ps = mSettings.mPackages.get(packageName);
12678            allUsers = sUserManager.getUserIds();
12679            perUserInstalled = new boolean[allUsers.length];
12680            for (int i = 0; i < allUsers.length; i++) {
12681                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12682            }
12683        }
12684
12685        synchronized (mInstallLock) {
12686            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12687            res = deletePackageLI(packageName, removeForUser,
12688                    true, allUsers, perUserInstalled,
12689                    flags | REMOVE_CHATTY, info, true);
12690            systemUpdate = info.isRemovedPackageSystemUpdate;
12691            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12692                removedForAllUsers = true;
12693            }
12694            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12695                    + " removedForAllUsers=" + removedForAllUsers);
12696        }
12697
12698        if (res) {
12699            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12700
12701            // If the removed package was a system update, the old system package
12702            // was re-enabled; we need to broadcast this information
12703            if (systemUpdate) {
12704                Bundle extras = new Bundle(1);
12705                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12706                        ? info.removedAppId : info.uid);
12707                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12708
12709                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12710                        extras, null, null, null);
12711                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12712                        extras, null, null, null);
12713                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12714                        null, packageName, null, null);
12715            }
12716        }
12717        // Force a gc here.
12718        Runtime.getRuntime().gc();
12719        // Delete the resources here after sending the broadcast to let
12720        // other processes clean up before deleting resources.
12721        if (info.args != null) {
12722            synchronized (mInstallLock) {
12723                info.args.doPostDeleteLI(true);
12724            }
12725        }
12726
12727        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12728    }
12729
12730    class PackageRemovedInfo {
12731        String removedPackage;
12732        int uid = -1;
12733        int removedAppId = -1;
12734        int[] removedUsers = null;
12735        boolean isRemovedPackageSystemUpdate = false;
12736        // Clean up resources deleted packages.
12737        InstallArgs args = null;
12738
12739        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12740            Bundle extras = new Bundle(1);
12741            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12742            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12743            if (replacing) {
12744                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12745            }
12746            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12747            if (removedPackage != null) {
12748                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12749                        extras, null, null, removedUsers);
12750                if (fullRemove && !replacing) {
12751                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12752                            extras, null, null, removedUsers);
12753                }
12754            }
12755            if (removedAppId >= 0) {
12756                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12757                        removedUsers);
12758            }
12759        }
12760    }
12761
12762    /*
12763     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12764     * flag is not set, the data directory is removed as well.
12765     * make sure this flag is set for partially installed apps. If not its meaningless to
12766     * delete a partially installed application.
12767     */
12768    private void removePackageDataLI(PackageSetting ps,
12769            int[] allUserHandles, boolean[] perUserInstalled,
12770            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12771        String packageName = ps.name;
12772        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12773        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12774        // Retrieve object to delete permissions for shared user later on
12775        final PackageSetting deletedPs;
12776        // reader
12777        synchronized (mPackages) {
12778            deletedPs = mSettings.mPackages.get(packageName);
12779            if (outInfo != null) {
12780                outInfo.removedPackage = packageName;
12781                outInfo.removedUsers = deletedPs != null
12782                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12783                        : null;
12784            }
12785        }
12786        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12787            removeDataDirsLI(ps.volumeUuid, packageName);
12788            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12789        }
12790        // writer
12791        synchronized (mPackages) {
12792            if (deletedPs != null) {
12793                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12794                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12795                    clearDefaultBrowserIfNeeded(packageName);
12796                    if (outInfo != null) {
12797                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12798                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12799                    }
12800                    updatePermissionsLPw(deletedPs.name, null, 0);
12801                    if (deletedPs.sharedUser != null) {
12802                        // Remove permissions associated with package. Since runtime
12803                        // permissions are per user we have to kill the removed package
12804                        // or packages running under the shared user of the removed
12805                        // package if revoking the permissions requested only by the removed
12806                        // package is successful and this causes a change in gids.
12807                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12808                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12809                                    userId);
12810                            if (userIdToKill == UserHandle.USER_ALL
12811                                    || userIdToKill >= UserHandle.USER_OWNER) {
12812                                // If gids changed for this user, kill all affected packages.
12813                                mHandler.post(new Runnable() {
12814                                    @Override
12815                                    public void run() {
12816                                        // This has to happen with no lock held.
12817                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12818                                                KILL_APP_REASON_GIDS_CHANGED);
12819                                    }
12820                                });
12821                                break;
12822                            }
12823                        }
12824                    }
12825                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12826                }
12827                // make sure to preserve per-user disabled state if this removal was just
12828                // a downgrade of a system app to the factory package
12829                if (allUserHandles != null && perUserInstalled != null) {
12830                    if (DEBUG_REMOVE) {
12831                        Slog.d(TAG, "Propagating install state across downgrade");
12832                    }
12833                    for (int i = 0; i < allUserHandles.length; i++) {
12834                        if (DEBUG_REMOVE) {
12835                            Slog.d(TAG, "    user " + allUserHandles[i]
12836                                    + " => " + perUserInstalled[i]);
12837                        }
12838                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12839                    }
12840                }
12841            }
12842            // can downgrade to reader
12843            if (writeSettings) {
12844                // Save settings now
12845                mSettings.writeLPr();
12846            }
12847        }
12848        if (outInfo != null) {
12849            // A user ID was deleted here. Go through all users and remove it
12850            // from KeyStore.
12851            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12852        }
12853    }
12854
12855    static boolean locationIsPrivileged(File path) {
12856        try {
12857            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12858                    .getCanonicalPath();
12859            return path.getCanonicalPath().startsWith(privilegedAppDir);
12860        } catch (IOException e) {
12861            Slog.e(TAG, "Unable to access code path " + path);
12862        }
12863        return false;
12864    }
12865
12866    /*
12867     * Tries to delete system package.
12868     */
12869    private boolean deleteSystemPackageLI(PackageSetting newPs,
12870            int[] allUserHandles, boolean[] perUserInstalled,
12871            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12872        final boolean applyUserRestrictions
12873                = (allUserHandles != null) && (perUserInstalled != null);
12874        PackageSetting disabledPs = null;
12875        // Confirm if the system package has been updated
12876        // An updated system app can be deleted. This will also have to restore
12877        // the system pkg from system partition
12878        // reader
12879        synchronized (mPackages) {
12880            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12881        }
12882        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12883                + " disabledPs=" + disabledPs);
12884        if (disabledPs == null) {
12885            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12886            return false;
12887        } else if (DEBUG_REMOVE) {
12888            Slog.d(TAG, "Deleting system pkg from data partition");
12889        }
12890        if (DEBUG_REMOVE) {
12891            if (applyUserRestrictions) {
12892                Slog.d(TAG, "Remembering install states:");
12893                for (int i = 0; i < allUserHandles.length; i++) {
12894                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12895                }
12896            }
12897        }
12898        // Delete the updated package
12899        outInfo.isRemovedPackageSystemUpdate = true;
12900        if (disabledPs.versionCode < newPs.versionCode) {
12901            // Delete data for downgrades
12902            flags &= ~PackageManager.DELETE_KEEP_DATA;
12903        } else {
12904            // Preserve data by setting flag
12905            flags |= PackageManager.DELETE_KEEP_DATA;
12906        }
12907        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12908                allUserHandles, perUserInstalled, outInfo, writeSettings);
12909        if (!ret) {
12910            return false;
12911        }
12912        // writer
12913        synchronized (mPackages) {
12914            // Reinstate the old system package
12915            mSettings.enableSystemPackageLPw(newPs.name);
12916            // Remove any native libraries from the upgraded package.
12917            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12918        }
12919        // Install the system package
12920        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12921        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12922        if (locationIsPrivileged(disabledPs.codePath)) {
12923            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12924        }
12925
12926        final PackageParser.Package newPkg;
12927        try {
12928            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12929        } catch (PackageManagerException e) {
12930            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12931            return false;
12932        }
12933
12934        // writer
12935        synchronized (mPackages) {
12936            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12937
12938            updatePermissionsLPw(newPkg.packageName, newPkg,
12939                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12940
12941            if (applyUserRestrictions) {
12942                if (DEBUG_REMOVE) {
12943                    Slog.d(TAG, "Propagating install state across reinstall");
12944                }
12945                for (int i = 0; i < allUserHandles.length; i++) {
12946                    if (DEBUG_REMOVE) {
12947                        Slog.d(TAG, "    user " + allUserHandles[i]
12948                                + " => " + perUserInstalled[i]);
12949                    }
12950                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12951
12952                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12953                }
12954                // Regardless of writeSettings we need to ensure that this restriction
12955                // state propagation is persisted
12956                mSettings.writeAllUsersPackageRestrictionsLPr();
12957            }
12958            // can downgrade to reader here
12959            if (writeSettings) {
12960                mSettings.writeLPr();
12961            }
12962        }
12963        return true;
12964    }
12965
12966    private boolean deleteInstalledPackageLI(PackageSetting ps,
12967            boolean deleteCodeAndResources, int flags,
12968            int[] allUserHandles, boolean[] perUserInstalled,
12969            PackageRemovedInfo outInfo, boolean writeSettings) {
12970        if (outInfo != null) {
12971            outInfo.uid = ps.appId;
12972        }
12973
12974        // Delete package data from internal structures and also remove data if flag is set
12975        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12976
12977        // Delete application code and resources
12978        if (deleteCodeAndResources && (outInfo != null)) {
12979            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12980                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12981            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12982        }
12983        return true;
12984    }
12985
12986    @Override
12987    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12988            int userId) {
12989        mContext.enforceCallingOrSelfPermission(
12990                android.Manifest.permission.DELETE_PACKAGES, null);
12991        synchronized (mPackages) {
12992            PackageSetting ps = mSettings.mPackages.get(packageName);
12993            if (ps == null) {
12994                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12995                return false;
12996            }
12997            if (!ps.getInstalled(userId)) {
12998                // Can't block uninstall for an app that is not installed or enabled.
12999                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13000                return false;
13001            }
13002            ps.setBlockUninstall(blockUninstall, userId);
13003            mSettings.writePackageRestrictionsLPr(userId);
13004        }
13005        return true;
13006    }
13007
13008    @Override
13009    public boolean getBlockUninstallForUser(String packageName, int userId) {
13010        synchronized (mPackages) {
13011            PackageSetting ps = mSettings.mPackages.get(packageName);
13012            if (ps == null) {
13013                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13014                return false;
13015            }
13016            return ps.getBlockUninstall(userId);
13017        }
13018    }
13019
13020    /*
13021     * This method handles package deletion in general
13022     */
13023    private boolean deletePackageLI(String packageName, UserHandle user,
13024            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13025            int flags, PackageRemovedInfo outInfo,
13026            boolean writeSettings) {
13027        if (packageName == null) {
13028            Slog.w(TAG, "Attempt to delete null packageName.");
13029            return false;
13030        }
13031        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13032        PackageSetting ps;
13033        boolean dataOnly = false;
13034        int removeUser = -1;
13035        int appId = -1;
13036        synchronized (mPackages) {
13037            ps = mSettings.mPackages.get(packageName);
13038            if (ps == null) {
13039                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13040                return false;
13041            }
13042            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13043                    && user.getIdentifier() != UserHandle.USER_ALL) {
13044                // The caller is asking that the package only be deleted for a single
13045                // user.  To do this, we just mark its uninstalled state and delete
13046                // its data.  If this is a system app, we only allow this to happen if
13047                // they have set the special DELETE_SYSTEM_APP which requests different
13048                // semantics than normal for uninstalling system apps.
13049                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13050                ps.setUserState(user.getIdentifier(),
13051                        COMPONENT_ENABLED_STATE_DEFAULT,
13052                        false, //installed
13053                        true,  //stopped
13054                        true,  //notLaunched
13055                        false, //hidden
13056                        null, null, null,
13057                        false, // blockUninstall
13058                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13059                if (!isSystemApp(ps)) {
13060                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13061                        // Other user still have this package installed, so all
13062                        // we need to do is clear this user's data and save that
13063                        // it is uninstalled.
13064                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13065                        removeUser = user.getIdentifier();
13066                        appId = ps.appId;
13067                        scheduleWritePackageRestrictionsLocked(removeUser);
13068                    } else {
13069                        // We need to set it back to 'installed' so the uninstall
13070                        // broadcasts will be sent correctly.
13071                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13072                        ps.setInstalled(true, user.getIdentifier());
13073                    }
13074                } else {
13075                    // This is a system app, so we assume that the
13076                    // other users still have this package installed, so all
13077                    // we need to do is clear this user's data and save that
13078                    // it is uninstalled.
13079                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13080                    removeUser = user.getIdentifier();
13081                    appId = ps.appId;
13082                    scheduleWritePackageRestrictionsLocked(removeUser);
13083                }
13084            }
13085        }
13086
13087        if (removeUser >= 0) {
13088            // From above, we determined that we are deleting this only
13089            // for a single user.  Continue the work here.
13090            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13091            if (outInfo != null) {
13092                outInfo.removedPackage = packageName;
13093                outInfo.removedAppId = appId;
13094                outInfo.removedUsers = new int[] {removeUser};
13095            }
13096            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13097            removeKeystoreDataIfNeeded(removeUser, appId);
13098            schedulePackageCleaning(packageName, removeUser, false);
13099            synchronized (mPackages) {
13100                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13101                    scheduleWritePackageRestrictionsLocked(removeUser);
13102                }
13103                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13104            }
13105            return true;
13106        }
13107
13108        if (dataOnly) {
13109            // Delete application data first
13110            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13111            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13112            return true;
13113        }
13114
13115        boolean ret = false;
13116        if (isSystemApp(ps)) {
13117            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13118            // When an updated system application is deleted we delete the existing resources as well and
13119            // fall back to existing code in system partition
13120            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13121                    flags, outInfo, writeSettings);
13122        } else {
13123            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13124            // Kill application pre-emptively especially for apps on sd.
13125            killApplication(packageName, ps.appId, "uninstall pkg");
13126            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13127                    allUserHandles, perUserInstalled,
13128                    outInfo, writeSettings);
13129        }
13130
13131        return ret;
13132    }
13133
13134    private final class ClearStorageConnection implements ServiceConnection {
13135        IMediaContainerService mContainerService;
13136
13137        @Override
13138        public void onServiceConnected(ComponentName name, IBinder service) {
13139            synchronized (this) {
13140                mContainerService = IMediaContainerService.Stub.asInterface(service);
13141                notifyAll();
13142            }
13143        }
13144
13145        @Override
13146        public void onServiceDisconnected(ComponentName name) {
13147        }
13148    }
13149
13150    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13151        final boolean mounted;
13152        if (Environment.isExternalStorageEmulated()) {
13153            mounted = true;
13154        } else {
13155            final String status = Environment.getExternalStorageState();
13156
13157            mounted = status.equals(Environment.MEDIA_MOUNTED)
13158                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13159        }
13160
13161        if (!mounted) {
13162            return;
13163        }
13164
13165        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13166        int[] users;
13167        if (userId == UserHandle.USER_ALL) {
13168            users = sUserManager.getUserIds();
13169        } else {
13170            users = new int[] { userId };
13171        }
13172        final ClearStorageConnection conn = new ClearStorageConnection();
13173        if (mContext.bindServiceAsUser(
13174                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13175            try {
13176                for (int curUser : users) {
13177                    long timeout = SystemClock.uptimeMillis() + 5000;
13178                    synchronized (conn) {
13179                        long now = SystemClock.uptimeMillis();
13180                        while (conn.mContainerService == null && now < timeout) {
13181                            try {
13182                                conn.wait(timeout - now);
13183                            } catch (InterruptedException e) {
13184                            }
13185                        }
13186                    }
13187                    if (conn.mContainerService == null) {
13188                        return;
13189                    }
13190
13191                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13192                    clearDirectory(conn.mContainerService,
13193                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13194                    if (allData) {
13195                        clearDirectory(conn.mContainerService,
13196                                userEnv.buildExternalStorageAppDataDirs(packageName));
13197                        clearDirectory(conn.mContainerService,
13198                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13199                    }
13200                }
13201            } finally {
13202                mContext.unbindService(conn);
13203            }
13204        }
13205    }
13206
13207    @Override
13208    public void clearApplicationUserData(final String packageName,
13209            final IPackageDataObserver observer, final int userId) {
13210        mContext.enforceCallingOrSelfPermission(
13211                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13212        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13213        // Queue up an async operation since the package deletion may take a little while.
13214        mHandler.post(new Runnable() {
13215            public void run() {
13216                mHandler.removeCallbacks(this);
13217                final boolean succeeded;
13218                synchronized (mInstallLock) {
13219                    succeeded = clearApplicationUserDataLI(packageName, userId);
13220                }
13221                clearExternalStorageDataSync(packageName, userId, true);
13222                if (succeeded) {
13223                    // invoke DeviceStorageMonitor's update method to clear any notifications
13224                    DeviceStorageMonitorInternal
13225                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13226                    if (dsm != null) {
13227                        dsm.checkMemory();
13228                    }
13229                }
13230                if(observer != null) {
13231                    try {
13232                        observer.onRemoveCompleted(packageName, succeeded);
13233                    } catch (RemoteException e) {
13234                        Log.i(TAG, "Observer no longer exists.");
13235                    }
13236                } //end if observer
13237            } //end run
13238        });
13239    }
13240
13241    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13242        if (packageName == null) {
13243            Slog.w(TAG, "Attempt to delete null packageName.");
13244            return false;
13245        }
13246
13247        // Try finding details about the requested package
13248        PackageParser.Package pkg;
13249        synchronized (mPackages) {
13250            pkg = mPackages.get(packageName);
13251            if (pkg == null) {
13252                final PackageSetting ps = mSettings.mPackages.get(packageName);
13253                if (ps != null) {
13254                    pkg = ps.pkg;
13255                }
13256            }
13257
13258            if (pkg == null) {
13259                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13260                return false;
13261            }
13262
13263            PackageSetting ps = (PackageSetting) pkg.mExtras;
13264            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13265        }
13266
13267        // Always delete data directories for package, even if we found no other
13268        // record of app. This helps users recover from UID mismatches without
13269        // resorting to a full data wipe.
13270        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13271        if (retCode < 0) {
13272            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13273            return false;
13274        }
13275
13276        final int appId = pkg.applicationInfo.uid;
13277        removeKeystoreDataIfNeeded(userId, appId);
13278
13279        // Create a native library symlink only if we have native libraries
13280        // and if the native libraries are 32 bit libraries. We do not provide
13281        // this symlink for 64 bit libraries.
13282        if (pkg.applicationInfo.primaryCpuAbi != null &&
13283                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13284            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13285            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13286                    nativeLibPath, userId) < 0) {
13287                Slog.w(TAG, "Failed linking native library dir");
13288                return false;
13289            }
13290        }
13291
13292        return true;
13293    }
13294
13295    /**
13296     * Reverts user permission state changes (permissions and flags) in
13297     * all packages for a given user.
13298     *
13299     * @param userId The device user for which to do a reset.
13300     */
13301    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13302        final int packageCount = mPackages.size();
13303        for (int i = 0; i < packageCount; i++) {
13304            PackageParser.Package pkg = mPackages.valueAt(i);
13305            PackageSetting ps = (PackageSetting) pkg.mExtras;
13306            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13307        }
13308    }
13309
13310    /**
13311     * Reverts user permission state changes (permissions and flags).
13312     *
13313     * @param ps The package for which to reset.
13314     * @param userId The device user for which to do a reset.
13315     */
13316    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13317            final PackageSetting ps, final int userId) {
13318        if (ps.pkg == null) {
13319            return;
13320        }
13321
13322        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13323                | FLAG_PERMISSION_USER_FIXED
13324                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13325
13326        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13327                | FLAG_PERMISSION_POLICY_FIXED;
13328
13329        boolean writeInstallPermissions = false;
13330        boolean writeRuntimePermissions = false;
13331
13332        final int permissionCount = ps.pkg.requestedPermissions.size();
13333        for (int i = 0; i < permissionCount; i++) {
13334            String permission = ps.pkg.requestedPermissions.get(i);
13335
13336            BasePermission bp = mSettings.mPermissions.get(permission);
13337            if (bp == null) {
13338                continue;
13339            }
13340
13341            // If shared user we just reset the state to which only this app contributed.
13342            if (ps.sharedUser != null) {
13343                boolean used = false;
13344                final int packageCount = ps.sharedUser.packages.size();
13345                for (int j = 0; j < packageCount; j++) {
13346                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13347                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13348                            && pkg.pkg.requestedPermissions.contains(permission)) {
13349                        used = true;
13350                        break;
13351                    }
13352                }
13353                if (used) {
13354                    continue;
13355                }
13356            }
13357
13358            PermissionsState permissionsState = ps.getPermissionsState();
13359
13360            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13361
13362            // Always clear the user settable flags.
13363            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13364                    bp.name) != null;
13365            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13366                if (hasInstallState) {
13367                    writeInstallPermissions = true;
13368                } else {
13369                    writeRuntimePermissions = true;
13370                }
13371            }
13372
13373            // Below is only runtime permission handling.
13374            if (!bp.isRuntime()) {
13375                continue;
13376            }
13377
13378            // Never clobber system or policy.
13379            if ((oldFlags & policyOrSystemFlags) != 0) {
13380                continue;
13381            }
13382
13383            // If this permission was granted by default, make sure it is.
13384            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13385                if (permissionsState.grantRuntimePermission(bp, userId)
13386                        != PERMISSION_OPERATION_FAILURE) {
13387                    writeRuntimePermissions = true;
13388                }
13389            } else {
13390                // Otherwise, reset the permission.
13391                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13392                switch (revokeResult) {
13393                    case PERMISSION_OPERATION_SUCCESS: {
13394                        writeRuntimePermissions = true;
13395                    } break;
13396
13397                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13398                        writeRuntimePermissions = true;
13399                        // If gids changed for this user, kill all affected packages.
13400                        mHandler.post(new Runnable() {
13401                            @Override
13402                            public void run() {
13403                                // This has to happen with no lock held.
13404                                killSettingPackagesForUser(ps, userId,
13405                                        KILL_APP_REASON_GIDS_CHANGED);
13406                            }
13407                        });
13408                    } break;
13409                }
13410            }
13411        }
13412
13413        // Synchronously write as we are taking permissions away.
13414        if (writeRuntimePermissions) {
13415            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13416        }
13417
13418        // Synchronously write as we are taking permissions away.
13419        if (writeInstallPermissions) {
13420            mSettings.writeLPr();
13421        }
13422    }
13423
13424    /**
13425     * Remove entries from the keystore daemon. Will only remove it if the
13426     * {@code appId} is valid.
13427     */
13428    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13429        if (appId < 0) {
13430            return;
13431        }
13432
13433        final KeyStore keyStore = KeyStore.getInstance();
13434        if (keyStore != null) {
13435            if (userId == UserHandle.USER_ALL) {
13436                for (final int individual : sUserManager.getUserIds()) {
13437                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13438                }
13439            } else {
13440                keyStore.clearUid(UserHandle.getUid(userId, appId));
13441            }
13442        } else {
13443            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13444        }
13445    }
13446
13447    @Override
13448    public void deleteApplicationCacheFiles(final String packageName,
13449            final IPackageDataObserver observer) {
13450        mContext.enforceCallingOrSelfPermission(
13451                android.Manifest.permission.DELETE_CACHE_FILES, null);
13452        // Queue up an async operation since the package deletion may take a little while.
13453        final int userId = UserHandle.getCallingUserId();
13454        mHandler.post(new Runnable() {
13455            public void run() {
13456                mHandler.removeCallbacks(this);
13457                final boolean succeded;
13458                synchronized (mInstallLock) {
13459                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13460                }
13461                clearExternalStorageDataSync(packageName, userId, false);
13462                if (observer != null) {
13463                    try {
13464                        observer.onRemoveCompleted(packageName, succeded);
13465                    } catch (RemoteException e) {
13466                        Log.i(TAG, "Observer no longer exists.");
13467                    }
13468                } //end if observer
13469            } //end run
13470        });
13471    }
13472
13473    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13474        if (packageName == null) {
13475            Slog.w(TAG, "Attempt to delete null packageName.");
13476            return false;
13477        }
13478        PackageParser.Package p;
13479        synchronized (mPackages) {
13480            p = mPackages.get(packageName);
13481        }
13482        if (p == null) {
13483            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13484            return false;
13485        }
13486        final ApplicationInfo applicationInfo = p.applicationInfo;
13487        if (applicationInfo == null) {
13488            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13489            return false;
13490        }
13491        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13492        if (retCode < 0) {
13493            Slog.w(TAG, "Couldn't remove cache files for package: "
13494                       + packageName + " u" + userId);
13495            return false;
13496        }
13497        return true;
13498    }
13499
13500    @Override
13501    public void getPackageSizeInfo(final String packageName, int userHandle,
13502            final IPackageStatsObserver observer) {
13503        mContext.enforceCallingOrSelfPermission(
13504                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13505        if (packageName == null) {
13506            throw new IllegalArgumentException("Attempt to get size of null packageName");
13507        }
13508
13509        PackageStats stats = new PackageStats(packageName, userHandle);
13510
13511        /*
13512         * Queue up an async operation since the package measurement may take a
13513         * little while.
13514         */
13515        Message msg = mHandler.obtainMessage(INIT_COPY);
13516        msg.obj = new MeasureParams(stats, observer);
13517        mHandler.sendMessage(msg);
13518    }
13519
13520    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13521            PackageStats pStats) {
13522        if (packageName == null) {
13523            Slog.w(TAG, "Attempt to get size of null packageName.");
13524            return false;
13525        }
13526        PackageParser.Package p;
13527        boolean dataOnly = false;
13528        String libDirRoot = null;
13529        String asecPath = null;
13530        PackageSetting ps = null;
13531        synchronized (mPackages) {
13532            p = mPackages.get(packageName);
13533            ps = mSettings.mPackages.get(packageName);
13534            if(p == null) {
13535                dataOnly = true;
13536                if((ps == null) || (ps.pkg == null)) {
13537                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13538                    return false;
13539                }
13540                p = ps.pkg;
13541            }
13542            if (ps != null) {
13543                libDirRoot = ps.legacyNativeLibraryPathString;
13544            }
13545            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13546                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13547                if (secureContainerId != null) {
13548                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13549                }
13550            }
13551        }
13552        String publicSrcDir = null;
13553        if(!dataOnly) {
13554            final ApplicationInfo applicationInfo = p.applicationInfo;
13555            if (applicationInfo == null) {
13556                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13557                return false;
13558            }
13559            if (p.isForwardLocked()) {
13560                publicSrcDir = applicationInfo.getBaseResourcePath();
13561            }
13562        }
13563        // TODO: extend to measure size of split APKs
13564        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13565        // not just the first level.
13566        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13567        // just the primary.
13568        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13569        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13570                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13571        if (res < 0) {
13572            return false;
13573        }
13574
13575        // Fix-up for forward-locked applications in ASEC containers.
13576        if (!isExternal(p)) {
13577            pStats.codeSize += pStats.externalCodeSize;
13578            pStats.externalCodeSize = 0L;
13579        }
13580
13581        return true;
13582    }
13583
13584
13585    @Override
13586    public void addPackageToPreferred(String packageName) {
13587        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13588    }
13589
13590    @Override
13591    public void removePackageFromPreferred(String packageName) {
13592        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13593    }
13594
13595    @Override
13596    public List<PackageInfo> getPreferredPackages(int flags) {
13597        return new ArrayList<PackageInfo>();
13598    }
13599
13600    private int getUidTargetSdkVersionLockedLPr(int uid) {
13601        Object obj = mSettings.getUserIdLPr(uid);
13602        if (obj instanceof SharedUserSetting) {
13603            final SharedUserSetting sus = (SharedUserSetting) obj;
13604            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13605            final Iterator<PackageSetting> it = sus.packages.iterator();
13606            while (it.hasNext()) {
13607                final PackageSetting ps = it.next();
13608                if (ps.pkg != null) {
13609                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13610                    if (v < vers) vers = v;
13611                }
13612            }
13613            return vers;
13614        } else if (obj instanceof PackageSetting) {
13615            final PackageSetting ps = (PackageSetting) obj;
13616            if (ps.pkg != null) {
13617                return ps.pkg.applicationInfo.targetSdkVersion;
13618            }
13619        }
13620        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13621    }
13622
13623    @Override
13624    public void addPreferredActivity(IntentFilter filter, int match,
13625            ComponentName[] set, ComponentName activity, int userId) {
13626        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13627                "Adding preferred");
13628    }
13629
13630    private void addPreferredActivityInternal(IntentFilter filter, int match,
13631            ComponentName[] set, ComponentName activity, boolean always, int userId,
13632            String opname) {
13633        // writer
13634        int callingUid = Binder.getCallingUid();
13635        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13636        if (filter.countActions() == 0) {
13637            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13638            return;
13639        }
13640        synchronized (mPackages) {
13641            if (mContext.checkCallingOrSelfPermission(
13642                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13643                    != PackageManager.PERMISSION_GRANTED) {
13644                if (getUidTargetSdkVersionLockedLPr(callingUid)
13645                        < Build.VERSION_CODES.FROYO) {
13646                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13647                            + callingUid);
13648                    return;
13649                }
13650                mContext.enforceCallingOrSelfPermission(
13651                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13652            }
13653
13654            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13655            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13656                    + userId + ":");
13657            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13658            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13659            scheduleWritePackageRestrictionsLocked(userId);
13660        }
13661    }
13662
13663    @Override
13664    public void replacePreferredActivity(IntentFilter filter, int match,
13665            ComponentName[] set, ComponentName activity, int userId) {
13666        if (filter.countActions() != 1) {
13667            throw new IllegalArgumentException(
13668                    "replacePreferredActivity expects filter to have only 1 action.");
13669        }
13670        if (filter.countDataAuthorities() != 0
13671                || filter.countDataPaths() != 0
13672                || filter.countDataSchemes() > 1
13673                || filter.countDataTypes() != 0) {
13674            throw new IllegalArgumentException(
13675                    "replacePreferredActivity expects filter to have no data authorities, " +
13676                    "paths, or types; and at most one scheme.");
13677        }
13678
13679        final int callingUid = Binder.getCallingUid();
13680        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13681        synchronized (mPackages) {
13682            if (mContext.checkCallingOrSelfPermission(
13683                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13684                    != PackageManager.PERMISSION_GRANTED) {
13685                if (getUidTargetSdkVersionLockedLPr(callingUid)
13686                        < Build.VERSION_CODES.FROYO) {
13687                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13688                            + Binder.getCallingUid());
13689                    return;
13690                }
13691                mContext.enforceCallingOrSelfPermission(
13692                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13693            }
13694
13695            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13696            if (pir != null) {
13697                // Get all of the existing entries that exactly match this filter.
13698                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13699                if (existing != null && existing.size() == 1) {
13700                    PreferredActivity cur = existing.get(0);
13701                    if (DEBUG_PREFERRED) {
13702                        Slog.i(TAG, "Checking replace of preferred:");
13703                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13704                        if (!cur.mPref.mAlways) {
13705                            Slog.i(TAG, "  -- CUR; not mAlways!");
13706                        } else {
13707                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13708                            Slog.i(TAG, "  -- CUR: mSet="
13709                                    + Arrays.toString(cur.mPref.mSetComponents));
13710                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13711                            Slog.i(TAG, "  -- NEW: mMatch="
13712                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13713                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13714                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13715                        }
13716                    }
13717                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13718                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13719                            && cur.mPref.sameSet(set)) {
13720                        // Setting the preferred activity to what it happens to be already
13721                        if (DEBUG_PREFERRED) {
13722                            Slog.i(TAG, "Replacing with same preferred activity "
13723                                    + cur.mPref.mShortComponent + " for user "
13724                                    + userId + ":");
13725                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13726                        }
13727                        return;
13728                    }
13729                }
13730
13731                if (existing != null) {
13732                    if (DEBUG_PREFERRED) {
13733                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13734                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13735                    }
13736                    for (int i = 0; i < existing.size(); i++) {
13737                        PreferredActivity pa = existing.get(i);
13738                        if (DEBUG_PREFERRED) {
13739                            Slog.i(TAG, "Removing existing preferred activity "
13740                                    + pa.mPref.mComponent + ":");
13741                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13742                        }
13743                        pir.removeFilter(pa);
13744                    }
13745                }
13746            }
13747            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13748                    "Replacing preferred");
13749        }
13750    }
13751
13752    @Override
13753    public void clearPackagePreferredActivities(String packageName) {
13754        final int uid = Binder.getCallingUid();
13755        // writer
13756        synchronized (mPackages) {
13757            PackageParser.Package pkg = mPackages.get(packageName);
13758            if (pkg == null || pkg.applicationInfo.uid != uid) {
13759                if (mContext.checkCallingOrSelfPermission(
13760                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13761                        != PackageManager.PERMISSION_GRANTED) {
13762                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13763                            < Build.VERSION_CODES.FROYO) {
13764                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13765                                + Binder.getCallingUid());
13766                        return;
13767                    }
13768                    mContext.enforceCallingOrSelfPermission(
13769                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13770                }
13771            }
13772
13773            int user = UserHandle.getCallingUserId();
13774            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13775                scheduleWritePackageRestrictionsLocked(user);
13776            }
13777        }
13778    }
13779
13780    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13781    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13782        ArrayList<PreferredActivity> removed = null;
13783        boolean changed = false;
13784        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13785            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13786            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13787            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13788                continue;
13789            }
13790            Iterator<PreferredActivity> it = pir.filterIterator();
13791            while (it.hasNext()) {
13792                PreferredActivity pa = it.next();
13793                // Mark entry for removal only if it matches the package name
13794                // and the entry is of type "always".
13795                if (packageName == null ||
13796                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13797                                && pa.mPref.mAlways)) {
13798                    if (removed == null) {
13799                        removed = new ArrayList<PreferredActivity>();
13800                    }
13801                    removed.add(pa);
13802                }
13803            }
13804            if (removed != null) {
13805                for (int j=0; j<removed.size(); j++) {
13806                    PreferredActivity pa = removed.get(j);
13807                    pir.removeFilter(pa);
13808                }
13809                changed = true;
13810            }
13811        }
13812        return changed;
13813    }
13814
13815    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13816    private void clearIntentFilterVerificationsLPw(int userId) {
13817        final int packageCount = mPackages.size();
13818        for (int i = 0; i < packageCount; i++) {
13819            PackageParser.Package pkg = mPackages.valueAt(i);
13820            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13821        }
13822    }
13823
13824    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13825    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13826        if (userId == UserHandle.USER_ALL) {
13827            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13828                    sUserManager.getUserIds())) {
13829                for (int oneUserId : sUserManager.getUserIds()) {
13830                    scheduleWritePackageRestrictionsLocked(oneUserId);
13831                }
13832            }
13833        } else {
13834            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13835                scheduleWritePackageRestrictionsLocked(userId);
13836            }
13837        }
13838    }
13839
13840    void clearDefaultBrowserIfNeeded(String packageName) {
13841        for (int oneUserId : sUserManager.getUserIds()) {
13842            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13843            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13844            if (packageName.equals(defaultBrowserPackageName)) {
13845                setDefaultBrowserPackageName(null, oneUserId);
13846            }
13847        }
13848    }
13849
13850    @Override
13851    public void resetApplicationPreferences(int userId) {
13852        mContext.enforceCallingOrSelfPermission(
13853                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13854        // writer
13855        synchronized (mPackages) {
13856            final long identity = Binder.clearCallingIdentity();
13857            try {
13858                clearPackagePreferredActivitiesLPw(null, userId);
13859                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13860                // TODO: We have to reset the default SMS and Phone. This requires
13861                // significant refactoring to keep all default apps in the package
13862                // manager (cleaner but more work) or have the services provide
13863                // callbacks to the package manager to request a default app reset.
13864                applyFactoryDefaultBrowserLPw(userId);
13865                clearIntentFilterVerificationsLPw(userId);
13866                primeDomainVerificationsLPw(userId);
13867                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13868                scheduleWritePackageRestrictionsLocked(userId);
13869            } finally {
13870                Binder.restoreCallingIdentity(identity);
13871            }
13872        }
13873    }
13874
13875    @Override
13876    public int getPreferredActivities(List<IntentFilter> outFilters,
13877            List<ComponentName> outActivities, String packageName) {
13878
13879        int num = 0;
13880        final int userId = UserHandle.getCallingUserId();
13881        // reader
13882        synchronized (mPackages) {
13883            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13884            if (pir != null) {
13885                final Iterator<PreferredActivity> it = pir.filterIterator();
13886                while (it.hasNext()) {
13887                    final PreferredActivity pa = it.next();
13888                    if (packageName == null
13889                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13890                                    && pa.mPref.mAlways)) {
13891                        if (outFilters != null) {
13892                            outFilters.add(new IntentFilter(pa));
13893                        }
13894                        if (outActivities != null) {
13895                            outActivities.add(pa.mPref.mComponent);
13896                        }
13897                    }
13898                }
13899            }
13900        }
13901
13902        return num;
13903    }
13904
13905    @Override
13906    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13907            int userId) {
13908        int callingUid = Binder.getCallingUid();
13909        if (callingUid != Process.SYSTEM_UID) {
13910            throw new SecurityException(
13911                    "addPersistentPreferredActivity can only be run by the system");
13912        }
13913        if (filter.countActions() == 0) {
13914            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13915            return;
13916        }
13917        synchronized (mPackages) {
13918            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13919                    " :");
13920            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13921            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13922                    new PersistentPreferredActivity(filter, activity));
13923            scheduleWritePackageRestrictionsLocked(userId);
13924        }
13925    }
13926
13927    @Override
13928    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13929        int callingUid = Binder.getCallingUid();
13930        if (callingUid != Process.SYSTEM_UID) {
13931            throw new SecurityException(
13932                    "clearPackagePersistentPreferredActivities can only be run by the system");
13933        }
13934        ArrayList<PersistentPreferredActivity> removed = null;
13935        boolean changed = false;
13936        synchronized (mPackages) {
13937            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13938                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13939                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13940                        .valueAt(i);
13941                if (userId != thisUserId) {
13942                    continue;
13943                }
13944                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13945                while (it.hasNext()) {
13946                    PersistentPreferredActivity ppa = it.next();
13947                    // Mark entry for removal only if it matches the package name.
13948                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13949                        if (removed == null) {
13950                            removed = new ArrayList<PersistentPreferredActivity>();
13951                        }
13952                        removed.add(ppa);
13953                    }
13954                }
13955                if (removed != null) {
13956                    for (int j=0; j<removed.size(); j++) {
13957                        PersistentPreferredActivity ppa = removed.get(j);
13958                        ppir.removeFilter(ppa);
13959                    }
13960                    changed = true;
13961                }
13962            }
13963
13964            if (changed) {
13965                scheduleWritePackageRestrictionsLocked(userId);
13966            }
13967        }
13968    }
13969
13970    /**
13971     * Common machinery for picking apart a restored XML blob and passing
13972     * it to a caller-supplied functor to be applied to the running system.
13973     */
13974    private void restoreFromXml(XmlPullParser parser, int userId,
13975            String expectedStartTag, BlobXmlRestorer functor)
13976            throws IOException, XmlPullParserException {
13977        int type;
13978        while ((type = parser.next()) != XmlPullParser.START_TAG
13979                && type != XmlPullParser.END_DOCUMENT) {
13980        }
13981        if (type != XmlPullParser.START_TAG) {
13982            // oops didn't find a start tag?!
13983            if (DEBUG_BACKUP) {
13984                Slog.e(TAG, "Didn't find start tag during restore");
13985            }
13986            return;
13987        }
13988
13989        // this is supposed to be TAG_PREFERRED_BACKUP
13990        if (!expectedStartTag.equals(parser.getName())) {
13991            if (DEBUG_BACKUP) {
13992                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13993            }
13994            return;
13995        }
13996
13997        // skip interfering stuff, then we're aligned with the backing implementation
13998        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13999        functor.apply(parser, userId);
14000    }
14001
14002    private interface BlobXmlRestorer {
14003        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14004    }
14005
14006    /**
14007     * Non-Binder method, support for the backup/restore mechanism: write the
14008     * full set of preferred activities in its canonical XML format.  Returns the
14009     * XML output as a byte array, or null if there is none.
14010     */
14011    @Override
14012    public byte[] getPreferredActivityBackup(int userId) {
14013        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14014            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14015        }
14016
14017        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14018        try {
14019            final XmlSerializer serializer = new FastXmlSerializer();
14020            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14021            serializer.startDocument(null, true);
14022            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14023
14024            synchronized (mPackages) {
14025                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14026            }
14027
14028            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14029            serializer.endDocument();
14030            serializer.flush();
14031        } catch (Exception e) {
14032            if (DEBUG_BACKUP) {
14033                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14034            }
14035            return null;
14036        }
14037
14038        return dataStream.toByteArray();
14039    }
14040
14041    @Override
14042    public void restorePreferredActivities(byte[] backup, int userId) {
14043        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14044            throw new SecurityException("Only the system may call restorePreferredActivities()");
14045        }
14046
14047        try {
14048            final XmlPullParser parser = Xml.newPullParser();
14049            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14050            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14051                    new BlobXmlRestorer() {
14052                        @Override
14053                        public void apply(XmlPullParser parser, int userId)
14054                                throws XmlPullParserException, IOException {
14055                            synchronized (mPackages) {
14056                                mSettings.readPreferredActivitiesLPw(parser, userId);
14057                            }
14058                        }
14059                    } );
14060        } catch (Exception e) {
14061            if (DEBUG_BACKUP) {
14062                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14063            }
14064        }
14065    }
14066
14067    /**
14068     * Non-Binder method, support for the backup/restore mechanism: write the
14069     * default browser (etc) settings in its canonical XML format.  Returns the default
14070     * browser XML representation as a byte array, or null if there is none.
14071     */
14072    @Override
14073    public byte[] getDefaultAppsBackup(int userId) {
14074        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14075            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14076        }
14077
14078        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14079        try {
14080            final XmlSerializer serializer = new FastXmlSerializer();
14081            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14082            serializer.startDocument(null, true);
14083            serializer.startTag(null, TAG_DEFAULT_APPS);
14084
14085            synchronized (mPackages) {
14086                mSettings.writeDefaultAppsLPr(serializer, userId);
14087            }
14088
14089            serializer.endTag(null, TAG_DEFAULT_APPS);
14090            serializer.endDocument();
14091            serializer.flush();
14092        } catch (Exception e) {
14093            if (DEBUG_BACKUP) {
14094                Slog.e(TAG, "Unable to write default apps for backup", e);
14095            }
14096            return null;
14097        }
14098
14099        return dataStream.toByteArray();
14100    }
14101
14102    @Override
14103    public void restoreDefaultApps(byte[] backup, int userId) {
14104        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14105            throw new SecurityException("Only the system may call restoreDefaultApps()");
14106        }
14107
14108        try {
14109            final XmlPullParser parser = Xml.newPullParser();
14110            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14111            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14112                    new BlobXmlRestorer() {
14113                        @Override
14114                        public void apply(XmlPullParser parser, int userId)
14115                                throws XmlPullParserException, IOException {
14116                            synchronized (mPackages) {
14117                                mSettings.readDefaultAppsLPw(parser, userId);
14118                            }
14119                        }
14120                    } );
14121        } catch (Exception e) {
14122            if (DEBUG_BACKUP) {
14123                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14124            }
14125        }
14126    }
14127
14128    @Override
14129    public byte[] getIntentFilterVerificationBackup(int userId) {
14130        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14131            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14132        }
14133
14134        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14135        try {
14136            final XmlSerializer serializer = new FastXmlSerializer();
14137            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14138            serializer.startDocument(null, true);
14139            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14140
14141            synchronized (mPackages) {
14142                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14143            }
14144
14145            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14146            serializer.endDocument();
14147            serializer.flush();
14148        } catch (Exception e) {
14149            if (DEBUG_BACKUP) {
14150                Slog.e(TAG, "Unable to write default apps for backup", e);
14151            }
14152            return null;
14153        }
14154
14155        return dataStream.toByteArray();
14156    }
14157
14158    @Override
14159    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14160        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14161            throw new SecurityException("Only the system may call restorePreferredActivities()");
14162        }
14163
14164        try {
14165            final XmlPullParser parser = Xml.newPullParser();
14166            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14167            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14168                    new BlobXmlRestorer() {
14169                        @Override
14170                        public void apply(XmlPullParser parser, int userId)
14171                                throws XmlPullParserException, IOException {
14172                            synchronized (mPackages) {
14173                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14174                                mSettings.writeLPr();
14175                            }
14176                        }
14177                    } );
14178        } catch (Exception e) {
14179            if (DEBUG_BACKUP) {
14180                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14181            }
14182        }
14183    }
14184
14185    @Override
14186    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14187            int sourceUserId, int targetUserId, int flags) {
14188        mContext.enforceCallingOrSelfPermission(
14189                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14190        int callingUid = Binder.getCallingUid();
14191        enforceOwnerRights(ownerPackage, callingUid);
14192        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14193        if (intentFilter.countActions() == 0) {
14194            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14195            return;
14196        }
14197        synchronized (mPackages) {
14198            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14199                    ownerPackage, targetUserId, flags);
14200            CrossProfileIntentResolver resolver =
14201                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14202            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14203            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14204            if (existing != null) {
14205                int size = existing.size();
14206                for (int i = 0; i < size; i++) {
14207                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14208                        return;
14209                    }
14210                }
14211            }
14212            resolver.addFilter(newFilter);
14213            scheduleWritePackageRestrictionsLocked(sourceUserId);
14214        }
14215    }
14216
14217    @Override
14218    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14219        mContext.enforceCallingOrSelfPermission(
14220                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14221        int callingUid = Binder.getCallingUid();
14222        enforceOwnerRights(ownerPackage, callingUid);
14223        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14224        synchronized (mPackages) {
14225            CrossProfileIntentResolver resolver =
14226                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14227            ArraySet<CrossProfileIntentFilter> set =
14228                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14229            for (CrossProfileIntentFilter filter : set) {
14230                if (filter.getOwnerPackage().equals(ownerPackage)) {
14231                    resolver.removeFilter(filter);
14232                }
14233            }
14234            scheduleWritePackageRestrictionsLocked(sourceUserId);
14235        }
14236    }
14237
14238    // Enforcing that callingUid is owning pkg on userId
14239    private void enforceOwnerRights(String pkg, int callingUid) {
14240        // The system owns everything.
14241        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14242            return;
14243        }
14244        int callingUserId = UserHandle.getUserId(callingUid);
14245        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14246        if (pi == null) {
14247            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14248                    + callingUserId);
14249        }
14250        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14251            throw new SecurityException("Calling uid " + callingUid
14252                    + " does not own package " + pkg);
14253        }
14254    }
14255
14256    @Override
14257    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14258        Intent intent = new Intent(Intent.ACTION_MAIN);
14259        intent.addCategory(Intent.CATEGORY_HOME);
14260
14261        final int callingUserId = UserHandle.getCallingUserId();
14262        List<ResolveInfo> list = queryIntentActivities(intent, null,
14263                PackageManager.GET_META_DATA, callingUserId);
14264        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14265                true, false, false, callingUserId);
14266
14267        allHomeCandidates.clear();
14268        if (list != null) {
14269            for (ResolveInfo ri : list) {
14270                allHomeCandidates.add(ri);
14271            }
14272        }
14273        return (preferred == null || preferred.activityInfo == null)
14274                ? null
14275                : new ComponentName(preferred.activityInfo.packageName,
14276                        preferred.activityInfo.name);
14277    }
14278
14279    @Override
14280    public void setApplicationEnabledSetting(String appPackageName,
14281            int newState, int flags, int userId, String callingPackage) {
14282        if (!sUserManager.exists(userId)) return;
14283        if (callingPackage == null) {
14284            callingPackage = Integer.toString(Binder.getCallingUid());
14285        }
14286        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14287    }
14288
14289    @Override
14290    public void setComponentEnabledSetting(ComponentName componentName,
14291            int newState, int flags, int userId) {
14292        if (!sUserManager.exists(userId)) return;
14293        setEnabledSetting(componentName.getPackageName(),
14294                componentName.getClassName(), newState, flags, userId, null);
14295    }
14296
14297    private void setEnabledSetting(final String packageName, String className, int newState,
14298            final int flags, int userId, String callingPackage) {
14299        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14300              || newState == COMPONENT_ENABLED_STATE_ENABLED
14301              || newState == COMPONENT_ENABLED_STATE_DISABLED
14302              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14303              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14304            throw new IllegalArgumentException("Invalid new component state: "
14305                    + newState);
14306        }
14307        PackageSetting pkgSetting;
14308        final int uid = Binder.getCallingUid();
14309        final int permission = mContext.checkCallingOrSelfPermission(
14310                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14311        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14312        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14313        boolean sendNow = false;
14314        boolean isApp = (className == null);
14315        String componentName = isApp ? packageName : className;
14316        int packageUid = -1;
14317        ArrayList<String> components;
14318
14319        // writer
14320        synchronized (mPackages) {
14321            pkgSetting = mSettings.mPackages.get(packageName);
14322            if (pkgSetting == null) {
14323                if (className == null) {
14324                    throw new IllegalArgumentException(
14325                            "Unknown package: " + packageName);
14326                }
14327                throw new IllegalArgumentException(
14328                        "Unknown component: " + packageName
14329                        + "/" + className);
14330            }
14331            // Allow root and verify that userId is not being specified by a different user
14332            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14333                throw new SecurityException(
14334                        "Permission Denial: attempt to change component state from pid="
14335                        + Binder.getCallingPid()
14336                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14337            }
14338            if (className == null) {
14339                // We're dealing with an application/package level state change
14340                if (pkgSetting.getEnabled(userId) == newState) {
14341                    // Nothing to do
14342                    return;
14343                }
14344                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14345                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14346                    // Don't care about who enables an app.
14347                    callingPackage = null;
14348                }
14349                pkgSetting.setEnabled(newState, userId, callingPackage);
14350                // pkgSetting.pkg.mSetEnabled = newState;
14351            } else {
14352                // We're dealing with a component level state change
14353                // First, verify that this is a valid class name.
14354                PackageParser.Package pkg = pkgSetting.pkg;
14355                if (pkg == null || !pkg.hasComponentClassName(className)) {
14356                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14357                        throw new IllegalArgumentException("Component class " + className
14358                                + " does not exist in " + packageName);
14359                    } else {
14360                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14361                                + className + " does not exist in " + packageName);
14362                    }
14363                }
14364                switch (newState) {
14365                case COMPONENT_ENABLED_STATE_ENABLED:
14366                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14367                        return;
14368                    }
14369                    break;
14370                case COMPONENT_ENABLED_STATE_DISABLED:
14371                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14372                        return;
14373                    }
14374                    break;
14375                case COMPONENT_ENABLED_STATE_DEFAULT:
14376                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14377                        return;
14378                    }
14379                    break;
14380                default:
14381                    Slog.e(TAG, "Invalid new component state: " + newState);
14382                    return;
14383                }
14384            }
14385            scheduleWritePackageRestrictionsLocked(userId);
14386            components = mPendingBroadcasts.get(userId, packageName);
14387            final boolean newPackage = components == null;
14388            if (newPackage) {
14389                components = new ArrayList<String>();
14390            }
14391            if (!components.contains(componentName)) {
14392                components.add(componentName);
14393            }
14394            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14395                sendNow = true;
14396                // Purge entry from pending broadcast list if another one exists already
14397                // since we are sending one right away.
14398                mPendingBroadcasts.remove(userId, packageName);
14399            } else {
14400                if (newPackage) {
14401                    mPendingBroadcasts.put(userId, packageName, components);
14402                }
14403                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14404                    // Schedule a message
14405                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14406                }
14407            }
14408        }
14409
14410        long callingId = Binder.clearCallingIdentity();
14411        try {
14412            if (sendNow) {
14413                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14414                sendPackageChangedBroadcast(packageName,
14415                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14416            }
14417        } finally {
14418            Binder.restoreCallingIdentity(callingId);
14419        }
14420    }
14421
14422    private void sendPackageChangedBroadcast(String packageName,
14423            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14424        if (DEBUG_INSTALL)
14425            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14426                    + componentNames);
14427        Bundle extras = new Bundle(4);
14428        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14429        String nameList[] = new String[componentNames.size()];
14430        componentNames.toArray(nameList);
14431        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14432        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14433        extras.putInt(Intent.EXTRA_UID, packageUid);
14434        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14435                new int[] {UserHandle.getUserId(packageUid)});
14436    }
14437
14438    @Override
14439    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14440        if (!sUserManager.exists(userId)) return;
14441        final int uid = Binder.getCallingUid();
14442        final int permission = mContext.checkCallingOrSelfPermission(
14443                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14444        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14445        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14446        // writer
14447        synchronized (mPackages) {
14448            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14449                    allowedByPermission, uid, userId)) {
14450                scheduleWritePackageRestrictionsLocked(userId);
14451            }
14452        }
14453    }
14454
14455    @Override
14456    public String getInstallerPackageName(String packageName) {
14457        // reader
14458        synchronized (mPackages) {
14459            return mSettings.getInstallerPackageNameLPr(packageName);
14460        }
14461    }
14462
14463    @Override
14464    public int getApplicationEnabledSetting(String packageName, int userId) {
14465        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14466        int uid = Binder.getCallingUid();
14467        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14468        // reader
14469        synchronized (mPackages) {
14470            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14471        }
14472    }
14473
14474    @Override
14475    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14476        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14477        int uid = Binder.getCallingUid();
14478        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14479        // reader
14480        synchronized (mPackages) {
14481            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14482        }
14483    }
14484
14485    @Override
14486    public void enterSafeMode() {
14487        enforceSystemOrRoot("Only the system can request entering safe mode");
14488
14489        if (!mSystemReady) {
14490            mSafeMode = true;
14491        }
14492    }
14493
14494    @Override
14495    public void systemReady() {
14496        mSystemReady = true;
14497
14498        // Read the compatibilty setting when the system is ready.
14499        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14500                mContext.getContentResolver(),
14501                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14502        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14503        if (DEBUG_SETTINGS) {
14504            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14505        }
14506
14507        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14508
14509        synchronized (mPackages) {
14510            // Verify that all of the preferred activity components actually
14511            // exist.  It is possible for applications to be updated and at
14512            // that point remove a previously declared activity component that
14513            // had been set as a preferred activity.  We try to clean this up
14514            // the next time we encounter that preferred activity, but it is
14515            // possible for the user flow to never be able to return to that
14516            // situation so here we do a sanity check to make sure we haven't
14517            // left any junk around.
14518            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14519            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14520                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14521                removed.clear();
14522                for (PreferredActivity pa : pir.filterSet()) {
14523                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14524                        removed.add(pa);
14525                    }
14526                }
14527                if (removed.size() > 0) {
14528                    for (int r=0; r<removed.size(); r++) {
14529                        PreferredActivity pa = removed.get(r);
14530                        Slog.w(TAG, "Removing dangling preferred activity: "
14531                                + pa.mPref.mComponent);
14532                        pir.removeFilter(pa);
14533                    }
14534                    mSettings.writePackageRestrictionsLPr(
14535                            mSettings.mPreferredActivities.keyAt(i));
14536                }
14537            }
14538
14539            for (int userId : UserManagerService.getInstance().getUserIds()) {
14540                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14541                    grantPermissionsUserIds = ArrayUtils.appendInt(
14542                            grantPermissionsUserIds, userId);
14543                }
14544            }
14545        }
14546        sUserManager.systemReady();
14547
14548        // If we upgraded grant all default permissions before kicking off.
14549        for (int userId : grantPermissionsUserIds) {
14550            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14551        }
14552
14553        // Kick off any messages waiting for system ready
14554        if (mPostSystemReadyMessages != null) {
14555            for (Message msg : mPostSystemReadyMessages) {
14556                msg.sendToTarget();
14557            }
14558            mPostSystemReadyMessages = null;
14559        }
14560
14561        // Watch for external volumes that come and go over time
14562        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14563        storage.registerListener(mStorageListener);
14564
14565        mInstallerService.systemReady();
14566        mPackageDexOptimizer.systemReady();
14567
14568        MountServiceInternal mountServiceInternal = LocalServices.getService(
14569                MountServiceInternal.class);
14570        mountServiceInternal.addExternalStoragePolicy(
14571                new MountServiceInternal.ExternalStorageMountPolicy() {
14572            @Override
14573            public int getMountMode(int uid, String packageName) {
14574                if (Process.isIsolated(uid)) {
14575                    return Zygote.MOUNT_EXTERNAL_NONE;
14576                }
14577                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14578                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14579                }
14580                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14581                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14582                }
14583                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14584                    return Zygote.MOUNT_EXTERNAL_READ;
14585                }
14586                return Zygote.MOUNT_EXTERNAL_WRITE;
14587            }
14588
14589            @Override
14590            public boolean hasExternalStorage(int uid, String packageName) {
14591                return true;
14592            }
14593        });
14594    }
14595
14596    @Override
14597    public boolean isSafeMode() {
14598        return mSafeMode;
14599    }
14600
14601    @Override
14602    public boolean hasSystemUidErrors() {
14603        return mHasSystemUidErrors;
14604    }
14605
14606    static String arrayToString(int[] array) {
14607        StringBuffer buf = new StringBuffer(128);
14608        buf.append('[');
14609        if (array != null) {
14610            for (int i=0; i<array.length; i++) {
14611                if (i > 0) buf.append(", ");
14612                buf.append(array[i]);
14613            }
14614        }
14615        buf.append(']');
14616        return buf.toString();
14617    }
14618
14619    static class DumpState {
14620        public static final int DUMP_LIBS = 1 << 0;
14621        public static final int DUMP_FEATURES = 1 << 1;
14622        public static final int DUMP_RESOLVERS = 1 << 2;
14623        public static final int DUMP_PERMISSIONS = 1 << 3;
14624        public static final int DUMP_PACKAGES = 1 << 4;
14625        public static final int DUMP_SHARED_USERS = 1 << 5;
14626        public static final int DUMP_MESSAGES = 1 << 6;
14627        public static final int DUMP_PROVIDERS = 1 << 7;
14628        public static final int DUMP_VERIFIERS = 1 << 8;
14629        public static final int DUMP_PREFERRED = 1 << 9;
14630        public static final int DUMP_PREFERRED_XML = 1 << 10;
14631        public static final int DUMP_KEYSETS = 1 << 11;
14632        public static final int DUMP_VERSION = 1 << 12;
14633        public static final int DUMP_INSTALLS = 1 << 13;
14634        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14635        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14636
14637        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14638
14639        private int mTypes;
14640
14641        private int mOptions;
14642
14643        private boolean mTitlePrinted;
14644
14645        private SharedUserSetting mSharedUser;
14646
14647        public boolean isDumping(int type) {
14648            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14649                return true;
14650            }
14651
14652            return (mTypes & type) != 0;
14653        }
14654
14655        public void setDump(int type) {
14656            mTypes |= type;
14657        }
14658
14659        public boolean isOptionEnabled(int option) {
14660            return (mOptions & option) != 0;
14661        }
14662
14663        public void setOptionEnabled(int option) {
14664            mOptions |= option;
14665        }
14666
14667        public boolean onTitlePrinted() {
14668            final boolean printed = mTitlePrinted;
14669            mTitlePrinted = true;
14670            return printed;
14671        }
14672
14673        public boolean getTitlePrinted() {
14674            return mTitlePrinted;
14675        }
14676
14677        public void setTitlePrinted(boolean enabled) {
14678            mTitlePrinted = enabled;
14679        }
14680
14681        public SharedUserSetting getSharedUser() {
14682            return mSharedUser;
14683        }
14684
14685        public void setSharedUser(SharedUserSetting user) {
14686            mSharedUser = user;
14687        }
14688    }
14689
14690    @Override
14691    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14692        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14693                != PackageManager.PERMISSION_GRANTED) {
14694            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14695                    + Binder.getCallingPid()
14696                    + ", uid=" + Binder.getCallingUid()
14697                    + " without permission "
14698                    + android.Manifest.permission.DUMP);
14699            return;
14700        }
14701
14702        DumpState dumpState = new DumpState();
14703        boolean fullPreferred = false;
14704        boolean checkin = false;
14705
14706        String packageName = null;
14707        ArraySet<String> permissionNames = null;
14708
14709        int opti = 0;
14710        while (opti < args.length) {
14711            String opt = args[opti];
14712            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14713                break;
14714            }
14715            opti++;
14716
14717            if ("-a".equals(opt)) {
14718                // Right now we only know how to print all.
14719            } else if ("-h".equals(opt)) {
14720                pw.println("Package manager dump options:");
14721                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14722                pw.println("    --checkin: dump for a checkin");
14723                pw.println("    -f: print details of intent filters");
14724                pw.println("    -h: print this help");
14725                pw.println("  cmd may be one of:");
14726                pw.println("    l[ibraries]: list known shared libraries");
14727                pw.println("    f[ibraries]: list device features");
14728                pw.println("    k[eysets]: print known keysets");
14729                pw.println("    r[esolvers]: dump intent resolvers");
14730                pw.println("    perm[issions]: dump permissions");
14731                pw.println("    permission [name ...]: dump declaration and use of given permission");
14732                pw.println("    pref[erred]: print preferred package settings");
14733                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14734                pw.println("    prov[iders]: dump content providers");
14735                pw.println("    p[ackages]: dump installed packages");
14736                pw.println("    s[hared-users]: dump shared user IDs");
14737                pw.println("    m[essages]: print collected runtime messages");
14738                pw.println("    v[erifiers]: print package verifier info");
14739                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14740                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14741                pw.println("    version: print database version info");
14742                pw.println("    write: write current settings now");
14743                pw.println("    installs: details about install sessions");
14744                pw.println("    <package.name>: info about given package");
14745                return;
14746            } else if ("--checkin".equals(opt)) {
14747                checkin = true;
14748            } else if ("-f".equals(opt)) {
14749                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14750            } else {
14751                pw.println("Unknown argument: " + opt + "; use -h for help");
14752            }
14753        }
14754
14755        // Is the caller requesting to dump a particular piece of data?
14756        if (opti < args.length) {
14757            String cmd = args[opti];
14758            opti++;
14759            // Is this a package name?
14760            if ("android".equals(cmd) || cmd.contains(".")) {
14761                packageName = cmd;
14762                // When dumping a single package, we always dump all of its
14763                // filter information since the amount of data will be reasonable.
14764                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14765            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14766                dumpState.setDump(DumpState.DUMP_LIBS);
14767            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14768                dumpState.setDump(DumpState.DUMP_FEATURES);
14769            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14770                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14771            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14772                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14773            } else if ("permission".equals(cmd)) {
14774                if (opti >= args.length) {
14775                    pw.println("Error: permission requires permission name");
14776                    return;
14777                }
14778                permissionNames = new ArraySet<>();
14779                while (opti < args.length) {
14780                    permissionNames.add(args[opti]);
14781                    opti++;
14782                }
14783                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14784                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14785            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14786                dumpState.setDump(DumpState.DUMP_PREFERRED);
14787            } else if ("preferred-xml".equals(cmd)) {
14788                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14789                if (opti < args.length && "--full".equals(args[opti])) {
14790                    fullPreferred = true;
14791                    opti++;
14792                }
14793            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14794                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14795            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14796                dumpState.setDump(DumpState.DUMP_PACKAGES);
14797            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14798                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14799            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14800                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14801            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14802                dumpState.setDump(DumpState.DUMP_MESSAGES);
14803            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14804                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14805            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14806                    || "intent-filter-verifiers".equals(cmd)) {
14807                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14808            } else if ("version".equals(cmd)) {
14809                dumpState.setDump(DumpState.DUMP_VERSION);
14810            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14811                dumpState.setDump(DumpState.DUMP_KEYSETS);
14812            } else if ("installs".equals(cmd)) {
14813                dumpState.setDump(DumpState.DUMP_INSTALLS);
14814            } else if ("write".equals(cmd)) {
14815                synchronized (mPackages) {
14816                    mSettings.writeLPr();
14817                    pw.println("Settings written.");
14818                    return;
14819                }
14820            }
14821        }
14822
14823        if (checkin) {
14824            pw.println("vers,1");
14825        }
14826
14827        // reader
14828        synchronized (mPackages) {
14829            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14830                if (!checkin) {
14831                    if (dumpState.onTitlePrinted())
14832                        pw.println();
14833                    pw.println("Database versions:");
14834                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14835                }
14836            }
14837
14838            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14839                if (!checkin) {
14840                    if (dumpState.onTitlePrinted())
14841                        pw.println();
14842                    pw.println("Verifiers:");
14843                    pw.print("  Required: ");
14844                    pw.print(mRequiredVerifierPackage);
14845                    pw.print(" (uid=");
14846                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14847                    pw.println(")");
14848                } else if (mRequiredVerifierPackage != null) {
14849                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14850                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14851                }
14852            }
14853
14854            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14855                    packageName == null) {
14856                if (mIntentFilterVerifierComponent != null) {
14857                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14858                    if (!checkin) {
14859                        if (dumpState.onTitlePrinted())
14860                            pw.println();
14861                        pw.println("Intent Filter Verifier:");
14862                        pw.print("  Using: ");
14863                        pw.print(verifierPackageName);
14864                        pw.print(" (uid=");
14865                        pw.print(getPackageUid(verifierPackageName, 0));
14866                        pw.println(")");
14867                    } else if (verifierPackageName != null) {
14868                        pw.print("ifv,"); pw.print(verifierPackageName);
14869                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14870                    }
14871                } else {
14872                    pw.println();
14873                    pw.println("No Intent Filter Verifier available!");
14874                }
14875            }
14876
14877            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14878                boolean printedHeader = false;
14879                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14880                while (it.hasNext()) {
14881                    String name = it.next();
14882                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14883                    if (!checkin) {
14884                        if (!printedHeader) {
14885                            if (dumpState.onTitlePrinted())
14886                                pw.println();
14887                            pw.println("Libraries:");
14888                            printedHeader = true;
14889                        }
14890                        pw.print("  ");
14891                    } else {
14892                        pw.print("lib,");
14893                    }
14894                    pw.print(name);
14895                    if (!checkin) {
14896                        pw.print(" -> ");
14897                    }
14898                    if (ent.path != null) {
14899                        if (!checkin) {
14900                            pw.print("(jar) ");
14901                            pw.print(ent.path);
14902                        } else {
14903                            pw.print(",jar,");
14904                            pw.print(ent.path);
14905                        }
14906                    } else {
14907                        if (!checkin) {
14908                            pw.print("(apk) ");
14909                            pw.print(ent.apk);
14910                        } else {
14911                            pw.print(",apk,");
14912                            pw.print(ent.apk);
14913                        }
14914                    }
14915                    pw.println();
14916                }
14917            }
14918
14919            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14920                if (dumpState.onTitlePrinted())
14921                    pw.println();
14922                if (!checkin) {
14923                    pw.println("Features:");
14924                }
14925                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14926                while (it.hasNext()) {
14927                    String name = it.next();
14928                    if (!checkin) {
14929                        pw.print("  ");
14930                    } else {
14931                        pw.print("feat,");
14932                    }
14933                    pw.println(name);
14934                }
14935            }
14936
14937            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14938                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14939                        : "Activity Resolver Table:", "  ", packageName,
14940                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14941                    dumpState.setTitlePrinted(true);
14942                }
14943                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14944                        : "Receiver Resolver Table:", "  ", packageName,
14945                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14946                    dumpState.setTitlePrinted(true);
14947                }
14948                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14949                        : "Service Resolver Table:", "  ", packageName,
14950                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14951                    dumpState.setTitlePrinted(true);
14952                }
14953                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14954                        : "Provider Resolver Table:", "  ", packageName,
14955                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14956                    dumpState.setTitlePrinted(true);
14957                }
14958            }
14959
14960            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14961                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14962                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14963                    int user = mSettings.mPreferredActivities.keyAt(i);
14964                    if (pir.dump(pw,
14965                            dumpState.getTitlePrinted()
14966                                ? "\nPreferred Activities User " + user + ":"
14967                                : "Preferred Activities User " + user + ":", "  ",
14968                            packageName, true, false)) {
14969                        dumpState.setTitlePrinted(true);
14970                    }
14971                }
14972            }
14973
14974            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14975                pw.flush();
14976                FileOutputStream fout = new FileOutputStream(fd);
14977                BufferedOutputStream str = new BufferedOutputStream(fout);
14978                XmlSerializer serializer = new FastXmlSerializer();
14979                try {
14980                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14981                    serializer.startDocument(null, true);
14982                    serializer.setFeature(
14983                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14984                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14985                    serializer.endDocument();
14986                    serializer.flush();
14987                } catch (IllegalArgumentException e) {
14988                    pw.println("Failed writing: " + e);
14989                } catch (IllegalStateException e) {
14990                    pw.println("Failed writing: " + e);
14991                } catch (IOException e) {
14992                    pw.println("Failed writing: " + e);
14993                }
14994            }
14995
14996            if (!checkin
14997                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14998                    && packageName == null) {
14999                pw.println();
15000                int count = mSettings.mPackages.size();
15001                if (count == 0) {
15002                    pw.println("No applications!");
15003                    pw.println();
15004                } else {
15005                    final String prefix = "  ";
15006                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15007                    if (allPackageSettings.size() == 0) {
15008                        pw.println("No domain preferred apps!");
15009                        pw.println();
15010                    } else {
15011                        pw.println("App verification status:");
15012                        pw.println();
15013                        count = 0;
15014                        for (PackageSetting ps : allPackageSettings) {
15015                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15016                            if (ivi == null || ivi.getPackageName() == null) continue;
15017                            pw.println(prefix + "Package: " + ivi.getPackageName());
15018                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15019                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15020                            pw.println();
15021                            count++;
15022                        }
15023                        if (count == 0) {
15024                            pw.println(prefix + "No app verification established.");
15025                            pw.println();
15026                        }
15027                        for (int userId : sUserManager.getUserIds()) {
15028                            pw.println("App linkages for user " + userId + ":");
15029                            pw.println();
15030                            count = 0;
15031                            for (PackageSetting ps : allPackageSettings) {
15032                                final long status = ps.getDomainVerificationStatusForUser(userId);
15033                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15034                                    continue;
15035                                }
15036                                pw.println(prefix + "Package: " + ps.name);
15037                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15038                                String statusStr = IntentFilterVerificationInfo.
15039                                        getStatusStringFromValue(status);
15040                                pw.println(prefix + "Status:  " + statusStr);
15041                                pw.println();
15042                                count++;
15043                            }
15044                            if (count == 0) {
15045                                pw.println(prefix + "No configured app linkages.");
15046                                pw.println();
15047                            }
15048                        }
15049                    }
15050                }
15051            }
15052
15053            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15054                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15055                if (packageName == null && permissionNames == null) {
15056                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15057                        if (iperm == 0) {
15058                            if (dumpState.onTitlePrinted())
15059                                pw.println();
15060                            pw.println("AppOp Permissions:");
15061                        }
15062                        pw.print("  AppOp Permission ");
15063                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15064                        pw.println(":");
15065                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15066                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15067                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15068                        }
15069                    }
15070                }
15071            }
15072
15073            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15074                boolean printedSomething = false;
15075                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15076                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15077                        continue;
15078                    }
15079                    if (!printedSomething) {
15080                        if (dumpState.onTitlePrinted())
15081                            pw.println();
15082                        pw.println("Registered ContentProviders:");
15083                        printedSomething = true;
15084                    }
15085                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15086                    pw.print("    "); pw.println(p.toString());
15087                }
15088                printedSomething = false;
15089                for (Map.Entry<String, PackageParser.Provider> entry :
15090                        mProvidersByAuthority.entrySet()) {
15091                    PackageParser.Provider p = entry.getValue();
15092                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15093                        continue;
15094                    }
15095                    if (!printedSomething) {
15096                        if (dumpState.onTitlePrinted())
15097                            pw.println();
15098                        pw.println("ContentProvider Authorities:");
15099                        printedSomething = true;
15100                    }
15101                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15102                    pw.print("    "); pw.println(p.toString());
15103                    if (p.info != null && p.info.applicationInfo != null) {
15104                        final String appInfo = p.info.applicationInfo.toString();
15105                        pw.print("      applicationInfo="); pw.println(appInfo);
15106                    }
15107                }
15108            }
15109
15110            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15111                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15112            }
15113
15114            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15115                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15116            }
15117
15118            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15119                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15120            }
15121
15122            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15123                // XXX should handle packageName != null by dumping only install data that
15124                // the given package is involved with.
15125                if (dumpState.onTitlePrinted()) pw.println();
15126                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15127            }
15128
15129            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15130                if (dumpState.onTitlePrinted()) pw.println();
15131                mSettings.dumpReadMessagesLPr(pw, dumpState);
15132
15133                pw.println();
15134                pw.println("Package warning messages:");
15135                BufferedReader in = null;
15136                String line = null;
15137                try {
15138                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15139                    while ((line = in.readLine()) != null) {
15140                        if (line.contains("ignored: updated version")) continue;
15141                        pw.println(line);
15142                    }
15143                } catch (IOException ignored) {
15144                } finally {
15145                    IoUtils.closeQuietly(in);
15146                }
15147            }
15148
15149            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15150                BufferedReader in = null;
15151                String line = null;
15152                try {
15153                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15154                    while ((line = in.readLine()) != null) {
15155                        if (line.contains("ignored: updated version")) continue;
15156                        pw.print("msg,");
15157                        pw.println(line);
15158                    }
15159                } catch (IOException ignored) {
15160                } finally {
15161                    IoUtils.closeQuietly(in);
15162                }
15163            }
15164        }
15165    }
15166
15167    private String dumpDomainString(String packageName) {
15168        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15169        List<IntentFilter> filters = getAllIntentFilters(packageName);
15170
15171        ArraySet<String> result = new ArraySet<>();
15172        if (iviList.size() > 0) {
15173            for (IntentFilterVerificationInfo ivi : iviList) {
15174                for (String host : ivi.getDomains()) {
15175                    result.add(host);
15176                }
15177            }
15178        }
15179        if (filters != null && filters.size() > 0) {
15180            for (IntentFilter filter : filters) {
15181                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15182                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15183                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15184                    result.addAll(filter.getHostsList());
15185                }
15186            }
15187        }
15188
15189        StringBuilder sb = new StringBuilder(result.size() * 16);
15190        for (String domain : result) {
15191            if (sb.length() > 0) sb.append(" ");
15192            sb.append(domain);
15193        }
15194        return sb.toString();
15195    }
15196
15197    // ------- apps on sdcard specific code -------
15198    static final boolean DEBUG_SD_INSTALL = false;
15199
15200    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15201
15202    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15203
15204    private boolean mMediaMounted = false;
15205
15206    static String getEncryptKey() {
15207        try {
15208            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15209                    SD_ENCRYPTION_KEYSTORE_NAME);
15210            if (sdEncKey == null) {
15211                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15212                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15213                if (sdEncKey == null) {
15214                    Slog.e(TAG, "Failed to create encryption keys");
15215                    return null;
15216                }
15217            }
15218            return sdEncKey;
15219        } catch (NoSuchAlgorithmException nsae) {
15220            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15221            return null;
15222        } catch (IOException ioe) {
15223            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15224            return null;
15225        }
15226    }
15227
15228    /*
15229     * Update media status on PackageManager.
15230     */
15231    @Override
15232    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15233        int callingUid = Binder.getCallingUid();
15234        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15235            throw new SecurityException("Media status can only be updated by the system");
15236        }
15237        // reader; this apparently protects mMediaMounted, but should probably
15238        // be a different lock in that case.
15239        synchronized (mPackages) {
15240            Log.i(TAG, "Updating external media status from "
15241                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15242                    + (mediaStatus ? "mounted" : "unmounted"));
15243            if (DEBUG_SD_INSTALL)
15244                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15245                        + ", mMediaMounted=" + mMediaMounted);
15246            if (mediaStatus == mMediaMounted) {
15247                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15248                        : 0, -1);
15249                mHandler.sendMessage(msg);
15250                return;
15251            }
15252            mMediaMounted = mediaStatus;
15253        }
15254        // Queue up an async operation since the package installation may take a
15255        // little while.
15256        mHandler.post(new Runnable() {
15257            public void run() {
15258                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15259            }
15260        });
15261    }
15262
15263    /**
15264     * Called by MountService when the initial ASECs to scan are available.
15265     * Should block until all the ASEC containers are finished being scanned.
15266     */
15267    public void scanAvailableAsecs() {
15268        updateExternalMediaStatusInner(true, false, false);
15269        if (mShouldRestoreconData) {
15270            SELinuxMMAC.setRestoreconDone();
15271            mShouldRestoreconData = false;
15272        }
15273    }
15274
15275    /*
15276     * Collect information of applications on external media, map them against
15277     * existing containers and update information based on current mount status.
15278     * Please note that we always have to report status if reportStatus has been
15279     * set to true especially when unloading packages.
15280     */
15281    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15282            boolean externalStorage) {
15283        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15284        int[] uidArr = EmptyArray.INT;
15285
15286        final String[] list = PackageHelper.getSecureContainerList();
15287        if (ArrayUtils.isEmpty(list)) {
15288            Log.i(TAG, "No secure containers found");
15289        } else {
15290            // Process list of secure containers and categorize them
15291            // as active or stale based on their package internal state.
15292
15293            // reader
15294            synchronized (mPackages) {
15295                for (String cid : list) {
15296                    // Leave stages untouched for now; installer service owns them
15297                    if (PackageInstallerService.isStageName(cid)) continue;
15298
15299                    if (DEBUG_SD_INSTALL)
15300                        Log.i(TAG, "Processing container " + cid);
15301                    String pkgName = getAsecPackageName(cid);
15302                    if (pkgName == null) {
15303                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15304                        continue;
15305                    }
15306                    if (DEBUG_SD_INSTALL)
15307                        Log.i(TAG, "Looking for pkg : " + pkgName);
15308
15309                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15310                    if (ps == null) {
15311                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15312                        continue;
15313                    }
15314
15315                    /*
15316                     * Skip packages that are not external if we're unmounting
15317                     * external storage.
15318                     */
15319                    if (externalStorage && !isMounted && !isExternal(ps)) {
15320                        continue;
15321                    }
15322
15323                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15324                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15325                    // The package status is changed only if the code path
15326                    // matches between settings and the container id.
15327                    if (ps.codePathString != null
15328                            && ps.codePathString.startsWith(args.getCodePath())) {
15329                        if (DEBUG_SD_INSTALL) {
15330                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15331                                    + " at code path: " + ps.codePathString);
15332                        }
15333
15334                        // We do have a valid package installed on sdcard
15335                        processCids.put(args, ps.codePathString);
15336                        final int uid = ps.appId;
15337                        if (uid != -1) {
15338                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15339                        }
15340                    } else {
15341                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15342                                + ps.codePathString);
15343                    }
15344                }
15345            }
15346
15347            Arrays.sort(uidArr);
15348        }
15349
15350        // Process packages with valid entries.
15351        if (isMounted) {
15352            if (DEBUG_SD_INSTALL)
15353                Log.i(TAG, "Loading packages");
15354            loadMediaPackages(processCids, uidArr);
15355            startCleaningPackages();
15356            mInstallerService.onSecureContainersAvailable();
15357        } else {
15358            if (DEBUG_SD_INSTALL)
15359                Log.i(TAG, "Unloading packages");
15360            unloadMediaPackages(processCids, uidArr, reportStatus);
15361        }
15362    }
15363
15364    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15365            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15366        final int size = infos.size();
15367        final String[] packageNames = new String[size];
15368        final int[] packageUids = new int[size];
15369        for (int i = 0; i < size; i++) {
15370            final ApplicationInfo info = infos.get(i);
15371            packageNames[i] = info.packageName;
15372            packageUids[i] = info.uid;
15373        }
15374        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15375                finishedReceiver);
15376    }
15377
15378    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15379            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15380        sendResourcesChangedBroadcast(mediaStatus, replacing,
15381                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15382    }
15383
15384    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15385            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15386        int size = pkgList.length;
15387        if (size > 0) {
15388            // Send broadcasts here
15389            Bundle extras = new Bundle();
15390            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15391            if (uidArr != null) {
15392                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15393            }
15394            if (replacing) {
15395                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15396            }
15397            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15398                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15399            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15400        }
15401    }
15402
15403   /*
15404     * Look at potentially valid container ids from processCids If package
15405     * information doesn't match the one on record or package scanning fails,
15406     * the cid is added to list of removeCids. We currently don't delete stale
15407     * containers.
15408     */
15409    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15410        ArrayList<String> pkgList = new ArrayList<String>();
15411        Set<AsecInstallArgs> keys = processCids.keySet();
15412
15413        for (AsecInstallArgs args : keys) {
15414            String codePath = processCids.get(args);
15415            if (DEBUG_SD_INSTALL)
15416                Log.i(TAG, "Loading container : " + args.cid);
15417            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15418            try {
15419                // Make sure there are no container errors first.
15420                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15421                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15422                            + " when installing from sdcard");
15423                    continue;
15424                }
15425                // Check code path here.
15426                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15427                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15428                            + " does not match one in settings " + codePath);
15429                    continue;
15430                }
15431                // Parse package
15432                int parseFlags = mDefParseFlags;
15433                if (args.isExternalAsec()) {
15434                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15435                }
15436                if (args.isFwdLocked()) {
15437                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15438                }
15439
15440                synchronized (mInstallLock) {
15441                    PackageParser.Package pkg = null;
15442                    try {
15443                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15444                    } catch (PackageManagerException e) {
15445                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15446                    }
15447                    // Scan the package
15448                    if (pkg != null) {
15449                        /*
15450                         * TODO why is the lock being held? doPostInstall is
15451                         * called in other places without the lock. This needs
15452                         * to be straightened out.
15453                         */
15454                        // writer
15455                        synchronized (mPackages) {
15456                            retCode = PackageManager.INSTALL_SUCCEEDED;
15457                            pkgList.add(pkg.packageName);
15458                            // Post process args
15459                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15460                                    pkg.applicationInfo.uid);
15461                        }
15462                    } else {
15463                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15464                    }
15465                }
15466
15467            } finally {
15468                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15469                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15470                }
15471            }
15472        }
15473        // writer
15474        synchronized (mPackages) {
15475            // If the platform SDK has changed since the last time we booted,
15476            // we need to re-grant app permission to catch any new ones that
15477            // appear. This is really a hack, and means that apps can in some
15478            // cases get permissions that the user didn't initially explicitly
15479            // allow... it would be nice to have some better way to handle
15480            // this situation.
15481            final VersionInfo ver = mSettings.getExternalVersion();
15482
15483            int updateFlags = UPDATE_PERMISSIONS_ALL;
15484            if (ver.sdkVersion != mSdkVersion) {
15485                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15486                        + mSdkVersion + "; regranting permissions for external");
15487                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15488            }
15489            updatePermissionsLPw(null, null, updateFlags);
15490
15491            // Yay, everything is now upgraded
15492            ver.forceCurrent();
15493
15494            // can downgrade to reader
15495            // Persist settings
15496            mSettings.writeLPr();
15497        }
15498        // Send a broadcast to let everyone know we are done processing
15499        if (pkgList.size() > 0) {
15500            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15501        }
15502    }
15503
15504   /*
15505     * Utility method to unload a list of specified containers
15506     */
15507    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15508        // Just unmount all valid containers.
15509        for (AsecInstallArgs arg : cidArgs) {
15510            synchronized (mInstallLock) {
15511                arg.doPostDeleteLI(false);
15512           }
15513       }
15514   }
15515
15516    /*
15517     * Unload packages mounted on external media. This involves deleting package
15518     * data from internal structures, sending broadcasts about diabled packages,
15519     * gc'ing to free up references, unmounting all secure containers
15520     * corresponding to packages on external media, and posting a
15521     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15522     * that we always have to post this message if status has been requested no
15523     * matter what.
15524     */
15525    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15526            final boolean reportStatus) {
15527        if (DEBUG_SD_INSTALL)
15528            Log.i(TAG, "unloading media packages");
15529        ArrayList<String> pkgList = new ArrayList<String>();
15530        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15531        final Set<AsecInstallArgs> keys = processCids.keySet();
15532        for (AsecInstallArgs args : keys) {
15533            String pkgName = args.getPackageName();
15534            if (DEBUG_SD_INSTALL)
15535                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15536            // Delete package internally
15537            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15538            synchronized (mInstallLock) {
15539                boolean res = deletePackageLI(pkgName, null, false, null, null,
15540                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15541                if (res) {
15542                    pkgList.add(pkgName);
15543                } else {
15544                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15545                    failedList.add(args);
15546                }
15547            }
15548        }
15549
15550        // reader
15551        synchronized (mPackages) {
15552            // We didn't update the settings after removing each package;
15553            // write them now for all packages.
15554            mSettings.writeLPr();
15555        }
15556
15557        // We have to absolutely send UPDATED_MEDIA_STATUS only
15558        // after confirming that all the receivers processed the ordered
15559        // broadcast when packages get disabled, force a gc to clean things up.
15560        // and unload all the containers.
15561        if (pkgList.size() > 0) {
15562            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15563                    new IIntentReceiver.Stub() {
15564                public void performReceive(Intent intent, int resultCode, String data,
15565                        Bundle extras, boolean ordered, boolean sticky,
15566                        int sendingUser) throws RemoteException {
15567                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15568                            reportStatus ? 1 : 0, 1, keys);
15569                    mHandler.sendMessage(msg);
15570                }
15571            });
15572        } else {
15573            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15574                    keys);
15575            mHandler.sendMessage(msg);
15576        }
15577    }
15578
15579    private void loadPrivatePackages(VolumeInfo vol) {
15580        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15581        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15582        synchronized (mInstallLock) {
15583        synchronized (mPackages) {
15584            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15585            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15586            for (PackageSetting ps : packages) {
15587                final PackageParser.Package pkg;
15588                try {
15589                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15590                    loaded.add(pkg.applicationInfo);
15591                } catch (PackageManagerException e) {
15592                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15593                }
15594
15595                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15596                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15597                }
15598            }
15599
15600            int updateFlags = UPDATE_PERMISSIONS_ALL;
15601            if (ver.sdkVersion != mSdkVersion) {
15602                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15603                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15604                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15605            }
15606            updatePermissionsLPw(null, null, updateFlags);
15607
15608            // Yay, everything is now upgraded
15609            ver.forceCurrent();
15610
15611            mSettings.writeLPr();
15612        }
15613        }
15614
15615        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15616        sendResourcesChangedBroadcast(true, false, loaded, null);
15617    }
15618
15619    private void unloadPrivatePackages(VolumeInfo vol) {
15620        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15621        synchronized (mInstallLock) {
15622        synchronized (mPackages) {
15623            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15624            for (PackageSetting ps : packages) {
15625                if (ps.pkg == null) continue;
15626
15627                final ApplicationInfo info = ps.pkg.applicationInfo;
15628                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15629                if (deletePackageLI(ps.name, null, false, null, null,
15630                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15631                    unloaded.add(info);
15632                } else {
15633                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15634                }
15635            }
15636
15637            mSettings.writeLPr();
15638        }
15639        }
15640
15641        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15642        sendResourcesChangedBroadcast(false, false, unloaded, null);
15643    }
15644
15645    /**
15646     * Examine all users present on given mounted volume, and destroy data
15647     * belonging to users that are no longer valid, or whose user ID has been
15648     * recycled.
15649     */
15650    private void reconcileUsers(String volumeUuid) {
15651        final File[] files = FileUtils
15652                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15653        for (File file : files) {
15654            if (!file.isDirectory()) continue;
15655
15656            final int userId;
15657            final UserInfo info;
15658            try {
15659                userId = Integer.parseInt(file.getName());
15660                info = sUserManager.getUserInfo(userId);
15661            } catch (NumberFormatException e) {
15662                Slog.w(TAG, "Invalid user directory " + file);
15663                continue;
15664            }
15665
15666            boolean destroyUser = false;
15667            if (info == null) {
15668                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15669                        + " because no matching user was found");
15670                destroyUser = true;
15671            } else {
15672                try {
15673                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15674                } catch (IOException e) {
15675                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15676                            + " because we failed to enforce serial number: " + e);
15677                    destroyUser = true;
15678                }
15679            }
15680
15681            if (destroyUser) {
15682                synchronized (mInstallLock) {
15683                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15684                }
15685            }
15686        }
15687
15688        final UserManager um = mContext.getSystemService(UserManager.class);
15689        for (UserInfo user : um.getUsers()) {
15690            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15691            if (userDir.exists()) continue;
15692
15693            try {
15694                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15695                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15696            } catch (IOException e) {
15697                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15698            }
15699        }
15700    }
15701
15702    /**
15703     * Examine all apps present on given mounted volume, and destroy apps that
15704     * aren't expected, either due to uninstallation or reinstallation on
15705     * another volume.
15706     */
15707    private void reconcileApps(String volumeUuid) {
15708        final File[] files = FileUtils
15709                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15710        for (File file : files) {
15711            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15712                    && !PackageInstallerService.isStageName(file.getName());
15713            if (!isPackage) {
15714                // Ignore entries which are not packages
15715                continue;
15716            }
15717
15718            boolean destroyApp = false;
15719            String packageName = null;
15720            try {
15721                final PackageLite pkg = PackageParser.parsePackageLite(file,
15722                        PackageParser.PARSE_MUST_BE_APK);
15723                packageName = pkg.packageName;
15724
15725                synchronized (mPackages) {
15726                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15727                    if (ps == null) {
15728                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15729                                + volumeUuid + " because we found no install record");
15730                        destroyApp = true;
15731                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15732                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15733                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15734                        destroyApp = true;
15735                    }
15736                }
15737
15738            } catch (PackageParserException e) {
15739                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15740                destroyApp = true;
15741            }
15742
15743            if (destroyApp) {
15744                synchronized (mInstallLock) {
15745                    if (packageName != null) {
15746                        removeDataDirsLI(volumeUuid, packageName);
15747                    }
15748                    if (file.isDirectory()) {
15749                        mInstaller.rmPackageDir(file.getAbsolutePath());
15750                    } else {
15751                        file.delete();
15752                    }
15753                }
15754            }
15755        }
15756    }
15757
15758    private void unfreezePackage(String packageName) {
15759        synchronized (mPackages) {
15760            final PackageSetting ps = mSettings.mPackages.get(packageName);
15761            if (ps != null) {
15762                ps.frozen = false;
15763            }
15764        }
15765    }
15766
15767    @Override
15768    public int movePackage(final String packageName, final String volumeUuid) {
15769        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15770
15771        final int moveId = mNextMoveId.getAndIncrement();
15772        try {
15773            movePackageInternal(packageName, volumeUuid, moveId);
15774        } catch (PackageManagerException e) {
15775            Slog.w(TAG, "Failed to move " + packageName, e);
15776            mMoveCallbacks.notifyStatusChanged(moveId,
15777                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15778        }
15779        return moveId;
15780    }
15781
15782    private void movePackageInternal(final String packageName, final String volumeUuid,
15783            final int moveId) throws PackageManagerException {
15784        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15785        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15786        final PackageManager pm = mContext.getPackageManager();
15787
15788        final boolean currentAsec;
15789        final String currentVolumeUuid;
15790        final File codeFile;
15791        final String installerPackageName;
15792        final String packageAbiOverride;
15793        final int appId;
15794        final String seinfo;
15795        final String label;
15796
15797        // reader
15798        synchronized (mPackages) {
15799            final PackageParser.Package pkg = mPackages.get(packageName);
15800            final PackageSetting ps = mSettings.mPackages.get(packageName);
15801            if (pkg == null || ps == null) {
15802                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15803            }
15804
15805            if (pkg.applicationInfo.isSystemApp()) {
15806                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15807                        "Cannot move system application");
15808            }
15809
15810            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15811                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15812                        "Package already moved to " + volumeUuid);
15813            }
15814
15815            final File probe = new File(pkg.codePath);
15816            final File probeOat = new File(probe, "oat");
15817            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15818                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15819                        "Move only supported for modern cluster style installs");
15820            }
15821
15822            if (ps.frozen) {
15823                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15824                        "Failed to move already frozen package");
15825            }
15826            ps.frozen = true;
15827
15828            currentAsec = pkg.applicationInfo.isForwardLocked()
15829                    || pkg.applicationInfo.isExternalAsec();
15830            currentVolumeUuid = ps.volumeUuid;
15831            codeFile = new File(pkg.codePath);
15832            installerPackageName = ps.installerPackageName;
15833            packageAbiOverride = ps.cpuAbiOverrideString;
15834            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15835            seinfo = pkg.applicationInfo.seinfo;
15836            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15837        }
15838
15839        // Now that we're guarded by frozen state, kill app during move
15840        final long token = Binder.clearCallingIdentity();
15841        try {
15842            killApplication(packageName, appId, "move pkg");
15843        } finally {
15844            Binder.restoreCallingIdentity(token);
15845        }
15846
15847        final Bundle extras = new Bundle();
15848        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15849        extras.putString(Intent.EXTRA_TITLE, label);
15850        mMoveCallbacks.notifyCreated(moveId, extras);
15851
15852        int installFlags;
15853        final boolean moveCompleteApp;
15854        final File measurePath;
15855
15856        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15857            installFlags = INSTALL_INTERNAL;
15858            moveCompleteApp = !currentAsec;
15859            measurePath = Environment.getDataAppDirectory(volumeUuid);
15860        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15861            installFlags = INSTALL_EXTERNAL;
15862            moveCompleteApp = false;
15863            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15864        } else {
15865            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15866            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15867                    || !volume.isMountedWritable()) {
15868                unfreezePackage(packageName);
15869                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15870                        "Move location not mounted private volume");
15871            }
15872
15873            Preconditions.checkState(!currentAsec);
15874
15875            installFlags = INSTALL_INTERNAL;
15876            moveCompleteApp = true;
15877            measurePath = Environment.getDataAppDirectory(volumeUuid);
15878        }
15879
15880        final PackageStats stats = new PackageStats(null, -1);
15881        synchronized (mInstaller) {
15882            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15883                unfreezePackage(packageName);
15884                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15885                        "Failed to measure package size");
15886            }
15887        }
15888
15889        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15890                + stats.dataSize);
15891
15892        final long startFreeBytes = measurePath.getFreeSpace();
15893        final long sizeBytes;
15894        if (moveCompleteApp) {
15895            sizeBytes = stats.codeSize + stats.dataSize;
15896        } else {
15897            sizeBytes = stats.codeSize;
15898        }
15899
15900        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15901            unfreezePackage(packageName);
15902            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15903                    "Not enough free space to move");
15904        }
15905
15906        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15907
15908        final CountDownLatch installedLatch = new CountDownLatch(1);
15909        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15910            @Override
15911            public void onUserActionRequired(Intent intent) throws RemoteException {
15912                throw new IllegalStateException();
15913            }
15914
15915            @Override
15916            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15917                    Bundle extras) throws RemoteException {
15918                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15919                        + PackageManager.installStatusToString(returnCode, msg));
15920
15921                installedLatch.countDown();
15922
15923                // Regardless of success or failure of the move operation,
15924                // always unfreeze the package
15925                unfreezePackage(packageName);
15926
15927                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15928                switch (status) {
15929                    case PackageInstaller.STATUS_SUCCESS:
15930                        mMoveCallbacks.notifyStatusChanged(moveId,
15931                                PackageManager.MOVE_SUCCEEDED);
15932                        break;
15933                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15934                        mMoveCallbacks.notifyStatusChanged(moveId,
15935                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15936                        break;
15937                    default:
15938                        mMoveCallbacks.notifyStatusChanged(moveId,
15939                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15940                        break;
15941                }
15942            }
15943        };
15944
15945        final MoveInfo move;
15946        if (moveCompleteApp) {
15947            // Kick off a thread to report progress estimates
15948            new Thread() {
15949                @Override
15950                public void run() {
15951                    while (true) {
15952                        try {
15953                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15954                                break;
15955                            }
15956                        } catch (InterruptedException ignored) {
15957                        }
15958
15959                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15960                        final int progress = 10 + (int) MathUtils.constrain(
15961                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15962                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15963                    }
15964                }
15965            }.start();
15966
15967            final String dataAppName = codeFile.getName();
15968            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15969                    dataAppName, appId, seinfo);
15970        } else {
15971            move = null;
15972        }
15973
15974        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15975
15976        final Message msg = mHandler.obtainMessage(INIT_COPY);
15977        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15978        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15979                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15980        mHandler.sendMessage(msg);
15981    }
15982
15983    @Override
15984    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15985        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15986
15987        final int realMoveId = mNextMoveId.getAndIncrement();
15988        final Bundle extras = new Bundle();
15989        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15990        mMoveCallbacks.notifyCreated(realMoveId, extras);
15991
15992        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15993            @Override
15994            public void onCreated(int moveId, Bundle extras) {
15995                // Ignored
15996            }
15997
15998            @Override
15999            public void onStatusChanged(int moveId, int status, long estMillis) {
16000                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16001            }
16002        };
16003
16004        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16005        storage.setPrimaryStorageUuid(volumeUuid, callback);
16006        return realMoveId;
16007    }
16008
16009    @Override
16010    public int getMoveStatus(int moveId) {
16011        mContext.enforceCallingOrSelfPermission(
16012                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16013        return mMoveCallbacks.mLastStatus.get(moveId);
16014    }
16015
16016    @Override
16017    public void registerMoveCallback(IPackageMoveObserver callback) {
16018        mContext.enforceCallingOrSelfPermission(
16019                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16020        mMoveCallbacks.register(callback);
16021    }
16022
16023    @Override
16024    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16025        mContext.enforceCallingOrSelfPermission(
16026                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16027        mMoveCallbacks.unregister(callback);
16028    }
16029
16030    @Override
16031    public boolean setInstallLocation(int loc) {
16032        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16033                null);
16034        if (getInstallLocation() == loc) {
16035            return true;
16036        }
16037        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16038                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16039            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16040                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16041            return true;
16042        }
16043        return false;
16044   }
16045
16046    @Override
16047    public int getInstallLocation() {
16048        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16049                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16050                PackageHelper.APP_INSTALL_AUTO);
16051    }
16052
16053    /** Called by UserManagerService */
16054    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16055        mDirtyUsers.remove(userHandle);
16056        mSettings.removeUserLPw(userHandle);
16057        mPendingBroadcasts.remove(userHandle);
16058        if (mInstaller != null) {
16059            // Technically, we shouldn't be doing this with the package lock
16060            // held.  However, this is very rare, and there is already so much
16061            // other disk I/O going on, that we'll let it slide for now.
16062            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16063            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16064                final String volumeUuid = vol.getFsUuid();
16065                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16066                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16067            }
16068        }
16069        mUserNeedsBadging.delete(userHandle);
16070        removeUnusedPackagesLILPw(userManager, userHandle);
16071    }
16072
16073    /**
16074     * We're removing userHandle and would like to remove any downloaded packages
16075     * that are no longer in use by any other user.
16076     * @param userHandle the user being removed
16077     */
16078    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16079        final boolean DEBUG_CLEAN_APKS = false;
16080        int [] users = userManager.getUserIdsLPr();
16081        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16082        while (psit.hasNext()) {
16083            PackageSetting ps = psit.next();
16084            if (ps.pkg == null) {
16085                continue;
16086            }
16087            final String packageName = ps.pkg.packageName;
16088            // Skip over if system app
16089            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16090                continue;
16091            }
16092            if (DEBUG_CLEAN_APKS) {
16093                Slog.i(TAG, "Checking package " + packageName);
16094            }
16095            boolean keep = false;
16096            for (int i = 0; i < users.length; i++) {
16097                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16098                    keep = true;
16099                    if (DEBUG_CLEAN_APKS) {
16100                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16101                                + users[i]);
16102                    }
16103                    break;
16104                }
16105            }
16106            if (!keep) {
16107                if (DEBUG_CLEAN_APKS) {
16108                    Slog.i(TAG, "  Removing package " + packageName);
16109                }
16110                mHandler.post(new Runnable() {
16111                    public void run() {
16112                        deletePackageX(packageName, userHandle, 0);
16113                    } //end run
16114                });
16115            }
16116        }
16117    }
16118
16119    /** Called by UserManagerService */
16120    void createNewUserLILPw(int userHandle) {
16121        if (mInstaller != null) {
16122            mInstaller.createUserConfig(userHandle);
16123            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16124            applyFactoryDefaultBrowserLPw(userHandle);
16125            primeDomainVerificationsLPw(userHandle);
16126        }
16127    }
16128
16129    void newUserCreated(final int userHandle) {
16130        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16131    }
16132
16133    @Override
16134    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16135        mContext.enforceCallingOrSelfPermission(
16136                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16137                "Only package verification agents can read the verifier device identity");
16138
16139        synchronized (mPackages) {
16140            return mSettings.getVerifierDeviceIdentityLPw();
16141        }
16142    }
16143
16144    @Override
16145    public void setPermissionEnforced(String permission, boolean enforced) {
16146        // TODO: Now that we no longer change GID for storage, this should to away.
16147        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16148                "setPermissionEnforced");
16149        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16150            synchronized (mPackages) {
16151                if (mSettings.mReadExternalStorageEnforced == null
16152                        || mSettings.mReadExternalStorageEnforced != enforced) {
16153                    mSettings.mReadExternalStorageEnforced = enforced;
16154                    mSettings.writeLPr();
16155                }
16156            }
16157            // kill any non-foreground processes so we restart them and
16158            // grant/revoke the GID.
16159            final IActivityManager am = ActivityManagerNative.getDefault();
16160            if (am != null) {
16161                final long token = Binder.clearCallingIdentity();
16162                try {
16163                    am.killProcessesBelowForeground("setPermissionEnforcement");
16164                } catch (RemoteException e) {
16165                } finally {
16166                    Binder.restoreCallingIdentity(token);
16167                }
16168            }
16169        } else {
16170            throw new IllegalArgumentException("No selective enforcement for " + permission);
16171        }
16172    }
16173
16174    @Override
16175    @Deprecated
16176    public boolean isPermissionEnforced(String permission) {
16177        return true;
16178    }
16179
16180    @Override
16181    public boolean isStorageLow() {
16182        final long token = Binder.clearCallingIdentity();
16183        try {
16184            final DeviceStorageMonitorInternal
16185                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16186            if (dsm != null) {
16187                return dsm.isMemoryLow();
16188            } else {
16189                return false;
16190            }
16191        } finally {
16192            Binder.restoreCallingIdentity(token);
16193        }
16194    }
16195
16196    @Override
16197    public IPackageInstaller getPackageInstaller() {
16198        return mInstallerService;
16199    }
16200
16201    private boolean userNeedsBadging(int userId) {
16202        int index = mUserNeedsBadging.indexOfKey(userId);
16203        if (index < 0) {
16204            final UserInfo userInfo;
16205            final long token = Binder.clearCallingIdentity();
16206            try {
16207                userInfo = sUserManager.getUserInfo(userId);
16208            } finally {
16209                Binder.restoreCallingIdentity(token);
16210            }
16211            final boolean b;
16212            if (userInfo != null && userInfo.isManagedProfile()) {
16213                b = true;
16214            } else {
16215                b = false;
16216            }
16217            mUserNeedsBadging.put(userId, b);
16218            return b;
16219        }
16220        return mUserNeedsBadging.valueAt(index);
16221    }
16222
16223    @Override
16224    public KeySet getKeySetByAlias(String packageName, String alias) {
16225        if (packageName == null || alias == null) {
16226            return null;
16227        }
16228        synchronized(mPackages) {
16229            final PackageParser.Package pkg = mPackages.get(packageName);
16230            if (pkg == null) {
16231                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16232                throw new IllegalArgumentException("Unknown package: " + packageName);
16233            }
16234            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16235            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16236        }
16237    }
16238
16239    @Override
16240    public KeySet getSigningKeySet(String packageName) {
16241        if (packageName == null) {
16242            return null;
16243        }
16244        synchronized(mPackages) {
16245            final PackageParser.Package pkg = mPackages.get(packageName);
16246            if (pkg == null) {
16247                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16248                throw new IllegalArgumentException("Unknown package: " + packageName);
16249            }
16250            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16251                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16252                throw new SecurityException("May not access signing KeySet of other apps.");
16253            }
16254            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16255            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16256        }
16257    }
16258
16259    @Override
16260    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16261        if (packageName == null || ks == null) {
16262            return false;
16263        }
16264        synchronized(mPackages) {
16265            final PackageParser.Package pkg = mPackages.get(packageName);
16266            if (pkg == null) {
16267                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16268                throw new IllegalArgumentException("Unknown package: " + packageName);
16269            }
16270            IBinder ksh = ks.getToken();
16271            if (ksh instanceof KeySetHandle) {
16272                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16273                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16274            }
16275            return false;
16276        }
16277    }
16278
16279    @Override
16280    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16281        if (packageName == null || ks == null) {
16282            return false;
16283        }
16284        synchronized(mPackages) {
16285            final PackageParser.Package pkg = mPackages.get(packageName);
16286            if (pkg == null) {
16287                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16288                throw new IllegalArgumentException("Unknown package: " + packageName);
16289            }
16290            IBinder ksh = ks.getToken();
16291            if (ksh instanceof KeySetHandle) {
16292                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16293                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16294            }
16295            return false;
16296        }
16297    }
16298
16299    public void getUsageStatsIfNoPackageUsageInfo() {
16300        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16301            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16302            if (usm == null) {
16303                throw new IllegalStateException("UsageStatsManager must be initialized");
16304            }
16305            long now = System.currentTimeMillis();
16306            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16307            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16308                String packageName = entry.getKey();
16309                PackageParser.Package pkg = mPackages.get(packageName);
16310                if (pkg == null) {
16311                    continue;
16312                }
16313                UsageStats usage = entry.getValue();
16314                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16315                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16316            }
16317        }
16318    }
16319
16320    /**
16321     * Check and throw if the given before/after packages would be considered a
16322     * downgrade.
16323     */
16324    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16325            throws PackageManagerException {
16326        if (after.versionCode < before.mVersionCode) {
16327            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16328                    "Update version code " + after.versionCode + " is older than current "
16329                    + before.mVersionCode);
16330        } else if (after.versionCode == before.mVersionCode) {
16331            if (after.baseRevisionCode < before.baseRevisionCode) {
16332                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16333                        "Update base revision code " + after.baseRevisionCode
16334                        + " is older than current " + before.baseRevisionCode);
16335            }
16336
16337            if (!ArrayUtils.isEmpty(after.splitNames)) {
16338                for (int i = 0; i < after.splitNames.length; i++) {
16339                    final String splitName = after.splitNames[i];
16340                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16341                    if (j != -1) {
16342                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16343                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16344                                    "Update split " + splitName + " revision code "
16345                                    + after.splitRevisionCodes[i] + " is older than current "
16346                                    + before.splitRevisionCodes[j]);
16347                        }
16348                    }
16349                }
16350            }
16351        }
16352    }
16353
16354    private static class MoveCallbacks extends Handler {
16355        private static final int MSG_CREATED = 1;
16356        private static final int MSG_STATUS_CHANGED = 2;
16357
16358        private final RemoteCallbackList<IPackageMoveObserver>
16359                mCallbacks = new RemoteCallbackList<>();
16360
16361        private final SparseIntArray mLastStatus = new SparseIntArray();
16362
16363        public MoveCallbacks(Looper looper) {
16364            super(looper);
16365        }
16366
16367        public void register(IPackageMoveObserver callback) {
16368            mCallbacks.register(callback);
16369        }
16370
16371        public void unregister(IPackageMoveObserver callback) {
16372            mCallbacks.unregister(callback);
16373        }
16374
16375        @Override
16376        public void handleMessage(Message msg) {
16377            final SomeArgs args = (SomeArgs) msg.obj;
16378            final int n = mCallbacks.beginBroadcast();
16379            for (int i = 0; i < n; i++) {
16380                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16381                try {
16382                    invokeCallback(callback, msg.what, args);
16383                } catch (RemoteException ignored) {
16384                }
16385            }
16386            mCallbacks.finishBroadcast();
16387            args.recycle();
16388        }
16389
16390        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16391                throws RemoteException {
16392            switch (what) {
16393                case MSG_CREATED: {
16394                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16395                    break;
16396                }
16397                case MSG_STATUS_CHANGED: {
16398                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16399                    break;
16400                }
16401            }
16402        }
16403
16404        private void notifyCreated(int moveId, Bundle extras) {
16405            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16406
16407            final SomeArgs args = SomeArgs.obtain();
16408            args.argi1 = moveId;
16409            args.arg2 = extras;
16410            obtainMessage(MSG_CREATED, args).sendToTarget();
16411        }
16412
16413        private void notifyStatusChanged(int moveId, int status) {
16414            notifyStatusChanged(moveId, status, -1);
16415        }
16416
16417        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16418            Slog.v(TAG, "Move " + moveId + " status " + status);
16419
16420            final SomeArgs args = SomeArgs.obtain();
16421            args.argi1 = moveId;
16422            args.argi2 = status;
16423            args.arg3 = estMillis;
16424            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16425
16426            synchronized (mLastStatus) {
16427                mLastStatus.put(moveId, status);
16428            }
16429        }
16430    }
16431
16432    private final class OnPermissionChangeListeners extends Handler {
16433        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16434
16435        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16436                new RemoteCallbackList<>();
16437
16438        public OnPermissionChangeListeners(Looper looper) {
16439            super(looper);
16440        }
16441
16442        @Override
16443        public void handleMessage(Message msg) {
16444            switch (msg.what) {
16445                case MSG_ON_PERMISSIONS_CHANGED: {
16446                    final int uid = msg.arg1;
16447                    handleOnPermissionsChanged(uid);
16448                } break;
16449            }
16450        }
16451
16452        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16453            mPermissionListeners.register(listener);
16454
16455        }
16456
16457        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16458            mPermissionListeners.unregister(listener);
16459        }
16460
16461        public void onPermissionsChanged(int uid) {
16462            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16463                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16464            }
16465        }
16466
16467        private void handleOnPermissionsChanged(int uid) {
16468            final int count = mPermissionListeners.beginBroadcast();
16469            try {
16470                for (int i = 0; i < count; i++) {
16471                    IOnPermissionsChangeListener callback = mPermissionListeners
16472                            .getBroadcastItem(i);
16473                    try {
16474                        callback.onPermissionsChanged(uid);
16475                    } catch (RemoteException e) {
16476                        Log.e(TAG, "Permission listener is dead", e);
16477                    }
16478                }
16479            } finally {
16480                mPermissionListeners.finishBroadcast();
16481            }
16482        }
16483    }
16484
16485    private class PackageManagerInternalImpl extends PackageManagerInternal {
16486        @Override
16487        public void setLocationPackagesProvider(PackagesProvider provider) {
16488            synchronized (mPackages) {
16489                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16490            }
16491        }
16492
16493        @Override
16494        public void setImePackagesProvider(PackagesProvider provider) {
16495            synchronized (mPackages) {
16496                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16497            }
16498        }
16499
16500        @Override
16501        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16502            synchronized (mPackages) {
16503                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16504            }
16505        }
16506
16507        @Override
16508        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16509            synchronized (mPackages) {
16510                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16511            }
16512        }
16513
16514        @Override
16515        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16516            synchronized (mPackages) {
16517                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16518            }
16519        }
16520
16521        @Override
16522        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16523            synchronized (mPackages) {
16524                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16525            }
16526        }
16527
16528        @Override
16529        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16530            synchronized (mPackages) {
16531                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16532                        packageName, userId);
16533            }
16534        }
16535
16536        @Override
16537        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16538            synchronized (mPackages) {
16539                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16540                        packageName, userId);
16541            }
16542        }
16543    }
16544
16545    @Override
16546    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16547        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16548        synchronized (mPackages) {
16549            final long identity = Binder.clearCallingIdentity();
16550            try {
16551                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16552                        packageNames, userId);
16553            } finally {
16554                Binder.restoreCallingIdentity(identity);
16555            }
16556        }
16557    }
16558
16559    private static void enforceSystemOrPhoneCaller(String tag) {
16560        int callingUid = Binder.getCallingUid();
16561        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16562            throw new SecurityException(
16563                    "Cannot call " + tag + " from UID " + callingUid);
16564        }
16565    }
16566}
16567